Voici mon code. Je luttais pour savoir pourquoi strncpy()
ne peux pas copier la chaîne dans un struct
, puisque cela fonctionnait parfaitement dans ma précédente mission. En outre, j'ai deuxième question: supposons que j'ai un struct contient un autre struct, comment affecter la valeur à l'struct intérieur:Erreur de segmentation: 11 (causée par strncpy())
struct _field {
char fieldName[50];
char fieldType[50];
int fieldLength;
};
struct _table {
char *tableFileName;
int reclen;
int fieldcount;
struct _field fields[100];
};
typedef enum { false, true } bool;
bool loadSchema(struct _table *table) {
printf("%s\n", "*** LOG: Loading table fields...");
FILE *fp = NULL;
char lines[1000];
char s[2] = " ";
fp = fopen("in.txt", "r+");
while (fgets(lines, sizeof(lines), fp) != NULL) {
char *token;
token = strtok(lines, s);
if (token != NULL) {
if (strcmp(token, "CREATETABLE") == 0) {
token = strtok(NULL, s);
if (token != NULL) {
token[strlen(token)-1] = '\0';
strcat(token, ".bin");
//table->tableFileName = token; // this line can write the value into struct
strncpy(table->tableFileName, token, 20);// this line cant write the value into struct
}
printf("*** LOG: Table name is [%s]\n", table->tableFileName);
}
/*if (strcmp(token, "ADD") == 0) {
token = strtok(NULL, s);
if (token != NULL) {
strncpy((*table).fields. fieldName, token, 50);
}// Q2: how to give a value into a struct of a struct?
}*/
}
}
return 1;
}
fichier d'entrée ressemble à ceci:
CREATETABLE people
ADD id char 50
ADD lname char 50
O/T, mais recommandez '#include stdbool.h' plutôt que votre propre' typedef' – yano
'table-> tableFileName' pointe vers rien (ou au moins l'allocation n'est pas affichée). –
D'où vient le '20'? Ça aurait dû être un indice que vous venez de le faire sortir de nulle part. La longueur passée à strncpy doit être la taille du tampon de destination. Dans votre cas c'est 0 puisque vous n'avez jamais alloué d'espace. – stark