Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it compulsory to initialize pointers in C++?

Is it compulsory to initialize t in the following code, before assigning value to t? Is the code correct?

void swap(int *x, int *y)
{
    int *t;
    *t = *x;
    *x = *y;
    *y = *t;
}
like image 614
Baali Avatar asked Mar 23 '11 10:03

Baali


People also ask

Do you have to initialize pointers in C?

You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator (&). The address-of operator (&) operates on a variable, and returns the address of the variable.

Do you need to initialize pointers?

All pointers, when they are created, should be initialized to some value, even if it is only zero. A pointer whose value is zero is called a null pointer. Practice safe programming: Initialize your pointers!

Can I declare a pointer without initialization?

Yes, C allows uninitialized variables. And a pointer variable is still a variable just as an int variable. But a good compiler and a good set of compiler flags would have the compiler help hunt down variables used before being initialized.

Do we need to free pointers in C?

No. The function is receiving a pointer from the caller, and does not know how the memory being pointed at was allocated, so it has no business trying to free it. Only the caller knows how it was allocated, so only the caller knows how to free it.


2 Answers

You don't need pointer to begin with:

void swap(int *x,int *y)
{
    int t; //not a pointer!
    t=*x;
    *x=*y;
    *y=t;
}
int a = 10, b = 20;
swap( &a, &b); //<-----------note : Needed &

--

Or maybe, you want the following swap function:

void swap(int & x,int & y) //parameters are references now!
{
    int t; //not a pointer!
    t=x;
    x=y;
    y=t;
}
int a = 10, b = 20;
swap(a,b); //<----------- Note: Not needed & anymore!
like image 92
Nawaz Avatar answered Nov 10 '22 04:11

Nawaz


is the following section of code correct?

Nopes! Your code invokes Undefined behaviour because you are trying to dereference a wild pointer.

 int *t;
 *t=*x; // bad

Try this rather

 int t; // a pointer is not needed here
 t=*x; 

or this

int *t = x; // initialize the pointer

like image 43
Prasoon Saurav Avatar answered Nov 10 '22 03:11

Prasoon Saurav