gpt4 book ai didi

c - 理解 C : Pointers and Structs

转载 作者:太空宇宙 更新时间:2023-11-04 05:03:10 26 4
gpt4 key购买 nike

我试图更好地理解 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com