C中的结构到二维结构指针赋值
我想用这段代码工作,我在efnet和freenode中搜索并询问,但我没有找到答案 我想要的是将一个结构C中的结构到二维结构指针赋值,c,pointers,struct,C,Pointers,Struct,我想用这段代码工作,我在efnet和freenode中搜索并询问,但我没有找到答案 我想要的是将一个结构woot分配给另一个二维结构woot*,我需要malloc 那么,如何在那里使用malloc,以及如何分配结构?谢谢 #include <stdio.h> struct omg { int foo; }; struct woot { struct omg *localfoo; int foo; }; int a = sizeof(struct woot);
woot
分配给另一个二维结构woot*
,我需要malloc
那么,如何在那里使用malloc
,以及如何分配结构?谢谢
#include <stdio.h>
struct omg {
int foo;
};
struct woot {
struct omg *localfoo;
int foo;
};
int a = sizeof(struct woot);
int main(void){
struct woot *what[10][10] = (struct woot *) malloc(100*a);
struct omg hahaha[100];
hahaha[1].foo = 15;
what[1][6].localfoo = &hahaha[1];
}
#包括
结构omg{
int foo;
};
结构低音{
结构omg*localfoo;
int foo;
};
int a=sizeof(结构低音);
内部主(空){
结构woot*what[10][10]=(结构woot*)malloc(100*a);
结构omg hahaha[100];
哈哈哈[1],foo=15;
what[1][6].localfoo=&hahaha[1];
}
我很好奇,这段代码甚至可以编译吗?(编辑:不,它没有。)在任何情况下:
struct woot*what[10][10]代码>应该足够了
#include <stdio.h>
#include <stdlib.h> // needed for malloc()
struct omg {
int foo;
};
struct woot {
struct omg *localfoo;
int foo;
};
int main(void){
const int a = sizeof(struct woot); /* there is no reason "a" should be global...
actually, "a" is not needed at all, and, even if it
were needed, it should be declared as "const" :) */
struct woot *what[10][10];
struct omg hahaha[100];
hahaha[1].foo = 15;
what[1][6]->localfoo = &hahaha[1];
what[7][2] = malloc(a); // I would write "malloc(sizeof(struct woot))"
return 0; // main() should return an int, as declared!
}
#包括
#包含//malloc()所需的
结构omg{
int foo;
};
结构低音{
结构omg*localfoo;
int foo;
};
内部主(空){
const int a=sizeof(struct woot);/*没有理由“a”应该是全局的。。。
事实上,根本不需要“a”,即使
如果需要,则应声明为“const”:*/
struct woot*what[10][10];
结构omg hahaha[100];
哈哈哈[1],foo=15;
what[1][6]->localfoo=&hahaha[1];
what[7][2]=malloc(a);//我会写“malloc(sizeof(struct-woot))”
return 0;//main()应返回声明的int!
}
您试图用标量值(malloc返回的指针)初始化数组。如果确实需要指向结构的指针的10×10矩阵(而不是结构的10×10矩阵),则不需要malloc:
//Statically allocated 10x10 matrix of pointers, no need for malloc.
struct woot *what[10][10];
要将指针指定给该矩阵中的单元格,请执行以下操作:
struct woot oneSpecificWoot;
what[1][2] = &oneSpecificWoot;
如果这真的是你想要的,你可以动态地创建一堆Woot并填充它。大概是这样的:
int i, j;
for(i=0; i<10; i++) {
for(j=0; j<10; j++) {
what[i][j] = malloc(sizeof(struct woot));
//Of course, you should always test the return value of malloc to make sure
// it's not NULL.
}
}
如果Woot是在其他地方创建的,并且您只希望在网格布局中引用它们,或者如果您在编译时不知道网格的尺寸,则第一种情况(指针的二维数组)更可能发生。但是在您的代码中,您使用malloc来创建固定数量的代码,因此您最好让编译器静态地分配它们。一般来说,在C中强制转换
malloc
的返回值不是一个好主意(不适用于C++)然后,我们在堆栈溢出上有一个关于这个特定主题的帖子:除非你的代码应该被编译成C++代码,否则这是不被接受的。在C中,void*
隐式转换为任何指针类型。您可能想向编写该页面的讲师显示此链接。我有一个非常基本的C,此代码用于C。我真的不知道在您选择的标识符上做些什么!但是什么[1][6]。localfoo=&hahaha[1];必须是什么?它可以在我的PC上干净地编译(Windows上的GCC 4.4.1)。
int i, j;
for(i=0; i<10; i++) {
for(j=0; j<10; j++) {
what[i][j] = malloc(sizeof(struct woot));
//Of course, you should always test the return value of malloc to make sure
// it's not NULL.
}
}
//A 10x10 matrix of woots, no malloc required.
struct woot what[10][10];