I want to realloc a 2D matrix in a different function from main but unfortunately, I get an invalid pointer error. I have read other answers but I can't see where is my error. My code is:
void example(double* w, size_t s){
w=realloc(w,(s+1)*sizeof(double));
w[s]=3;
}
int main(int argc, char *argv[]){
double w[100][1];
int i;
for(i=0;i<100;i++){
example(w[i],sizeof(w[i])/sizeof(w[i][0])
}
free(w);
return 1;
}
so the first level of the array is always fixed but the second can change. What is wrong with this?
CORRECTION:
int main(int argc, char *argv[]){
double **w;
int i;
w=malloc(100*sizeof(double *));
for(i=0;i<100;i++){
w[i]=malloc(1*sizeof(double));
example(w[i],sizeof(w[i])/sizeof(w[i][0])
}
free(w);
return 1;
}
The w pointer is not dynamically allocated (it didn't come from realloc or malloc) so it is invalid to pass it as the argument to realloc. Also, you will need to pass the new pointer back to main if you want to free it in main.