理解 C:指针和结构

2024-04-30

我试图更好地理解 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]);
}  

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;
};

这段代码没有做任何事情,它可以编译,但是一旦我运行它,我就会收到“分段错误”错误。我只是想了解如何读取和写入结构以及使用指针。谢谢 :)


新代码:

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

这是指针的快速概述(至少在我使用它们时):

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)

并与结构配对:

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

最后,使用数组:

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;"

希望这能澄清一些事情——如果我遗漏了什么,请毫不犹豫地询问更多细节。干杯!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

理解 C:指针和结构 的相关文章

随机推荐