Thread: hi , i'm having a problem with pointers in C ...

  1. #1
    Registered User
    Join Date
    Oct 2008

    Question hi , i'm having a problem with pointers in C ...

    I will give a simple example inspired from my problem :
    void change(int *x, int *y){x=y;}
    int main(){
    int *xx,*yy;
    yy = (int*)malloc(sizeof(int));
    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 .


  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    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:
    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.

    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.

  3. #3
    Registered User
    Join Date
    Oct 2008
    So your code that changes the pointer should look like:

    void change(int **x, int **y)
    // ...
    change (&xx, &yy);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with file handling (pointers)
    By hmk in forum C Programming
    Replies: 5
    Last Post: 09-19-2008, 10:03 AM
  2. Problem with pointers
    By kotoko in forum C Programming
    Replies: 3
    Last Post: 06-12-2008, 05:17 AM
  3. A problem with pointers
    By vsla in forum C Programming
    Replies: 2
    Last Post: 10-10-2007, 04:14 AM
  4. Returning pointer to array of pointers problem
    By jimzy in forum C Programming
    Replies: 15
    Last Post: 11-11-2006, 06:38 AM
  5. Problem writing swap using pointers
    By joshdick in forum C++ Programming
    Replies: 1
    Last Post: 02-29-2004, 10:06 PM

Tags for this Thread