简体   繁体   中英

Few doubts about pointers in C

1) to initialize a pointer I use:

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

Am I doing this right?

what about:

int *Pnumber;
*Pnumber=10;

When I compile it, I get:

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

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

Am I doing this right?

Yes, you are.

what about:

  `int *Pnumber;  
   *Pnumber=10;`

Pnumber is an unitialized pointer. Dereferencing this pointer leads to an undefined behavior. Pnumber must point to an allocated memory (either to a variable or a dynamically allocated memory area).

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

As long as you don't use malloc , don't use free .

In the first version you point the pointer Pnumber to memory that has already been allocated and thus you may change the value pointed to by the pointer. This version is correct. In the second version you never specify what is the pointer pointing to(it remains uninitialized) and thus when you try to access the memory this will cause an error. So the second version is not correct.

Your first approach is right.

But this wrong:

int *Pnumber;
*Pnumber=10;

Because the pointer doesn't point to valid memory whereas in the first approach it does.

The first one is correct

In the second you are missing pointing the pointer to a memory space.

The pointer is an address so

If we have

int *p;

That means p is an address

and *p is the content of the memory address.

so the pointer should be pointed to a memory space before you fill the memory with

*p = 5;

if you use a Pointer you "point a variable like you did:

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

the advantage of the Pointer is that you save memory to your Program so if you want to change the value of number which is an integer 32bit you can use *Pnumber = 10; here you're using integer but if you use a array of them or double or float it a lot of memory and that why it better for you to save the address of the variable in 32 bit in 32bit OS architecture always with pointer in doesn't matter what type you'RE pointing at

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM