# Thread: pointer arithmetic

1. ## pointer arithmetic

Hi, here is a structure with 2 pointer to integer

I want increment the value of x by 1, (tt.c) ++ is not increment to 11 rather it increments to 14. how do i increment the value pointed by tt.c ? any help?
thx
Code:
#include <stdio.h>
Code:
main () {typedef struct {
Code:
int *c;        int *d; }ABC; ABC  tt;
Code:
int x=10, y=11;    tt.c = &x;      tt.d = &y;
Code:
(tt.c)++ ;  // lincrementing = 10+1
Code:
printf ("value of x %u\n", (tt.c)) ;  }

2. To increment THE VALUE STORED in x: (*tt.c)++

Also, this
Code:
printf("value of x %u/n", (tt.c))
isn't displaying the value stored in x. It's displaying the address of x. You need to dereference it.

clu82

3. Here's a suggestion: when you don't understand program output, sprinkle a few printf()s around.

consider:
Code:
#include <stdio.h>

main ()
{
typedef struct {
int *c;
int *d;
}ABC;

ABC  tt;

int x=10, y=11;
tt.c = &x;
tt.d = &y;

printf("tt.c = %p\n", tt.c);
printf("*tt.c = %d\n", *tt.c);
printf("tt.d = %p\n", tt.d);
printf("*tt.d = %p\n", *tt.d);

// the following makes tt.c point to who-knows-where
(tt.c)++ ;  // lincrementing = 10+1
printf("After incrementing tt.c = %p\n", tt.c);
printf("After incrementing tt.c, *tt.c = %d\n", *tt.c);

// tt.c is a pointer; you are printing the value of the pointer,
// not the value of who-knows-what that tt.c is pointing to
printf ("value of x %u\n", (tt.c)) ;
printf ("value of x %p\n", (tt.c)) ;
return 0;
}
Dave

4. ## Re: pointer arithmetic

The reason (tt.c)++ incremented by 4 is because the value is a pointer and pointers are 4 bytes, to keep them aligned the language will increment by it's size.

Two other points:

First, you need code tags around the entire program, not each line

Second, your formatting is abysmal (based on the removal of code tags). It should be more like:
Code:
#include <stdio.h>
int main ()
{
typedef struct
{
int *c;
int *d;
}ABC;
ABC  tt;
int x=10, y=11;

tt.c = &x;
tt.d = &y;
(tt.c)++ ;  // lincrementing = 10+1
printf ("value of x %u\n", (tt.c)) ;
return 0;
}

Popular pages Recent additions