PDA

Click to See Complete Forum and Search --> : Pointer declaration and initialization


lerouxc1
Mar 18th, 2002, 10:28 AM
Hi,
I'm wondering what actually happens when you declare a pointer and initialize it on the same line.

Does it set the pointer's value or the value the pointer points to?

Which of the following is correct?

int *a = 1;

or

int *b = malloc(4);

Thanks,
Cedric

Nightshadow
Mar 18th, 2002, 01:33 PM
I donīt know about that Malloc thing, but this is how I do it:

int number = 0;
int* pNumber = 0;

// sets the pointer pNumber to point at the adress of number
pNumber = &number;

*pNumber = 5; // gives the value 5 to the variable number

cout << "number is: " << number << endl;


output: number is: 5

Nightshadow
Mar 18th, 2002, 01:34 PM
I donīt know about that Malloc thing, but this is how I do it:
int main()
{
int number = 0;
int* pNumber = 0;

// sets the pointer pNumber to point at the adress of number
pNumber = &number;

*pNumber = 5; // gives the value 5 to the variable number

cout << "number is: " << number << endl;

return 0;
}
output: number is: 5

Nightshadow
Mar 18th, 2002, 01:41 PM
Hmm when I edited my message, it added a second one.. that really sucks... oh well

lerouxc1
Mar 18th, 2002, 02:53 PM
Maybe I should reiterate my question...
(if you "don't know about that malloc thing" , please don't reply)

When a pointer is created, you must initialize it to point to something. I am trying to do this in one line. Is it possible?
What I'm fearing is that "int *a=1" assigns the value 1 to some unknown place in memory.

Which of the following two statements is correct? I know they are both valid. But I am looking for code correctness.

int *a = 1; // assigning the value 1 to *a

or

int *b = malloc(4); //assigning the newly allocated memory location to b

Thanks for any help.
Cedric

parksie
Mar 18th, 2002, 03:55 PM
Assigning a pointer has to be done in two steps, I think.

First, you have to give the pointer itself a value, normally by using new or malloc:int *ptr = malloc(sizeof(int) * 5);

int *cplusptr = new int[5];Then, you have to dereference that pointer - you can't do it in one step because the outcome of malloc or new decides where in memory you put the value, therefore it's totally separate:ptr[0] = 5;
ptr[1] = 10;Finally, you free up the memory:free(ptr);

delete[] cplusptr;Make sure you match malloc/free and new/delete otherwise REALLY nasty stuff happens!

CornedBee
Mar 18th, 2002, 04:02 PM
int *a = 1;
makes the pointer a point to the address 1. This is invalid memory in windows, causing an access violation when dereferencing.