#include <stdio.h>
int main()
{
int* n;
*n = 20; // causes the crash
printf("%d\n", *n);
return 0;
}
but for some reason if i first set int* n = i then I can change the value with *n = 20
there a reason for this?
int i = 19;
int* n;
*n = i;
*n = 20;
edit: thank you everyone for helping i learned a lot from your answers.
int* n;
*n = i;
No, all you see (in both of your examples) is result of undefined behavior. Above you didn't initialize the pointer to point to a meaningful memory - by applying * operator you are dereferencing the pointer and telling it to write some value to the memory it points to, but since you didn't make it point to valid memory - you can't write through that pointer.
This would be fine
int x = 0;
int* n = &x; // Now your pointer points to valid memory
*n = 5; // Value of x will be 5 now
Yes, there is a reason. When you declare :
int* n;
pointer n shows nowhere. So when you try to set its value by
*n = 20;
the program crashes as you are trying to access the contents of a pointer showing nowhere.
On the other hand, when you declare
int i = 19;
int* n;
n = &i;
you make the pointer n show to some valid address. So when afterwards you assign
*n = 20;
you actually access the contents of a valid memory address.
The reason why you can't set the value using that pointer is because its not pointing to a memory address yet, you need to use malloc and give it something to point to.
Hope this helps :D
E.g
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int *n;
n = malloc(sizeof(int));
*n = 20;
printf("n = %d\n", *n);
system("pause");
return 0;
}
Related
I am new to pointers.
For the below program , I get an answer of 255 and not 20. Please suggest how to correct.
Here is the code :
int sum(int *a , int *b);
int main()
{
int *p;
int *q;
*p =10;
*q =10;
int c = sum(p,q);
printf("%d",c);
}
int sum(int *a , int *b)
{
return((*a)+ (*b));
}
There is data, then there are pointers. For simplicity, once you have data, then you can point to it. This is accomplished by using the & operator. To go back to the data from a pointer, use the * operator as you have
Something more like
int sum(int *a , int *b);
int main()
{
int p_data=10;
int q_data=10;
int *p =&p_data;
int *q =&q_data;
int c = sum(p,q);
printf("%d",c);
}
int sum(int *a , int *b)
{
return((*a)+ (*b));
}
EDIT: Also note that pointers can be used to access memory allocated from malloc, or mmap'd, or other means
You need to alloc memory for pointers. This code should work:
#include <stdio.h>
#include <stdlib.h>
int sum(int *a , int *b);
int main()
{
int *p = (int*) malloc(sizeof(int));
int *q = (int*) malloc(sizeof(int));
if (p != NULL && q != NULL)
{
*p =10;
*q =10;
int c = sum(p,q);
printf("%d", c);
free(p);
free(q);
}
else
{
printf("Could not allocate enough memory");
return 1;
}
return 0;
}
int sum(int *a , int *b)
{
return (*a) + (*b);
}
Hope this helps!
A pointer is a variable that holds the address of another variable, and this seems clear to you. But what seems not still very clear is that when you create a pointer the compiler doesn't automagically create also a variable to point to...
In code:
int *p;
int *q;
*p =10;
*q =10;
You are defining p and q as pointers to int, but to which variables of type int they point? They have a garbage inside and can point anywhere, so when assigning 10 to what they point to, in reality, you are spamming somewhere in memory.
Under these conditions when you call sum I would expect more a memory fault than a strange value (255), but everything can happen with bad pointers, even to access an existing memory.
The correct code is:
int sum(int *a , int *b);
int main()
{
int i1, i2; //Allocate 2 int variables
int *p = &i1; //Create pointers and assign them
int *q = &i2; //the address of int vars i1 and i2
*p =10; //Initialize variables pointed by pointers with 10
*q =10;
int c = sum(p,q);
printf("%d",c);
}
int sum(int *a , int *b)
{
return((*a)+ (*b));
}
A pointer needs to be assign the address of some valid memory to point to before it may be dereferenced of the *-operator and gets written some data to where it points to.
You miss those very assignments.
Dereferencing a pointer implies reading out its value. If no value ever had been assigned to a pointer variable, already reading out its value might invoke the infamous Undefined Behaviour, anything can happen after this.
So your result could also have been just the famous 42.
Lesson learned: Never apply any operator to a variable which had not been properly been initialised.
Another approach. I think it may be useless for return function but it can help you about pointers It is passing pointer to the sum function
#include <stdio.h>
int sum(int *a , int *b);
int main()
{
int p = 10;
int q = 10;
int c = sum(&p,&q);
printf("%d",c);
}
int sum(int *a , int *b)
{
return((*a)+ (*b));
}
You're getting 255 is because of random luck. I get 20 when I compile it, but that's also random luck. The technical term is "undefined behavior", and this is undefined because you never initialized your int *p and int *q pointers.
What's inside your pointer variables? You don't know, I don't know, nobody does. Since you never initialized them, their contents are whatever bits were there before initialization. It's like moving into a house and getting whatever junk the previous tenants left for you.
If the contents of the pointers are addresses in memory (and they don't overlap), then the value returned should be 20 (by random luck). But if one of them contains a null address, who knows what you'll get!
If you want to get 20 reliably, you need to allocate memory:
In C++:
int * p = new int;
int * q = new int;
In C:
int * p = (int*)malloc(sizeof(int))
int * q = (int*)malloc(sizeof(int))
#include <stdio.h>
void swap (int *a, int *b)
{
int *tmp;
*tmp = *a;
*a = *b;
*b = *tmp;
}
int main ()
{
int x = 5;
int y = 7;
swap (&x,&y);
printf ("\n x = %d \n y = %d \n",x,y);
}
I'm using codeblocks, and this code won't work, and I don't understand why... On one computer it works perfectly but on the other it won't run at all.
Any help?
Thanks in advance.
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
What you need is a variable tmp to store the value and not a pointer *tmp.
The below code really a poor way of doing this but
int *tmp = malloc(sizeof(int));
*tmp = *a;
*a = *b;
*b = *tmp;
Once done please free the memory using
free(tmp);
Gopi already corrected your code - adding on to the previous answer - i think this is good to know information for a newbie:
Section 4.1 states:
An lvalue (3.10) of a
non-function, non-array type T can be
converted to an rvalue. If T is an
incomplete type, a program that
necessitates this conversion is
ill-formed. If the object to which the
lvalue refers is not an object of type
T and is not an object of a type
derived from T, or if the object is
uninitialized, a program that
necessitates this conversion has
undefined behavior. If T is a
non-class type, the type of the rvalue
is the cv-unqualified version of T.
Otherwise, the type of the rvalue is
T.
When you try to dereference and uninitialized pointer the behavior is undefined. Undefined means anything can happen - there is no guarantee. So you can get different behavior in different environments.
From Wiki Making pointers safer
A pointer which does not have any address assigned to it is called a wild pointer. Any attempt to use such uninitialized pointers can cause unexpected behavior, either because the initial value is not a valid address, or because using it may damage other parts of the program. The result is often a segmentation fault, storage violation or wild branch (if used as a function pointer or branch address).
What you did here:
int *tmp;
*tmp = *a;
is that you created a pointer to int which is not pointing to anything - basically it contains some junk value (could be your pincode even - who knows).
Your mistake was to use uninitialized memory. Always allocate memory to a pointer before using it. Next, don't forget to free the allocated memory after you're done with it.
Also, you should add return 0; at the end of your main() function.
If you don't mind a second opinion, check the below code.
#include <stdio.h>
#include <stdlib.h>
void swap (int *a, int *b)
{
int *tmp = malloc(sizeof(*tmp));
*tmp = *a;
*a = *b;
*b = *tmp;
free(tmp);
}
int main ()
{
int x = 5;
int y = 7;
swap (&x,&y);
printf ("\n x = %d \n y = %d \n",x,y);
return 0;
}
If you want to use pointers, although it does not make any sense at all
void swap(int *a, int *b)
{
int tmp[1];
*tmp = *a;
*a = *b;
*b = *tmp;
}
here tmp is not strictly a pointer, but you can use the * indirection operator on it.
Or
void swap(int *a, int *b)
{
int value = *a;
int *tmp = &value;
*tmp = *a;
*a = *b;
*b = *tmp;
}
Or you can use malloc as Gopi already pointed out.
If you want to use pointers, then do use pointers:
#include <stdio.h>
void swap (int ** ppx, int ** ppy)
{
int * p = *ppx;
*ppx = *ppy;
*ppy = p;
}
int main (void)
{
int x = 5;
int y = 7;
int * px = &x;
int * py = &y;
printf ("\nx = %d\ny = %d\n", *px, *py);
swap (&px, &py);
printf ("\nx = %d\ny = %d\n", *px, *py);
return 0;
}
Result:
x = 5
y = 7
x = 7
y = 5
Hi I'm new to the C language, can someone explains what ** symbol mean.
typedef struct _TREENODE {
struct _TREENODE *Left, *Right;
TCHAR key[KEY_SIZE];
LPTSTR pData;
} TREENODE, *LPTNODE, **LPPTNODE;
If x is a pointer, *x dereferences it. **x is the same as *(*x), so **x dereferences a pointer to a pointer. (eg, it is the thing that is pointed to by the thing that x opints to).
** is a pointer to pointer, it is also used for dereferencing a pointer variable.
eg: int a=10,*b,**c;
b=&a;
c=&b;
printf("the a value is:%d\n",a);
printf("the b value is:%d\n",*b);
printf("the c value is:%d\n",**c);
just execute this code you will get the idea about pointer to pointer.
In you want to change a variable, you pass it by pointer (to the variable).
And if you want to change a pointer, you also pass it by pointer (to the pointer) which is a double pointer.
There are two things to know about * in C:
It's an operation. Doing *x on a pointer dereferences that pointer. Doing **x on a pointer can dereference a pointer to a pointer, and so on.
It's a type. Declaring a type of int *x means that it's a pointer to an int type. Declaring int **x means that it's a pointer to a pointer to an int type.
Example:
int main() {
int foo = 4;
int *bar = &foo; // declaring a pointer to int type *bar
int **baz = &bar; // declaring a pointer to a pointer to int type **baz
printf("foo: %d, *bar: %d, **baz: %d\n", foo, *bar, **baz); // derefencing the pointer *bar and **baz
return 0;
}
In a declaration, ** means pointer to a pointer. When evaluating an expression, ** dereferences a pointer to a pointer.
int** p; // Declares p to be a pointer to a pointer.
And...
**p = 10; // Dereferences p and assigns 10 to a memory location.
One common use of pointers to pointers is to represent dynamic 2D arrays. For example, if you want to create a matrix of M rows and N columns, you could do:
int** matrix = malloc(M*sizeof(*matrix));
int i = 0, j = 0;
for ( i = 0; i < M; ++i )
matrix[i] = malloc(N*sizeof(*matrix[0]));
Usage of the double pointer:
for ( i = 0; i < M; ++i )
for ( j = 0; j < N; ++j )
matrix[i][j] = 0; // Assigns a value to the element
// at the i-th row and j-th column.
If you want to use string pointer dereferencing, you would use:
for ( i = 0; i < M; ++i )
for ( j = 0; j < N; ++j )
*(*(matrix+i)+j) = 0;
Memory allocated for the matrix has to be freed in two passes also.
for ( i = 0; i < M; ++i )
free(matrix[i]);
free(matrix);
** means a pointer to a pointer.
Most of the time I like to think of it as "pointer(s)" to "a memory area". Which in fact may be a little redundant.
For example, suppose you have to dynamically store several words on memory, how would you do that? There are several ways to do this, but I'll provide an example that illustrate the use of **.
Now, suppose you want to store three words: hi, hello and goodbye
hi, hello and goodbye are strings, they consume, 2, 5 and 7 bytes on memory respectively. Well, in fact it's 3, 6 and 8 bytes because of the \0, but lets not get into many details.
But one thing is clear, we need three memory areas to hold these strings and also three pointers to reference these memory areas later.
Note that one can just declare three pointers that points to these memory areas, but, would you be willing to declare one thousand pointers to hold one thousand words? This is where ** kicks in.
Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUMBER_OF_WORDS 3
int
main(int argc, char **argv)
{
int i;
char **words;
/* pointers */
words = malloc(sizeof(char*)*NUMBER_OF_WORDS);
/* memory areas*/
words[0] = strdup("Hi");
words[1] = strdup("Hello");
words[2] = strdup("Goodbye");
for(i=0; i < NUMBER_OF_WORDS; i++)
printf("%d) %s\n", i, words[i]);
for(i=0; i < NUMBER_OF_WORDS; i++)
free(words[i]); /* memory area */
free(words); /* pointers */
return 0;
}
I got a weird question to do as an exercise :
Write a function which take a pointer of a pointer of a pointer of a pointer of a pointer of a pointer of a pointer of a pointer of a pointer of an int as a parameter and assign a value to it.
I think the function I wrote is right (please correct if it's not) but how can I test it ?
void function(int *********anInt)
{
*********anInt = 5;
}
I tried :
int main(void) {
int *********nbr = malloc(sizeof(int));
function(nbr);
printf("%d", *********nbr);
}
But I get a segfault, I just learned about malloc and pointers so I don't fully understand it.
Of course, you can test it, although it looks weird.
#include <stdio.h>
void function(int *********anInt)
{
*********anInt = 5;
}
int main()
{
int n = 0;
int *p1 = &n;
int **p2 = &p1;
int ***p3 = &p2;
int ****p4 = &p3;
int *****p5 = &p4;
int ******p6 = &p5;
int *******p7 = &p6;
int ********p8 = &p7;
function(&p8);
printf("%d\n", n);
return 0;
}
Try
int main() {
int *********nbr;
nbr = malloc(sizeof(int********));
*nbr = malloc(sizeof(int*******));
**nbr = malloc(sizeof(int******));
***nbr = malloc(sizeof(int*****));
****nbr = malloc(sizeof(int****));
*****nbr = malloc(sizeof(int***));
******nbr = malloc(sizeof(int**));
*******nbr = malloc(sizeof(int*));
********nbr = malloc(sizeof(int));
function(nbr);
printf("%d", *********nbr);
}
You'll need a ridiculous main program to go with the assignment from hell!
int main(void)
{
int l0 = 0;
int *l1 = &l0;
int **l2 = &l1;
int ***l3 = &l2;
int ****l4 = &l3;
int *****l5 = &l4;
int ******l6 = &l5;
int *******l7 = &l6;
int ********l8 = &l7;
printf("%d %d %d %d %d %d %d %d %d\n", l0, *l1, **l2, ***l3, ****l4, *****l5,
******l6, *******l7, ********l8);
function(&l8);
printf("%d %d %d %d %d %d %d %d %d\n", l0, *l1, **l2, ***l3, ****l4, *****l5,
******l6, *******l7, ********l8);
return 0;
}
Untested: maybe I didn't count something right, but the general idea is about correct. This is a torture test — for innocent C programmers and for compilers.
An int** is a pointer that points to a pointer:
int myInt;
int* pInt = &myInt;
int** ppInt = &pInt;
An int*** is a pointer that points to a pointer that points to a pointer:
int*** pppInt = &ppInt;
To test your function, you need to carry this on and on, the right number of times.
See md5's solution, however it lacks explaination
Explained:
The reason your test program didn't work is because malloc returns a void* which is simply a memory address (a pointer). You assigned this to an int*****... which means when the program tries to dereference down to the actual int what it's doing is first taking the memory address of the int and dereferencing it (which is okay) but after this since your value (5) is now the value it then derefences that, which should come back with your segfault.
Think of the assignment as nested dereferences:
int ********p8 = *anInt; // p8 == 5
int *******p7 = *p8; // This breaks since dereferencing memory
// address 5 results in a segfault
What was done to avoid this was we actually nested the pointers that way when dereferencing for assignment we have memory addresses (pointers) to dereference to eventually get to the memory address which stores the value.
I don't understand why this works:
void main() {
int * b;
b = (int *)malloc(sizeof(int));
*b = 1;
printf("*b = %d\n", *b);
}
while this does not (gets segmentation fault for the malloc()):
void main() {
int ** a;
int i;
for (i = 0; i<= 3; i++) {
a[i] = (int*)malloc(sizeof(int));
*(a[i]) = i;
printf("*a[%d] = %d\n", i, *(a[i]));
}
}
since I find a[i] is just like b in the first example.
BTW, a[i] is equal to *(a+i), right?
You need to allocate memory for a first, so that you can access its members as a[i].
So if you want to allocate for 4 int * do
a = malloc(sizeof(int *) * 4);
for (i = 0; i<= 3; i++) {
...
}
or define it as array of integer pointers as
int *a[4];
a is a 2 dimensional pointer, you have to allocate both dimension.
b is a 1 dimensional pointer, you have to allocate only one dimension and that's what you're doing with
b = (int *)malloc(sizeof(int));
So in order the second example to work you have to allocate the space for the pointer of pointer
void main() {
int ** a;
int i;
a = (int**)malloc(4*sizeof(int*));
for (i = 0; i<= 3; i++) {
a[i] = (int*)malloc(sizeof(int));
*(a[i]) = i;
printf("*a[%d] = %d\n", i, *(a[i]));
}
The allocated pointer is written to uninitialized memory (you never set a to anything), causing undefined behavior.
So no, it's not at all equivalent to the code in the first example.
You would need something like:
int **a;
a = malloc(3 * sizeof *a);
first, to make sure a holds something valid, then you can use indexing and assign to a[0].
Further, this:
a[i] = (int*)malloc(sizeof(int));
doesn't make any sense. It's assigning to a[i], an object of type int *, but allocating space for sizeof (int).
Finally, don't cast the return value of malloc() in C.
actually malloc it's not that trivial if you really want safe and portable, on linux for example malloc could return a positive response for a given request even if the actual memory it's not even really reserved for your program or the memory it's not writable.
For what I know both of your examples can potentially return a seg-fault or simply crash.
#ruppells-vulture I would argue that malloc is really portable and "safe" for this reasons.