![]() |
| | #1 |
| Registered User Join Date: Oct 2008
Posts: 4
| Code: void change(int *x, int *y){x=y;}
int main(){
int *xx,*yy;
yy = (int*)malloc(sizeof(int));
change(xx,yy);
if(xx == NULL)printf("is null\n");
else printf("---- %d ----\n",*xx);
.................................................. .........
xx and yy must be declared int* , it's something that i must do in my program . and xx =yy must be done in a function , not in main . 10x |
| blackslither is offline | |
| | #2 |
| Kernel hacker Join Date: Jul 2007 Location: Farncombe, Surrey, England
Posts: 15,686
| Since your swap function only changes the local variables inside the function change, you will not see any effect in main. To modify a pointer, you need to pass a pointer to pointer - this applies to all of C: to change something, you need to know it's location, so you need a pointer. Considering that xx could be just about any value in the world that can be held in a pointer, who knows what is going to happen. Only yy is initialized. It's exactly the same as: Code: int x;
printf("%d\n", x);
Unless a local variable is actually given a value, it will have whatever value happens to be in it's location in memory. -- Mats
__________________ Compilers can produce warnings - make the compiler programmers happy: Use them! Please don't PM me for help - and no, I don't do help over instant messengers. |
| matsp is offline | |
| | #3 |
| Registered User Join Date: Oct 2008
Posts: 2
| So your code that changes the pointer should look like: Code: void change(int **x, int **y)
{
*x=*y;
}
// ...
change (&xx, &yy);
Daper http://www.linuxprogrammingblog.com |
| Daper is offline | |
![]() |
| Tags |
| c language, c++ language, pointer, pointers, problem |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Problem with file handling (pointers) | hmk | C Programming | 5 | 09-19-2008 10:03 AM |
| Problem with pointers | kotoko | C Programming | 3 | 06-12-2008 05:17 AM |
| A problem with pointers | vsla | C Programming | 2 | 10-10-2007 04:14 AM |
| Returning pointer to array of pointers problem | jimzy | C Programming | 15 | 11-11-2006 06:38 AM |
| Problem writing swap using pointers | joshdick | C++ Programming | 1 | 02-29-2004 10:06 PM |