Re: [Dev-C++] Doubt about pass pointer to int.
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Per W. <pw...@ia...> - 2004-02-29 22:16:09
|
Since C and C++ does call by value, change_int will get a COPY of the
original pointer. This is fine if you want to change the value that the
pointer points to. However, with a COPY of the pointer, you can't allocate
a new pointer within change_int, and expect it to survive back to the
caller. In this case you are released the memory that the original
"number" pointer had allocated, but you don't change "number" to point to
the newly allocated block.
In C, you should use double indirection, i.e. pointer to pointer as can be
seen in my changes below.
Note that your change_int() has an incorrect name since it doesn't change
an int, but instead reallocates an int.
/Per W
On Sun, 29 Feb 2004, Vinicius wrote:
> Hello,
>
> The output of the code below is:
> number = 10
> number = 0 (or other number except 15)
>
> Why the output of the second 'number' is not 15? Why the 'number' address is
> not changed?
>
> Thanks in advance, Vinicius.
>
>
> #include <stdio.h>
> #include <stdlib.h>
>
> void change_int(int *num);
void change_int(int** num);
>
> int main(void)
> {
> int *number;
>
> number = (int *) malloc(sizeof(int));
> *number = 10;
> printf("number = %d\n", *number);
change_int(&number);
> change_int(number);
> printf("number = %d\n", *number);
>
> free(number);
> system("PAUSE");
> return 0;
> }
>
> void change_int(int *num)
void change_int(int** num)
> {
> int *temp;
int **temp;
>
> temp = num;
temp = *num;
> num = (int *) malloc(sizeof(int));
*num = (int*)malloc(sizeof(int));
> *num = 15;
**num = 15;
> free(temp);
> }
>
>
>
>
> -------------------------------------------------------
> SF.Net is sponsored by: Speed Start Your Linux Apps Now.
> Build and deploy apps & Web services for Linux with
> a free DVD software kit from IBM. Click Now!
> http://ads.osdn.com/?ad_id=1356&alloc_id=3438&op=click
> _______________________________________________
> Dev-cpp-users mailing list
> Dev...@li...
> TO UNSUBSCRIBE: http://www23.brinkster.com/noicys/devcpp/ub.htm
> https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
>
|