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?