(作业问题) 我刚刚学习 C,我正在编写一个程序,从文件中读取数据,创建该数据的路由器,并将指向路由器的指针放入大小为 255 的数组中,但我不断收到标题错误我试图将它们添加到数组中
#define ARRAY_SIZE 255
struct router routers[ARRAY_SIZE] = {0};
int main(int argc, char *argv[]){
unsigned char id;
char name[32];
struct router *new_router;
if(argc == 2){
//reads file with fread
//setting id and name which prints out as expected
new_router = make_router(id, name); //initialising method that returns a router pointer
routers[new_router->id] = new_router;
//error occurs here, at [new_router->id]. Have also tried just using id
}
}
我搜索了很多具有相同错误消息的线程,但它们要么是没有声明数组的人,要么是建议尝试使用 unsigned char 作为索引号,这就是我的意思我已经在使用了。希望对此有所了解。
struct router{
unsigned char id;
char name[32];
}
struct router* make_router(unsigned char id, char* name){
struct router *r = malloc(sizeof(struct router));
r->id = id;
r->name = name;
return r;
}
最佳答案
假设make_router
动态分配一个结构体,那么
routers[new_router->id] = *new_router; // note *
解决了编译器错误。
但是,如果结构具有指针成员,则无法像这样复制结构。您说“路由器只是一个基本结构,其中 id 为 unsigned char,name 为 char*”,情况就是如此。但通过这样的分配,您将不会获得所指向数据的硬拷贝。
指针不是数据。它们不包含数据。他们指向分配在其他地方的数据。
所以,您实际上正在寻找的是一个指针数组,正如另一个答案中所建议的那样。如果是这样,你必须重新编写这个程序。
关于c - 下标值既不是数组,也不是指针,也不是数组索引处的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46449315/