2012-03-17 6 views
8

Ricevo un buffer char * che ha la lunghezza di 10. Ma voglio concatenare l'intero contenuto nella mia struct che ha una variabile char *.Come concatere due caratteri * in C?

typedef struct{ 
    char *buffer; 
    //.. 

}file_entry; 

file_entry real[128]; 

int fs_write(char *buffer, int size, int file) { 
    //every time this function is called buffer have 10 of lenght only 
    // I want to concat the whole text in my char* in my struct 
} 

Qualcosa di simile a questo:

real[i].buffer += buffer; 

Come posso fare questo in C?

risposta

10

In generale, effettuare le seguenti operazioni (regolare e aggiungere il controllo degli errori, come si vede in forma)

// real[i].buffer += buffer; 

    // Determine new size 
    int newSize = strlen(real[i].buffer) + strlen(buffer) + 1; 

    // Allocate new buffer 
    char * newBuffer = (char *)malloc(newSize); 

    // do the copy and concat 
    strcpy(newBuffer,real[i].buffer); 
    strcat(newBuffer,buffer); // or strncat 

    // release old buffer 
    free(real[i].buffer); 

    // store new pointer 
    real[i].buffer = newBuffer; 
4

È possibile utilizzare strcat(3) per concatenare le stringhe. Assicurati di aver assegnato abbastanza spazio alla destinazione!

Nota che chiamare semplicemente strcat() un numero di volte risulterà in un Schlemiel the Painter's algorithm. Tenere traccia della lunghezza totale nella tua struttura (o altrove, se preferisci) ti aiuterà in questo.

+0

Usa sempre 'strncat' (incluso anche nel link sopra) e non' strcat'. – pickypg

+3

Sempre? Sembra un po 'pesante. "Stai attento" è sempre un buon consiglio, però - sono d'accordo. Ecco una domanda e alcune risposte su quando utilizzare ciascuna: http://stackoverflow.com/questions/6491038/strcat-vs-strncat-when-should-which-function-be-used –

+2

Se non sai perché sei usando 'strcat', perché i due buffer sono sotto le garanzie predeterminate, allora dovresti sempre usare' strncat'. Qualcuno che inizia in C starà sempre meglio usando 'strncat' su' strcat' semplicemente perché il rischio non vale la ricompensa inosservabile. Considerando quale sia effettivamente il vantaggio, direi che non ne trarrai mai beneficio a meno che tu non stia scrivendo qualcosa di incredibilmente basso e che i controlli pre-requisito siano già stati fatti. – pickypg

0

Non sono chiaro. Vuoi:

  • per concatenare ognuno dei 10 buffer di caratteri che si ricevono in un array, indicò da uno real[0].buffer, o
  • vuoi di ogni buffer 10 carattere da puntato da un diverso real[i].buffer o
  • qualcos'altro?

Sarà necessario allocare spazio sufficiente per la copia del buffer:

#include <stdlib.h> 
//... 
int size = 10+1; // need to allocate enough space for a terminating '\0' 
char* buff = (char *)malloc(size); 
if (buff == NULL) { 
    fprintf(stderr, "Error: Failed to allocate %d bytes in file: %s, line %d\n, 
        size, __FILE__, __LINE__); 
    exit(1); 
} 
buff[0] = '\0'; // terminate the string so that strcat can work, if needed 
//... 
real[i].buffer = buff; // now buffer points at some space 
//... 
strncpy(real[i].buffer, buffer, size-1);