c - 理解 C : Pointers and Structs

标签 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]);
}  

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

希望这能解决一些问题 - 如果有任何遗漏,请不要犹豫,询问更多详细信息。干杯!

关于c - 理解 C : Pointers and Structs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5148512/

相关文章:

c - 关于逐像素渲染位图算法的建议

c - Unix - 从子阻塞排序

c - 这个使用 RECURSION 删除给定数组中所有强数字的函数有什么错误?

c - 在缓冲区溢出的情况下利用 C 中的 strcpy(),

C - 使用指向字符数组的指针打印网格

c# - 如何从 O(1) 中匹配特定条件的数组中选择随机元素

c - 从指针访问数组会给出不断变化的错误值

c - 从指针数组中检索数组

r - 具有多个组件的RHadoop key

java - java链接集实现