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?
source to share
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
.
source to share
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 .
source to share
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
source to share