Thread: Pointer Arithmetics and Arrays

  1. #1
    Registered User
    Join Date
    Dec 2010
    Posts
    113

    Pointer Arithmetics and Arrays

    I am trying to figure out how pointer arithmetics work on arrays. However I couldn't make an example work.

    Firstly I start with a one dimensional array and the example works;

    Code:
    #include <stdio.h>
    
    int main(void){
        int array[2];
        int *ptr=array;
        *(ptr+1)=1000;
        printf("%d",array[1]);
        return 0;
    }
    After that I add one more dimension and it doesn't show the result I want;

    Code:
    #include <stdio.h>
    
    int main(void){
        int array[2][2];
        int (*ptr)[2]=array;
        *(ptr+1)=999;
        printf("%d",array[1][0]);
        return 0;
    }
    Why doesn't this increase the address by one *ptr[2]? Isn't it possible to perform pointer arithmetics with pointer to arrays?

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Does that second snippet even compile? I get the following error when I try: main.c|6|error: assignment to expression with array type|


    Jim

  3. #3
    Registered User
    Join Date
    Dec 2010
    Posts
    113
    My compiler doesn't give me an error and shows a console window but the one below may compile well. However it still doesn't work.

    Code:
    #include <stdio.h>
     
    int main(void){
        int array[2][2];
        int (*ptr)[2];
        ptr=array;
        *(ptr+1)=999;
        printf("%d",array[1][0]);
        return 0;
    }

  4. #4
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    I think you need one more dereference.
    Code:
    ptr[1][0] = 999;

  5. #5
    Registered User
    Join Date
    Dec 2010
    Posts
    113
    Quote Originally Posted by MutantJohn View Post
    I think you need one more dereference.
    Code:
    ptr[1][0] = 999;
    Thanks for the hint, one more dereference solves the problem. I will think about the logic.

    Code:
    #include <stdio.h>
      
    int main(void){
        int array[2][2];
        int (*ptr)[2];
        ptr=array;
        *(*(ptr+1))=999;
        printf("%d",array[1][0]);
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Wrong array length with pointers arithmetics
    By MartinR in forum C Programming
    Replies: 2
    Last Post: 10-23-2015, 10:06 PM
  2. How fix error? (point arithmetics)
    By grytskiv in forum C Programming
    Replies: 2
    Last Post: 03-13-2011, 01:11 PM
  3. Pointer arithmetics
    By Ducky in forum C Programming
    Replies: 2
    Last Post: 04-05-2010, 09:47 AM
  4. C Pointer Arrays
    By valaris in forum C Programming
    Replies: 3
    Last Post: 07-27-2008, 01:20 AM
  5. Pointer arrays help
    By stevy123 in forum C Programming
    Replies: 7
    Last Post: 04-18-2007, 10:11 AM

Tags for this Thread