Chr*_*ris 3 c compiler-construction pointers compiler-errors
我有一个结构类型的指针,我做了.在程序启动它开始为NULL然后我malloc/realloc因为我需要添加/删除这些结构我只是用我的指针指向第一个结构并像数组一样穿过它.
当我malloc/realloc时,我总是使内存中"数组"/区域的大小比它需要的大.我这样做,所以我可以将内存中的"最后一个索引"/区域设置为NULL,所以我可以说像while(指针!= NULL).
我得到错误:当我尝试将NULL分配给内存数组/内存区域中的最后一个位置时,赋值无效:
// Realloc remotelist by adding one to connrhosts
connrhosts++;
remotelist = realloc(remotelist, sizeof(rhost)*(connrhosts + 1));
(remotelist + connrhosts) = NULL;
Run Code Online (Sandbox Code Playgroud)
我想我说的是:
据我所知(或感觉)我做的一切都是正确的,但我现在已经在这个项目上工作了一段时间,而且我的印象是我有隧道视野.我希望有一双新鲜的眼睛看看我的逻辑/代码,让我知道他们的想法和我做错了什么.再次感谢.:d
编辑 - 我的一部分问题是我认为我对使用指针做什么有误解.
这是我的结构:
typedef struct {
char address[128]; // Buffer that holds our address of the remote host
int port; // Port of the remote host
int conn; // FD to the connection of our remote host
int ofiles; // Open files associated with the remote host
} rhost;
Run Code Online (Sandbox Code Playgroud)
我希望我能做的是循环我的数组/内存区域,并说如果它不是NULL然后用它做一些事情.所以我的原始循环语句是while(NULL!= remotelist).现在我相信正在阅读这些逻辑错误的回复和评论,因为我正在检查指针是否为空?我应该检查指针所指向的内存/结构区域是否为空?如果是这种情况,它应该像while(NULL!=*(remotelist + someoffset))?
我正在这样做,因为我的老师在课堂上建议它/谈论它.
我对remotelist的初始声明/初始化是:rhost*remotelist = NULL;
小智 6
当LHS是一个不能成为可分配变量的求值表达式时,会发生错误的左值赋值.你正在做什么看起来像应该在RHS上的操作(指针算术).
你能做的是:
remotelist[connrhosts] = NULL; // array notation asuming
// remotelist is an array of pointers
Run Code Online (Sandbox Code Playgroud)
假设connrhosts是int或size_t,或者你可以这样做:
remotelist += connrhost; // pointer arithmetic
*remotelist = NULL; // assuming remotelist is an array of pointers.
Run Code Online (Sandbox Code Playgroud)