Thread: Pointer notation help!

  1. #1
    Registered User
    Join Date
    Mar 2011
    Posts
    1

    Exclamation Pointer notation help!

    The following code is used to swap numbers in an array. However I just found out that it has to be in pointer notation. I have been trying several ways with the indirection operator, but I cannot seem to get it to compile... Any suggestions would be a great help thanks! Here is my code:

    temp = my_code[0];
    my_code[0] = my_code[2];
    my_code[2] = temp;
    temp = my_code[1];
    my_code[1] = my_code[3];
    my_code[3] = temp;

    By the way, I am doing this in a function which uses pass by reference if that means anything?

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    my_code[x] is equivalent to *(my_code + x).

    Of course, the instructor probably wants something more like:
    Code:
    int *swap1 = &my_code[0];
    int *swap2 = &my_code[2]; // Or: int *swap2 = my_code + 2 (see above)
    temp = *swap1;
    *swap1 = *swap2;
    *swap2 = temp;
    Or maybe your instructor wants a function for it, that you'd call like: swap(&my_code[0], &my_code[2]);
    ...and is declared like: void swap(int *first, int *second)
    Last edited by itsme86; 03-23-2011 at 09:12 AM.
    If you understand what you're doing, you're not learning anything.

  3. #3
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    We'd have to see the code and the parameter declarations. my_code[0] my already be a pointer... or a huge struct. Can't tell.

  4. #4

  5. #5
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Quote Originally Posted by nonoob View Post
    We'd have to see the code and the parameter declarations. my_code[0] my already be a pointer... or a huge struct. Can't tell.
    The OP said the posted code swaps numbers in an array.
    If you understand what you're doing, you're not learning anything.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointer to a function pointer
    By @nthony in forum C Programming
    Replies: 3
    Last Post: 05-30-2010, 05:13 PM
  2. Ban pointers or references on classes?
    By Elysia in forum C++ Programming
    Replies: 89
    Last Post: 10-30-2007, 03:20 AM
  3. Question About Pointer To Pointer
    By BlitzPackage in forum C++ Programming
    Replies: 2
    Last Post: 09-19-2005, 10:19 PM
  4. Could somebody please help me with this C program
    By brett73 in forum C Programming
    Replies: 6
    Last Post: 11-25-2004, 02:19 AM
  5. towers of hanoi problem
    By aik_21 in forum C Programming
    Replies: 1
    Last Post: 10-02-2004, 01:34 PM

Tags for this Thread