Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...