Thread: Passing address to a function, Problems !

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    13

    Passing address to a function, Problems !

    I was trying to pass addresses of 2 variables to a function, but compiler is giving me an error.

    Code:
    add(&array1,&num2);
    Anything wrong with the above code ?

    Error is :
    cannot convert `int (*)[10]' to `int*' for argument `1' to `void add(int*, int*)'

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Yes, there is something wrong. An array name, when passed to a function, is automatically converted to be interpreted as a pointer to the first element of the array in question. Thus the array name is viewed as a pointer when you pass it to a function. Adding the '&' complicates matters. It's the same address and technically the same thing, as far as the hardware is concerned, but there is a technical difference between an array and a pointer in C.

    Thus the solution is to lose the '&' in your first argument.

  3. #3
    Registered User
    Join Date
    Apr 2007
    Posts
    13
    Is there anything wrong with this :

    int array[10];
    int *array_pointer;

    array_pointer=&array;

  4. #4
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Yes, there is something wrong. Same principle as I explained above.

    Contrary to what some may think, I'm not a human compiler. Please read what I said in detail. It explains exactly why there is an issue with this. Just to clarify, yet, again, there is a difference between an array and a pointer. At the hardware level, no such difference necessarily exists with what you're doing, but in C, as far as the type of the data is interpreted by the compiler, there is a huge difference.

  5. #5
    Registered User
    Join Date
    Apr 2007
    Posts
    13
    Quote Originally Posted by MacGyver View Post
    Contrary to what some may think, I'm not a human compiler.
    lol, that cracked me up.

    Well, your explanation helped ! Thanks a ton !

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. Problems passing parameter to function
    By HAssan in forum C Programming
    Replies: 5
    Last Post: 10-21-2008, 02:26 PM
  3. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  4. Including lib in a lib
    By bibiteinfo in forum C++ Programming
    Replies: 0
    Last Post: 02-07-2006, 02:28 PM
  5. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM