1

Suppose I have a pointer

int *x;

Then I need to let the pointer point to an int of value, say 42.

Should I do this:

   *x = 42;

or this:

  int y = 42;
  x = &y;

? What is the usual practice?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
zell
  • 9,830
  • 10
  • 62
  • 115
  • I assume you are doing `*x=42` after a call to `x = malloc`, aren't you? – IrAM Dec 08 '20 at 10:25
  • I was thinking that because as long as x is non-null, *x=42 should work even without malloc. Right? It would be like we just put 42 to a random memory case, but what would be wrong with it? – zell Dec 08 '20 at 10:37
  • but random memory cannot guarantee it will be successfully stored, that would be **UB** (undefined behavior) – IrAM Dec 08 '20 at 10:43
  • Regarding the common misconception that you can somehow store data inside pointers, see [Crash or “segmentation fault” when data is copied/scanned/read to an uninitialized pointer](https://stackoverflow.com/questions/37549594/crash-or-segmentation-fault-when-data-is-copied-scanned-read-to-an-uninitializ). – Lundin Dec 08 '20 at 11:15

3 Answers3

2

After this declaration

int *x;

the pointer x either is equal to NULL (if it is declared outside any function) or has an indeterminate value. So dereferencing the pointer like

*x = 42;

invokes undefined behavior.

You can write either

int y = 42;
x = &y;

or

x = malloc( sizeof( int ) );
*x = 42;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

When you do:

int *x = 42;

you assigne the pointeur x to the memory case 42, that gonna make a segmentation fault. The right way to do what you wan't is:

int y = 42;
x = &y;
DipStax
  • 343
  • 2
  • 12
0

x gets the adress of y (&y)

#include <stdio.h>

int main()
{
      int y=42;
      int x=&y;
      printf("\nY = %d is at adress X = %d \n",y,x);
}
MED LDN
  • 684
  • 1
  • 5
  • 10