0

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]);
}
DRC
  • 1
  • 1
  • 1
    When you say "not working", what exactly isn't working? – Kon Oct 12 '18 at 16:13
  • `x[1][2]=10;` - you haven't allocated memory for this. Neither global nor local. – Eugene Sh. Oct 12 '18 at 16:14
  • The second example only works by coincidence — it is undefined behaviour. You allocated one `int *`, and assign it to an `int **`. You've not allocated the `int` that these need to point to. And using subscripts other than 0 is accessing out of bounds, etc. One of the nasty things about undefined behaviour is that it can appear to work — right up until it doesn't. And it's not the compiler's fault, either. UB is the programmer's problem. – Jonathan Leffler Oct 12 '18 at 16:15
  • what you have here is undefined behavior (UB). The second one only seemed to work, add more code to it and see what happens, put the code in a function and call it,... – pm100 Oct 12 '18 at 16:15
  • This is a duplicate of probably ten other questions here. – Andrew Henle Oct 12 '18 at 16:17

1 Answers1

0

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

0___________
  • 60,014
  • 4
  • 34
  • 74