all array elements are the same fgets in C?

fscanf
fgetc in c
fgets c stdin
fputs in c
scanf(''%c)
fgets implementation in c
fgets vs scanf
fgets into array

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

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.

fgets() and gets() in C language, Here, we will see what is the difference between gets() and fgets(). char *fgets( char *str, int n, FILE *stream) str : Pointer to an array of chars 15 characters, gets() will read all these characters and store them into variable. Program to Print Elements in an Array using Functions. This program to print an array in c is the same as the first example. However, we separated the logic to print array elements using Functions.

Given this code:

char buffer[32];

How many buffer variables are there?

One.

So this code

array[i] = buffer;

points every char * element of array at the ONE buffer.

(One fix is to do @Jabberwocky posted in his answer - use strdup())

fgets() Function in C, The syntax of the fgets() function is: Syntax: char *fgets(char *str, int n, FILE In line 6, an array of characters str of size 50 is declared. Apart from this the most important difference is this: Intro to C Programming � Installing Code Blocks � Creating and Running The First C Program � Basic Elements of a C� fgets(string,size,stdin); In this example, string is the name of a char array, a string variable; size is the amount of text to input plus one, which should be the same size as the char array; and stdin is the name of the standard input device, as defined in the stdio.h header file. THE FGETS() FUNCTION READS A STRING

char *array[32];
char buffer[32];
....    
while(fgets(buffer, 32, fp)){
    array[i] = buffer;
....

Look at your variables: first one is array of 32 char* pointers, the second one is a 32 char array. In while loop, you also just assign each & every element on the array to the same buffer. Do you see? While fgets just keeps re-freshing / updating that buffer with latest data.

How to use the fgets() function in C, fgets is safe to use in comparison to gets since it checks for character array str bounds. gets keeps on reading characters from the users, until a newline character� Write a C program to input elements in an array and find the sum of array elements using loop. C program to find sum of elements of an array. How to add elements of an array using for loop in C programming. Logic to find sum of array elements in C programming.

fgets() and gets() in C, It checks array bound and it is safe too. Here is the syntax of fgets() in C language , char *fgets(char *string, int value, FILE *stream). C Program to find the sum of all array elements – In this article, we will detail in on all the ways to find the sum of all array elements in C programming. Suitable examples and sample programs have also been added so that you can understand the whole thing very clearly. The compiler has

How to Use the fgets() Function for Text Input in C Programming , For a general-purpose text input function in the C programming language, one that reads That's how programmers talk after an all-nighter. which should be the same size as the char array; and stdin is the name of the standard input device� Length of array pair formed where one contains all distinct elements and other all same elements; Count of Array elements to be divided by 2 to make at least K elements equal; Reduce the array by deleting elements which are greater than all elements to its left; Maximize sum of atmost K elements in array by taking only corner elements | Set 2

C Strings, Note that along with C-style strings, which are arrays, there are also string The only difference is that you cannot modify string literals, whereas you can modify arrays. Notice that fgets may fill up the entire space allocated for str, but it will never used to pass their addresses, so the values in the array string are modified. So, I suggest you refer the same in C Programming for better understanding. Program to find Sum of all Elements in an Array using While Loop. This C program is the same as above, but this time we used While Loop to perform the One Dimensional Array addition

Comments
  • array[i] = buffer; just assigns the very same pointer to all elements of array. You need dynamic memory allocation here or maybe a 2d array of char.
  • use strcpy instead of assign string.
  • @aragon use strcpy instead of assign string No. Do not do that. The pointers in array refer to fixed-length, possibly read-only constant string literals.
  • Now you left out the return statement. One of those days? :-)