Store array of char pointers in C -
i'm trying read in file of text , store inside array using c function, running pointer difficulties:
the file read in format \t:
france baguette
china rice
japan sushi
etc.
my code following, shows last entry in file:
void func(char *a[]) { file *dic = fopen("dic.log", "r"); char *country = malloc(30); char *food = malloc(30); int = 0; while (fscanf(dic, "%s %s", country, food) == 2) { a[i] = country; a[i+1] = food; i+=2; } fclose(dic); } int main (int argc, char*argv) { char *b[6]; func(b); printf("%s %s\n", b[0], b[1]); printf("%s %s\n", b[2], b[3]); return 1; } i want function populate array 'b' in following manner:
b[france,baguette,china,rice,japan,sushi]
it happenimg because have allocated memory country , food once.
use malloc inside while loop allocate both of them memory individually store values.
your code like
void func(char *a[]) { file *dic = fopen("dic.log", "r"); char *country; char *food; int = 0; while (!feof(dic)) { country = (char*)malloc(30); food = (char*)malloc(30); fscanf(dic, "%s%s", country, food); a[i] = country; a[i+1] = food; i+=2; } fclose(dic); } int main (int argc, char*argv) { char *b[6]; func(b); printf("%s %s\n", b[0], b[1]); printf("%s %s\n", b[2], b[3]); return 1; }
Comments
Post a Comment