A little doubt about pointers in C

1) to initialize the pointer I am using:

int number, *Pnumber;
    Pnumber=&number;
    number=10;

      

Am I doing it right?

What about:

int *Pnumber;
*Pnumber=10;

      

When I compile it I get:

RUN FAILED (output 1 value, total time: 858ms)

by the way. do I need to use free (Pnumber) to free memory?

+3


source to share


5 answers


Am I doing it right?

Yes you.

What about:

  `int *Pnumber;  
   *Pnumber=10;`

      



Pnumber

is a uniform pointer. Splitting this pointer results in undefined behavior. Pnumber

must point to allocated memory (either a variable or a dynamically allocated memory area).

by the way. do I need to use free (Pnumber) to free memory?

Until you use malloc

, don't use free

.

+5


source


In the first version, you point the Pnumber pointer to memory that has already been allocated, and therefore you can change the value the pointer points to. This version is correct. In the second version, you never specify what the pointer is pointing to (it remains uninitialized), and thus, when trying to access memory, it will result in an error. Thus, the second version does not match no .



+2


source


Your first approach is correct.

But this is wrong:

int *Pnumber;
*Pnumber=10;

      

Because the pointer does not point to valid memory, whereas in the first approach it does.

+1


source


First correct

In the second, you are missing a pointer to a memory location.

A pointer is an address, so

If we have

int *p;

      

This means p is the address

and * p is the contents of the memory address.

to make the pointer point to memory space before you fill the memory with

*p = 5;

      

+1


source


if you use a pointer, you are "specifying the variable, just like you are:

 int number, *Pnumber;
Pnumber=&number;
number=10;

      

the advantage of a pointer is that you save memory in your program, so if you want to change the value of a number that is a 32 bit integer, you can use * Pnumber = 10; here you are using an integer, but if you use an array of them or double or float a lot of memory and why you are better off storing the address of a variable in 32-bit in 32-bit OS architecture, always with a pointer in the file doesn 'It doesn't matter which the type you point to

+1


source







All Articles