This question already has an answer here:
I am trying to assign values for a double pointer and I could not do it because when my pointer is locally declared it is working fine and when I declare it globally then it is not working. Here are the codes for the above mentioned scenarios
// Declared Globally, Not Working
#include<stdio.h>
#include<stdlib.h>
int **x;
int main() {
x=(int**)malloc(sizeof(int*));
x[1][2]=10;
printf("%d",x[1][2]);
}
// Declared Locally, Working fine
#include<stdio.h>
#include<stdlib.h>
int main() {
int **x;
x=(int**)malloc(sizeof(int*));
x[1][2]=10;
printf("%d",x[1][2]);
}
In both cases it is invalid code. You need to allocate memory for the pointer(s) then for the object(s). You only malloc space for the pointer but not for the object.
It is the UB
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.