I have written a function to allocate memory for an array and store the array length in a pointer so I can use both in my main function. Everything seems to work fine until I try to loop through the array printing the values.
When I use the array size pointer to terminate the print loop it shows strange behaviour. Could you please show me where I am going wrong?
Thanks in advance :)
#include <stdio.h>
#include <stdlib.h>
void func (int** arr, int** len){
int length = 5;
*len=&length;
*arr = malloc(sizeof(int)*(**len));
for (int i=0; i<(**len); ++i){
(*arr)[i]=i*10;
}
}
int main(){
int* len = NULL;
int* arr = NULL;
func(&arr, &len);
for (int i=0; i<5; ++i){
printf("%d\n", arr[i]);
} //works
/*
for (int i=0; i<*len; ++i){
printf("%d\n", arr[i]);
} //doesnt work
*/
free(arr);
return 0;
}
*len=&length;You are storing the address of a local variable in that pointer. This variable does not exist any longer when you leave that function. Accessing it is illegal. Why do you want a pointer to store the length. It is just a numerical value. You should change toint * lenin parameter list and inmainuseint len = 0;mallocdoes not accept a pointer to a pointer, it returns a pointer. Functions may, and generally do, return values. Use that to your advantage,