Thread: Pointer initialization question

1. Pointer initialization question

If I use this code:
Code:
`int *x = 12345678`
Is this the same (when splitting it into 2 lines of code) as saying
Code:
```int *x //declare pointer variable
*x = 12345678 //set the value at the memory address pointed to by x to be equal to 12345678```
Or is it the same as
Code:
```int *x //declare pointer variable
x = 12345678 //make x point to memory address 12345678```

2. Re: Pointer initialization question

it would be the same as pointing x to memory location 12345678... if you put in the semicolons

if we're talking C++, you should be getting a compiler error though.

maybe it should be int *x = reinterpret_cast<int*>(12345678);

3. Re: Pointer initialization question

Note that statements in c/c++ are terminated with a ;

Code:
`int *x = 12345678;`
This means that x is of type pointer to integer (x is the address of a memory location at which location an integer is stored). The value of x is initialised to 12345678 (eg x points to the memory location 12345678 at which location an integer is stored). In this case, * means pointer to.

Code:
```int *x;
*x = 12345678;```
This means that x is of type pointer to integer - and is uninitialised. At the memory location pointed to by the value of x, set to the value 12345678. As x is not initialised, x could take any value in the range of an integer. So some unknown location in memory is set to 12345678. In this case, the * in int *x means pointer to. The * in * x = means the contents of the memory pointed to (dereference).

Code:
```int *x; // declare pointer variable
x = 12345678; // make x point to memory address 12345678```
Yes.

Note that as pointed out in post #2 by dexwerx, you cannot directly assign a number to a pointer type. In this case 12345678 is of type int and x is of type pointer to int. Therefore a cast is required. In c++ this would be reinterpret_cast as in post #2.

Code:
`int *x = reinterpret_cast<int*>(12345678);`
or
Code:
`auto x = reinterpret_cast<int*>(12345678);`
Or for c

Code:
`int *x = (int*)12345678;`
Note that if the value of x (the memory location) is not valid in the context of the program then a run-time exception will occur.

Also note, that unless you are programming embedded-devices etc, you probably wouldn't initialise a memory pointer with a fixed value in this way. You would usually initialise with the address of an existing variable or with the value of a memory location obtained via a call to new, malloc() etc.

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

Featured

Click Here to Expand Forum to Full Width