理解C:指针和结构
我正在努力更好地理解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的一般教程(其中有很多)。 只需检查谷歌。 以下网站有很好的信息,可以更好地解释您的问题。
http://www.cplusplus.com/doc/tutorial/pointers/
http://www.cplusplus.com/doc/tutorial/structures/
它们将帮助您掌握基本语法并了解操作符及其工作原理。 请注意,该站点是C ++,但在C中的基础是相同的。
首先,你的第二行应该给你一些关于将指针转换为int的警告。 第三行我很惊讶编译。 在最高警告级别编译,并注意警告。
*
根据它是在声明还是表达式中执行不同的操作。 在声明中(如int *ptr
或lc3_word_t *R
),它只是意味着“这是一个指针”。
在表达式(如*ptr = &R
)中,它意味着取消引用指针,这基本上是像常规变量一样使用指向的值。
&
表示“取这个地址”。 如果某些东西不是指针,则使用它将其转换为指针。 如果某些东西已经是指针(如函数中的R
或ptr
),则无需再次获取其地址。
int *ptr; *ptr = &R;
这里ptr
没有初始化。 它可以指向任何东西。 然后用*
取消引用它并为其分配R
的地址。 这不应该编译,因为&R
是类型lc3_word_t**
(指向指针的指针),而*ptr
是int
类型。
&ptr[0] = 1;
也不合法。 在这里你取ptr[0]
的地址并尝试分配它1.这也是非法的,因为它是一个右值,但是你可以想到你不能改变变量ptr[0]
的位置,因为你的’基本上尝试做的是改变ptr[0]
的地址。
让我们逐步完成代码。
首先声明一个指向int: int *ptr
的指针。 顺便说一下,我喜欢把它写成这个int* ptr
(用*
而不是ptr
)来提醒自己指针是类型的一部分,即ptr
的类型是指向int
指针。
接下来,将ptr
指向的值分配给R
的地址。 *
取消引用指针(获取指向的值)和&
给出地址。 这是你的问题。 你混淆了这些类型。 将R( lc3_word_t**
)的地址分配给* ptr( int
)将不起作用。
接下来是&ptr[0] = 1;
。 这也没有多大意义。 &ptr[0]
是&ptr[0]
的第一个元素的地址(作为数组)。 我猜你只想要第一个地址的值,即ptr[0]
或*ptr
。