0

I want to use a C function to get an array and count with variable size (@runtime). I implement this function as following:

void getList(int **listArray, int *count){

  // get the total count
  int totalListCount = getTotalListCount();

  // Initialize the array
  int theList[totalListCount];
  memset( theList, 0, sizeof(int)*totalListCount );

  // Set the elements in the array
  for (int i = 0; i < totalListCount; i++) {
    theList[i] = theElementAtIndex(i);
  }

  // Assign the value to the pointer. 
  *count = totalListCount;
  *listArray = theList;
}

After getting the array and the count, I could print the values:

int *list;
int count;

getList(&list, &count);

for (int i = 0; i < count; i++) {
    printf("list[%d]: %d \n", i, list[i]);
}

Is the implementation correct? Do I need to manage the memory for those pointers, and how?

Mat
  • 202,337
  • 40
  • 393
  • 406
Xaree Lee
  • 3,188
  • 3
  • 34
  • 55
  • 1
    You're referring to a memory which is created on the stack which ceases to exist after the function call. – Uchia Itachi Dec 01 '13 at 07:50
  • 1
    You can't return a local array. You'd have to dynamically allocate it with `malloc()` or one of its brethren. And, when you're done with it, you need to free it with `free()`. – Jonathan Leffler Dec 01 '13 at 07:52

1 Answers1

2
   // Initialize the array
   int theList[totalListCount];

you should not return the function's local array, you should use malloc like this:

   int *theList = malloc(totalListCount);

off course,you should free it when you not use it

sundq
  • 735
  • 2
  • 9
  • 28