Home > Back-end >  Function to modify all elements instead of one in C
Function to modify all elements instead of one in C

Time:10-02

I'm very bad with C. I have to create a function that saves a name from a file into an array. My code seems like it is working, but when I printf at the end of the function, all elements are the last name on the list.

void Names(char *Txt, char **Array) {
  FILE *Text;
  Text = fopen(Txt, "r");
  int a = 0;
  int Buffer = 150;
  char string[150];
  char Buff[25];
  while (fgets(string, Buffer, Text) != NULL) {
    strcpy(Buff, strtok(string, " ,\n"));
    Array[a] = Buff;
        printf("%s\n;Array[a]);
        a  ;
  }
  int c = 0;
  while (c < a) {
        printf("%s\n", Array[c]);
        c  ;
  }
}

The first while prints all names like it should, but the second doesn't.

The first one prints name1,name2,name3,name4, and the second one prints name4,name4,name4,name4.

CodePudding user response:

You just assign pointer to buff here

Array[a]=Buff

That is you have ptr to Buff in every Array element. You must allocate new array to Array[n] instead of use Buff.

strcpy(Buff,strtok(string," ,\n")); Array[a]=Buff;

Remove Buff var and replace this piece by

Array[a] = (char*)malloc(sizeof(char) * 25);
strcopy(Array[a], strtok(string," ,\n"));

It could help.

  •  Tags:  
  • c
  • Related