1

I am trying to parse an empty array of string to a function where that function fills the array with some string data. Then use the array of strings outside that function.

Below is an example code of what I'm trying to do.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define READLENGTH 155
#define READLISTLENGTH 100

void fileReader(char *readBuffer[]) {

  
  for (int i=0;i<100;i++) {
    char buffer[50];
    snprintf(buffer, 20, "hello world %d",i);
    readBuffer[i] = &buffer;
  }
}

int main()
{
    char *readBuffer[READLISTLENGTH];
    fileReader(readBuffer);
    
    for(int i = 0; i < READLISTLENGTH; i++) {
      printf("%s \n",readBuffer[i]);
    }
}

The expected output is,

hello world 0
hello world 1
hello world 2
     :
     :
hello world 99

But what I get is,

hello world 99
hello world 99
hello world 99
    :
    :
hello world 99
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • `readBuffer[i] = &buffer;` That is storing a reference to a local variable. The variable is only valid within each iteration of the loop. You need to allocate dynamic memory which will have lifetime beyond the function. e.g . `readBuffer[i] = strdup(buffer);`. Don't forget that the memory needs to be freed when no longer needed. – kaylum May 13 '21 at 11:40

1 Answers1

1

You declared an uninitialized array of pointers

char *readBuffer[READLISTLENGTH];

Within the function fileReader you are assigning the address of the same local array buffer to elements of the passed array.

char buffer[50];
snprintf(buffer, 20, "hello world %d",i);
readBuffer[i] = &buffer;

After exiting the function the elements of the array will be invalid pointers because the array buffer will not be alive.

Moreover the compiler should issue a nessage for this assignment

readBuffer[i] = &buffer;

because the types of the operands are not compatible. At least you should write

readBuffer[i] = buffer;

In any case either you need to declare a two-dimensional character array like for example

char readBuffer[READLISTLENGTH][50];

(in this case the function declarations shall be changed) or within the function fileReader you need to allocate dynamically memory for each element of the array of pointers and to copy entered strings from the local array buffer into allocated memory.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335