我将分两套阅读char*
(或字符串)使用strtok
,并且由于这两组字符是相关的,(address : command\n)
我决定使用一个结构。
struct line* array = (struct line*)malloc(sizeof(file) * sizeof(struct line*));
这条线malloc
函数的空间给了我一个分段错误,我想知道你是否能告诉我一个正确的方法malloc
它的空间。对于上下文,这是我的其余代码:
struct line
{
char* addr;
char* inst;
};
while loop{
x = strtok(line,": ");
y = strtok(NULL,"\n");
strcpy(array[i].addr,x); //assume that x and y are always 3characters
strcpy(array[i].inst,++y);
i++;
}
所有类型的分配工作都是相同的。如果您需要分配一个数组line
结构,你可以这样做:
struct line* array = malloc(number_of_elements * sizeof(struct line));
在您的代码中,您分配了一个具有适当大小的数组line
指针,不是为了line
结构。另请注意,没有理由强制转换返回值malloc()
.
请注意,这是更好的使用方式:
sizeof(*array)
代替:
sizeof(struct line)
这样做的原因是,如果您更改类型,分配仍将按预期工作array
。在这种情况下,这是不太可能的,但这只是一个值得习惯的一般事情。
另请注意,可以避免重复该单词struct
一遍又一遍地,由typedef
结构体:
typedef struct line
{
char* addr;
char* inst;
} line;
然后你可以这样做:
line* array = malloc(number_of_elements * sizeof(*array));
当然不要忘记也分配内存array.addr
and array.inst
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)