理解C:指针和结构

ada*_*ges 0 c pointers data-structures

我正在努力更好地理解c,而我很难理解我在哪里使用*和&字符.而且只是结构一般.这是一些代码:

void word_not(lc3_word_t *R, lc3_word_t A) {
    int *ptr;
    *ptr = &R;
    &ptr[0] = 1;
    printf("this is R at spot 0: %d", ptr[0]);
}  
Run Code Online (Sandbox Code Playgroud)

lc3_word_t是一个像这样定义的结构:

struct lc3_word_t__ {
  BIT b15;
  BIT b14;
  BIT b13;
  BIT b12;
  BIT b11;
  BIT b10;
  BIT b9;
  BIT b8;
  BIT b7;
  BIT b6;
  BIT b5;
  BIT b4;
  BIT b3;
  BIT b2;
  BIT b1;
  BIT b0;
};
Run Code Online (Sandbox Code Playgroud)

这段代码没有做任何事情,它编译但是一旦我运行它我得到一个"分段错误"错误.我只是想了解如何读取和写入结构并使用指针.谢谢 :)


新守则:

void word_not(lc3_word_t *R, lc3_word_t A) {
    int* ptr;
    ptr = &R;
    ptr->b0 = 1;
    printf("this is: %d", ptr->b0);
}
Run Code Online (Sandbox Code Playgroud)

Xav*_*olt 8

这是一个快速的指针纲要(至少我使用它们):

int i;
int* p; //I declare pointers with the asterisk next to the type, not the name;
        //it's not conventional, but int* seems like the full data type to me.

i = 17; //i now holds the value 17 (obviously)
p = &i; //p now holds the address of i (&x gives you the address of x)
*p = 3; //the thing pointed to by p (in our case, i) now holds the value 3
        //the *x operator is sort of the reverse of the &x operator
printf("%i\n", i); //this will print 3, cause we changed the value of i (via *p)
Run Code Online (Sandbox Code Playgroud)

并与结构配对:

typedef struct
{
    unsigned char a;
    unsigned char r;
    unsigned char g;
    unsigned char b;
} Color;

Color c;
Color* p;

p = &c;     //just like the last code
p->g = 255; //set the 'g' member of the struct to 255
            //this works because the compiler knows that Color* p points to a Color
            //note that we don't use p[x] to get at the members - that's for arrays
Run Code Online (Sandbox Code Playgroud)

最后,使用数组:

int a[] = {1, 2, 7, 4};
int* p;

p = a;    //note the lack of the & (address of) operator
          //we don't need it, as arrays behave like pointers internally
          //alternatively, "p = &a[0];" would have given the same result

p[2] = 3; //set that seven back to what it should be
          //note the lack of the * (dereference) operator
          //we don't need it, as the [] operator dereferences for us
          //alternatively, we could have used "*(p+2) = 3;"
Run Code Online (Sandbox Code Playgroud)

希望这能清除一些事情 - 如果我遗漏了任何东西,请不要犹豫,询问更多细节.干杯!