Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

all array elements are the same fgets in C?

So currently my program uses a hard-coded array like this:

char *array[] = {"array","ofran","domle","tters", "squar"}

Basically n strings of n length "an n*n grid. I then treat the values like a 2D array. So I will access array[y][x] and do comparison operations and math using the corresponding ASCII.

I wanted to allow text files of various sizes (n*n) (up to 32) be implemented in my program instead of hard coding it. But am having issues with using fgets.

My current function for getting and storing the file information looks like this:

char *array[32];
char buffer[32];
FILE *fp = fopen("textfile.txt","r");

int n = 0;
while(fgets(buffer, 32, fp)){
    array[i] = buffer;
    n++;
}
fclose(fp);

but all values of "array" are the same (they are the last string). So with the example values above. If I printed array[0] to array [4] I get

values from my code

squar
squar
squar
squar
squar

expected values:

array
ofran
domle
tters
squar
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

array[i] = buffer just assigns the very same pointer to all elements of array. You need dynamic memory allocation here:

char *array[32];
char buffer[32];
FILE *fp = fopen("textfile.txt","r");

int n = 0;
while(fgets(buffer, 32, fp)){
    array[i] = strdup(buffer);  // allocate memory for a new string
                                // containing a copy of the string in buffer
    n++;
}
fclose(fp);

No error checking is done here for brevity. Also if the input file contains more than 32 lines you'll run into trouble.

if strdup does not exist on your platform:

char *strdup(const char *str)
{
  char *newstring = malloc(strlen(str) + 1);  // + 1 for the NUL terminator
  if ( newstring )
    strcpy(newstring, str);
  return(newstring);
}

Again no error checking is done here for brevity.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...