I looking for a clarification regarding the pointers. I have compiled the following code in bordland c++ 5.5.1 without any errors. But while i am trying to execute gives a core error.
int main ()
{
int x=10,y=20;
int &a=x;
int &b=y;
int *c;
int *d;
*c=x;
*d=y;
return 0;
}
Basically I am trying to create two reference variable (a,b) and assigned with two variables (x,y). after that I created two pointer variable(c,d) and tried to assign same variables (x,y). This gives me error while exection and not at compilation.
whether I am doing any wrong, this is not a standard assignments of pointer variable. why the pointer assignment is getting failed at this point. Please help me to understand this.
1st Update:
Thanks to all. First, I understood that I am working on a C++ feature (reference variable).
Second, I need to allocate memory for the pointer variables before play with it.
The code you posted is C++, not C. And your problem is that you need to make those pointers actually point at something:
int * c = & x; // make c point at x
* c = 42; // changes x
You have declared c and d as int pointers and you are trying to update their pointed values, they aren't pointing to anywhere valid since you never initialize them with valid memory.
Try c = &x; and then play with c.
You are dereferencing an invalid pointer. 'c' and 'd' were not assigned a memory location and so will be using whatever was previously in memory as their location. You need to do:
int *c = new int;
int *d = new int;
It looks to me like you're not entirely clear on the syntax.
Typing int *c is tricky, because it looks like you're declaring an integer with the name *c. However, this is not the case. This will declare a pointer to an integer, and in C/C++, pointers to a certain type are denoted by appending a * after the type name. Thus, you're declaring a variable of type int* (pointer to an integer), with the name c, even though the spacing makes it look different. For the record, typing int* c yields the same result, and is arguably more readable.
It follows then that typing *c does not reference your variable, as it is actually called c. Instead, what this does is dereference the pointer: it returns whatever object the pointer is pointing to. Or, if the pointer is invalid, cause an error.
If you want to declare a pointer and set it to point to an object at a later point, you need to do this:
int *c;
// stuff goes here
c = &x;
&x will return x's address in memory, which can be assigned to a pointer as a value. Then, you can manipulate the value through the pointer by dereferencing it: e.g. *c = 15.
You have defined two pointer variables c and d but you have not allocated any memory for them. You need to assign some memory to both of them.
Do this:
int *c = &x;
int *d = &y;
Related
Is returning a pointer declared inside the function considered bad practice? Example:
int* foo(void)
{
int * ret_val = 1234;
return ret_val;
}
I believe you're suppose to use:
static int * ret_val = 1234;
But then again, wouldn't it still be considered bad practice to return memory outside of your scope?
Returning a pointer isn't a problem as long as it points to memory that is still in scope, such as dynamically allocated memory, global data, or local variables that still exist further up the call stack.
The problem with the above code is that you're dereferencing a pointer without assigning anything to it. This: *ret_val = 1234; assigns the value 1234 to the address that ret_val points to, but ret_val wasn't assigned anything.
If on the other hand you did this:
int* foo(void)
{
int * ret_val;
ret_val = malloc(sizeof(int));
*ret_val = 1234;
return ret_val;
}
That is fine since you're returning a pointer to dynamically allocated memory.
The primary culprit is
*ret_val = 1234;
is applied with an uninitialized pointer.
I believe you're suppose to use:
static int* ret_val;
No, to fix that you could use
int* foo() {
static int_val = 1234;
return &int_val;
}
But it's arguable if that's what you really want. All callers of that function will share the same instance of int_val.
It's a really bad practice if your return a pointer to a local variable, because you will have a dangling pointer.
int* foo(void)
{
int a = 1337;
return &a; //Don't do this!
}
But sometimes it could be useful:
int* copy_array(int *array, int size)
{
int *v = (int*) malloc (size * sizeof (int));
//..copy the array..
return v;
}
Anyway, you should avoid returning pointers, so there is no risk of memory leaks.
Aside from your use of ret_val without it being allocated, returning a pointer from a function is fair practice, though it takes special care:
Don't return a pointer to a local variable, as it will be destroyed when the function exits and cause undefined behavior if dereferenced
If the function allocates memory, it is the responsibility of the caller function to ensure that the pointer is deallocated when it is no longer needed, to avoid memory leaks
If the function is processing an array in the form of a pointer, it needs to be aware of the size of the array to avoid undefined behavior, typically as an extra size parameter or a global constant
A pointer is like a shortcut or a hyperlink. Creating just a shortcut does not install a program. Creating a hyperlink does not magically sets up the whole website.
Same with a pointer: a int* is a pointer to an integer. It is not the integer itself. As such you must make sure that the pointer points to something meaningful before you try to follow the pointer.
One way of doing so is to create an integer and the sets a pointer to point to it:
int* ret_val = new int;
This will create an integer (the new operator), and then sets the ret_val pointer to point to it.
Objects created through new exist until you explicitly destroy them through delete or when your application ends. For that reason, if you have new int in a function, it is safe to access it even if the function ends.
What would be dangereous, and probably caused your concern, is if you would set the pointer ret_val not to a new integer, but to an existing local variable, i.e.
int myInteger;
int* ret_val = &myInteger;
In such scenario, ret_val points to a local variable myInteger which gets destroyed when the scope containing the declaration ends. You end up with a dangling pointer, referencing stuff that does not exist (think: broken hyperlink). Using such a pointer can lead to undefined behavior. It may crash your program, but it may as well silently accept it, modifying some random space in memory.
So, a function of the shape:
int* foo(void)
{
int* ret_val = new int;
*ret_val = 1234;
return ret_val;
}
is safe to use. It is not necessarily a good practice: the user of such function must know that it creates a new integer, that later - at some point - someone should delete. Functions that do that typically highlight such behavior in some way, e.g. through its name. For example, allocateInt() makes it clear that it created something that later should be delete. In contrast, getInt() suggests that the integer already exists and nothing new is created.
You should consider:
int *foo() {
int *ret_val = new int(1234);
return ret_val;
}
instead of (bad code):
int* foo(void)
{
int * ret_val;
*ret_val = 1234;
return ret_val; // dangling pointer!
}
otherwise you will have dangling pointer (the second example).
Obviously don't forget to release the memory.
You should also consider using smart pointers:
https://en.wikipedia.org/wiki/Smart_pointer
As you specified both C++ and C languages the above code is in C++ (operator new), please refer to (e.g.) #Mattia F. answer for ANSI C.
I want to pass a pointer to a function.
Lets say I am creating a structure and declare a pointer to that structure. I allocate memory to that pointer and then I want to "pass" that pointer to a function so I can do stuff to that block of memory. How I do that?
It is done the same way as passing a normal variable. You shouldn't think of a pointer any different than a variable, as a pointer is a variable (although a bit special).
Say you have an integer and a pointer to that integer:
int a = 0;
int * ptr = &a;
Note that ptr and a are both variables, and in this instance, we use the reference operator & to reference a by &a which gives the address of a -- this is a pointer to a.
Now say you have two functions:
void foo(int i){}
void bar(int * p){}
Now these two functions do the same thing (nothing), but one takes an int and one takes a pointer to an int, int *. If you called foo(a) and modified i, i would be modified in the function body, but have no effect on a. If you called bar(ptr) and modified the value pointed to by ptr by using the dereference operator * as something like *ptr = 1, it would modify the value pointed to by ptr, which in this case would be a.
In your case, passing a struct would be just the same. Say you have a structure
struct MyStruct { int b; };
And had two more functions
void structFoo(struct MyStruct m) {}
void structBar(struct MyStruct * mp) {}
You could work on the pointer in the same way as our above int and int * functions, although you would now also have to access the struct components by dereferencing the struct with (*mp).b, or the shorthand version mp->b.
For ease of use, you may also want to do something like
typedef struct MyStruct MyStruct;
Which will allow you to use MyStruct as the type name rather than requiring struct MyStruct as in the above functions, although you may want to avoid doing this until you fully understand what is happening and get through difficulties with pointers.
Hopefully that gives you some idea of what is going on, although the C++ tutorial on pointers gives a much more in-depth discussion than what I can provide.
It would be a good exercise to create some small programs and mess around with pointer and regular types while printing the results to help understand what is happening where. You should remember that to allocate a pointer, you're going to need to use either new or malloc(), otherwise you will have a SEGFAULT error. This is not an issue when referencing a variable declared as I have done with &a above as the memory is already allocated when a declaration such as int a is made. A declaration of a pointer allocates the memory for that pointer, but not the memory that it points to. This eventually leads into the difference between the stack and the heap, although I wouldn't think about that until you have a very thorough understanding of pointers.
Structure in c/cpp is like all the other types. You can use & and * as you do it for int.
I have tried the c++ code
double* p;
*p = 123.0;
in vs 2010, and it broke off because the pointer hasn't been initialized. But I remember I have read in a blog(forget which one...), that the 123.0 is a const value,so p is pointing to a const value now, you can use *p to get 123.0 but you cannot change the value. Which one is the truth?? Thank you!
p doesn't point anywhere and you tell it to store value 123.0. Where should it go? This is undefined behaviour.
If you want it to point to a constant value in a memory address that will stick around, try
static const double d = 123.0;
const double* p = &d;
I can't suggest anything more without context of what you are trying to do.
Your approach is wrong since double* p; only declares a pointer, but it is uninitialized so when you do *p = 123.0; it triggers an undefined behaviour.
You need to point p to a valid double location so you can modify it.
Neil's answer is partially correct. In his example, you cannot change *p anymore like you do in your question. You need to get rid of the const. In that answer, p points to memory on the stack.
If you want to create a heap-allocated double, you would use the new keyword.
double* d = new double;
*d = 123.0;
However, you have to make sure to delete this memory after you are done using it.
delete d;
Since you are using MSVC 2010, which includes some C++11 features, the better way to do the same would be to use unique_ptr. It acts the same as a raw pointer, but it will manage the memory allocated by the pointer ... i.e. it will automatically call delete once it goes out of scope.
unique_ptr<double> d = unique_ptr<double>(new double);
*d = 123.0;
// when d goes out of scope, the memory will be deleted as well
I'm bit new to C++ and try to work things with Qt and came across this confusing thing:
The concepts on various tutorials state something like:
Class *obj;
*obj - will display the value of object stored at the referenced memory
obj - will be address of memory to which it is pointing
so, I would do something like
*obj=new Class();
but if I want to access a function, I have to do obj->function1();
instead of *obj->function1();
-- not sure why, since with normal objects [ normalObj.function1();] would work, since that's the value directly.
So, for pointer objects why do we use memory reference to access the function,
or is it that in case of normal objects also, its always references
P.S: Can someone guide me to a good tutorial of usage of pointers in C++, so that my queries like these can be directly addressed in it.
The * symbol is used to define a pointer and to dereference a pointer. For example, if I wanted to create a pointer to an int, I could do:
int *ptr;
In this example, the * is being used to declare that this is a pointer to an int. Now, when you are not declaring a pointer and you use the * symbol with an already declared pointer, then you are dereferencing it. As you probably know, a pointer is simply an address. When you dereference a pointer, you are obtaining the value that is being pointed to by that address. For example:
int pointToMe = 5;
int *ptr = &pointToMe;
std::cout << *ptr;
This will print out 5. Also, if you are assigning a pointer to a new address and it's not in the declaration, you do not use the * symbol. So:
int pointToMe = 5;
int *ptr;
ptr = &pointToMe;
is how you would do it. You can also deference the pointer to assign a new value to the value being pointed to by the address. Such as:
int pointToMe = 5;
int *ptr = &pointToMe;
std::cout << *ptr; // Prints out 5
*ptr = 27;
std::cout << *ptr; // Prints out 27
Now, -> acts like the deference symbol. It will dereference the pointer and then use the member functions and variables as if you had used . with a non-pointer object. Even with an object that is not a pointer you can use the -> by first getting the address:
CObj object;
(&object)->MemberFunction();
That's just a brief overview of pointers, hope it helps.
You can use the "normal" . to access the objects members, but you have to dereference the pointer first.
Due to operator precedence, this will look like (*obj).member. For those who think this is too much to write, obj->member is a shorter alternative.
If you have an object c of type Class, *c.ptr means dereferencing a pointer ptr that is a member of Class. That is one reason for (*obj).member, which means something else.
Actually, you're wrong. You do:
obj=new Class();
or
Class *obj = new Class;
which are completely different.
Class *obj;
*obj = new Class;
wouldn't compile.
obj is of type Class*, so that's what you can assign to it (and what new Class returns).
More precisely u can do like this
Class obj;
Class* obj_ptr;
obj_ptr = &obj;
// Now onwards you can use the pointer to access data members and function
obj_ptr->a = 10; // Like this
If I have the following for example:
int *x;
x = func(a);
For the statement: x = func(a);, do we say that we are returning an address to x? Or, how exactly do we read it?
EDIT: Is it eligible to say that we are returning a pointer to x? If so, can you explain how this is done exactly? I mean, how are we returning a pointer?
x is a pointer to an int, so in other words it is the address of a memory location where an int is stored. So x = func(a) means that func returns the address of an int and stores it in the variable x.
Take care not to return the address of a local variable whose contents would be undefined after func returns.
RE: Your edit:
EDIT: Is it eligible to say that we are returning a pointer to x? If so, can you explain how is this done exactly? I mean, how are we returning a pointer?
Yes, it is certainly eligible. Try and think of and treat pointers as any other data type. Under the hood, they are just memory addresses. A pointer can be returned the same way any other data type can be returned.
Take this code for example:
int* giveMeAPointer() {
return y;
}
int* x = giveMeAPointer();
Say that "y" is declared globally as: "int* y = ...". Now the memory address being pointed to by "x" is the same as the memory address being pointed to by "y".
Now let's say that "y" was -not- declared as a pointer, but instead as a normal int (e.g. "int y = 5"). The function could do this and still be valid:
int* giveMeAPointer() {
int* result = &y;
return result;
}
*x is points to int typed variable in memory. So function func should return address to int.
int *x;
x = new int; // create your own int
*x = 5; // access - set it's value
delete x; // delete int - free memory
x = getGlobalCounter();
(*x)++; // increment global pointer
For example the getGlobalCounter function:
static int counter;
int *getGlobalCounter() {
return &counter; // return address of counter
}
But isn't always good idea to delete objects returned from functions. In that case it should result in runtime error, because of counter isn't dynamically allocated int as in top example.
If you are assigning a variable's value to the return-type of a function, then that return-type must match the variable's type. This goes the same for pointers.
So, if you have:
int* myPointer;
And...
int* func();
Then setting myPointer equal to func() will change the memory address which "myPointer" points to, to the memory address returned by func().
x is a pointer, specifically to an int. So it should be obvious that there are two memory locations used. One for the pointer and one for the memory it's pointing to (assuming the pointer is not null).
The pointer itself holds a memory address, specifically the location of the memory it's pointing to. Something like 0xa456e4fa.
Yes, func() is returning a pointer. The prototype of func would look like the following..
int * func(someObj a); //I don't know the datatype of your parameter,
//so I'm just making something up.
Notice the return type is a pointer to an int. From this and what I said previously, it should be obvious what this will return. Something of the form 0xyyyyyy, or a memory address/pointer. That memory address goes into your x pointer.
Remember that the pointer itself is not holding the data that it's pointing to, it is only the address. There's really no reason you CAN'T return a pointer. However, you do need to be careful in WHAT you return. You do not want to return the address of a local variable because that variable will go out of scope once the function has completed its execution. You'll then be returning the address of something invalid. Returning the VALUE of a local pointer however, is fine because the value you returned (the address) will be preserved as will the memory it's pointing to.
I also just realized I wrote you a book. Damn, I sure do ramble when I'm tired.
The statement just reads that x is assigned the value returned by function func. For the code to compile without errors , the func should return an address though . And for the code to execute as expected as AlexFZ pointed out , you should take care that func does not return the address of a variable local to the function.
It means that func() returns a variable of type int*.
Is it eligible to say that we are returning a pointer to x?
No, we are returning a pointer to an integer and assigning it to x since it is a pointer.
This is an example code which returns an int pointer
int* func(int a)
{
int *y = &a;
return y;
}