C Board  

Go Back   C Board > General Programming Boards > C Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 10-25-2008, 04:53 PM   #1
Registered User
 
Join Date: Oct 2008
Posts: 4
Question hi , i'm having a problem with pointers in C ...

I will give a simple example inspired from my problem :
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 doesn't point to the value of yy (*yy) , the program prints "is null" . Why ?

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   Reply With Quote
Old 10-25-2008, 05:06 PM   #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);
x could be all values that are valid for an integer.

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   Reply With Quote
Old 10-26-2008, 03:57 AM   #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   Reply With Quote
Reply

Tags
c language, c++ language, pointer, pointers, problem

Thread Tools
Display Modes

Forum Jump

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


All times are GMT -6. The time now is 11:05 PM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.0 RC2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22