char *userArray[10] = malloc(sizeof(char[10])*15);
You have not cleared whether your variable userArray
is stack or heap allocated and what's the dimension of the userArray
?
Arrays in C can be of two types (based on where they are stored):
- Stack Memory Arrays
- Heap Memory Arrays
Stack Memory Arrays
You can initiate a array which is going to be stored on stack memory like this:
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Now, to obtain array's length use this:
size_t length_arr = sizeof(arr) / sizeof(*arr);
Heap Memory Arrays
You can initiate a array which is going to be stored on heap memory like this:
int *arr = (int *)calloc(10, sizeof(int));
Now, do not use sizeof
to obtain arr
's length because sizeof(arr)
will return the size of the pointer, which in my case is 8.
So, you need to keep track of the length of array.
Also, do not forget to free()
the heap allocated resource after use.
For freeing heap allocated resources snippet will be:
free(arr);
NOTE: Must include stdlib.h
header file before using functions like malloc()
, calloc()
, realloc()
or free()
.