如果我有一个指向结构的指针,该结构具有指向结构的数组?如何访问特定的数组元素? [英] How do I access a specific array element if I have a pointer to a struct which has a pointer to and a array of structs?
问题描述
如果我有一个指向结构的指针,如何指向一个结构数组的指针,我如何访问特定的数组元素?
struct node {
int number;
};
struct queue {
struct node * array;
};
int main(){
struct queue *队列;
struct node * t;
queues =(struct red *)malloc(sizeof(struct queue));
queues- > array =(struct node *)malloc(10 * sizeof(struct node));
queues-> array-> number = 5;
queues- >(数组+ 1) - >数字= 6
}
我的尝试:
queues-> array-> number可以访问第一个元素,但是如何访问其他元素?
queues->(array + i) - >数字不起作用和
queues-> array [i] - >数字不起作用
您需要使用点引用器,因为array [i]
是一个正确的引用,而不是一个指针(我知道它很混乱,但这是C中的规则)。所以你应该按如下方式编写代码:
int i = 3 跨度>; // 或任何其他偏移量
queues-> array [i] .number = < span class =code-digit> 6 ;
首先,让它编译! red未声明:
queues =(struct red *)malloc(sizeof(struct queue));我假设你的意思是:
queues =(struct queue *)malloc(sizeof(struct queue));
然后只需将它用作数组:queues-> array [1] .number = 6;
struct node * n = queues-> array;
for(int i = 0; i< 10; i ++)
{
printf(%u \ nn,n [i]);
}会给你:
5
6
0
0
0
0
0
0
0
0(尽管零可能会被随机数据替换,具体取决于您的编译器)
How do I access a specific array element if I have a pointer to a struct which has a pointer to an array of structs?
struct node {
int number;
};
struct queue {
struct node *array;
};
int main() {
struct queue *queues;
struct node *t;
queues = (struct red*)malloc(sizeof(struct queue));
queues->array = (struct node*)malloc(10 * sizeof(struct node));
queues->array->number = 5;
queues->(array + 1)->number = 6
}
What I have tried:
queues->array->number can access the first element,but how do i access other elements?
queues->(array + i)->number doesnt work and
queues->array[i]->number doesnt work
You need to use the dot referencer sincearray[i]
is a proper reference, rather than a pointer (I know it's confusing but that is the rule in C). So you should code it as follows:
int i = 3; // or any other offset queues->array[i].number = 6;
First off, get it to compile! "red" is not declared:
queues = (struct red*)malloc(sizeof(struct queue));I assume you meant:
queues = (struct queue*)malloc(sizeof(struct queue));
Then just use it as an array:queues->array[1].number = 6; struct node *n = queues->array; for (int i = 0; i < 10; i++) { printf("%u\n", n[i]); }Will give you:
5 6 0 0 0 0 0 0 0 0(Though the zeros may be replaced with random data, depending on your compiler)
这篇关于如果我有一个指向结构的指针,该结构具有指向结构的数组?如何访问特定的数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!