0

Because in C there is no Array List I wanted to try and code my own one. I came up with this Idea:

int* createArrayList(int size) {
    int arrayList[size];
    clearList(arrayList);
    int* returnVal = arrayList;
    return returnVal;
}

This code makes an array with the given size, calls clearList() which sets all values in the array to 0 and than returns a refrences to that array.

int* arrayList = createArrayList(10);
outputArray(arrayList);

This is the code in the main function, it gets the pointer from createArrayList() and then calls outputArray() which is just a for-loop that prints out the array using printf().

In the clearList() and outputArray() functions I use sizeof().

I am excpecting to have 10 rows of 0 but its only 8 rows and when I write for example arrayList[2] = 10; in beetween then the output is again 8 rows of 0 with a few random numbers in beetween and the 10. Also the random numbers only show up at the spots of 1 and 3.

Note: Please focus on the question and not my code for the array list, I know it can be better.

elite_tnt
  • 1
  • 2
  • 2
    You're trying to return a pointer to an array that is no longer available after the function returns. Obviously that makes no sense, so don't. – Tom Karzes Jan 09 '23 at 15:09
  • you need to dynamically allocate `arrayList` for this to work – yano Jan 09 '23 at 15:18

0 Answers0