Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with C pointers

Tags:

c

pointers

Here's the deal. I have a large character array and am trying to manipulate it. Here's some code I was using to test the idea:

#include <stdio.h>

char r[65536],*e=r;

main() {
    e+=8;
    while(*e) {
        *e+=1;
        e+=5;
        *e-=1;
        e-=1;
    }
    *e+=1;
    printf("%i",*e);
    printf(" %c",e);
}

What it's supposed to do is:

  1. Set the first element to 8
  2. Then, while the current element is not zero,
    1. Move to the next cell
    2. Add 5 to it
    3. Move back
    4. Subtract one. (This repeats 8 times because the while test will fail when it has subtracted the last one)
  3. Display the location of the pointer
  4. Display the contents of the array that the pointer points to (I hope)

What it does:

1 Φ

as opposed to

40 (   

^^ 8 x 5 = 40, so that's what it should display.

Any tips/suggestions/criticism accepted.

like image 821
itdoesntwork Avatar asked Jan 27 '12 13:01

itdoesntwork


3 Answers

You're dereferencing exactly where you should not and vice versa. What you meant to do was:

*e+=8;
while(*e) {
    e+=1;
    *e+=5;
    e-=1;
    *e-=1;
}
*e+=1;
printf("%d",e - r); //index
printf(" %p",e); //pointer value      
printf(" %c",*e); //pointee value

* retrieves the value the pointer points to.

like image 180
Armen Tsirunyan Avatar answered Oct 16 '22 02:10

Armen Tsirunyan


"Set the first element to 8" would be

*e = 8;

"Move to the next cell" would be

e += 1;

and so on.

With e you are accessing the pointer, the address. Incrementing/decrementing it will move the pointer forth and back.

With *e you access the value it is pointing to (dereference it).

You are using it the other way around most of the times.

Remark: Note that in the declaration of e you have to write char *e = r; to initialize the pointer (not the value). Here the * specifies the type of e. The declaration reads: e is a pointer to char and its value is (the address of) e --- it is similar to char *r; r = e;.

like image 7
undur_gongor Avatar answered Oct 16 '22 02:10

undur_gongor


*e dereferences the pointer; that is, it manipulates the value pointed to. Manipulating the pointer itself means manipulating e directly.

When you do e+=5, you're moving the pointer ahead by 5 spaces, if you do *e+=5, then you add 5 to the value pointed to by the pointer.

like image 6
Michael Madsen Avatar answered Oct 16 '22 03:10

Michael Madsen