【发布时间】:2021-03-02 17:29:40
【问题描述】:
如何将字符串存储在结构数组中?当我尝试这个时,我的代码给了我一个分段错误。整数也会发生这种情况。
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
/* get the weight and the object */
struct term{
char term[200]; // assume terms are not longer than 200
double number;
};
int main(void)
{
struct term *new[12];
char word[13]= "hello world";
int num =123;
strcpy(new[0]->term,word);
new[0]->number = num;
char word2[20]= "hello new world";
int num2 =123;
strcpy(new[1]->term,word2);
new[0]->number = num2;
}
【问题讨论】:
-
new[0] 未初始化,因此分配给它的属性当然会出错。请打开编译器警告,这很容易发现。
-
new是指向struct term的指针数组,而不是struct term的数组。 -
最后一行应该是
new[1]->number吗? -
main 的第一行是 'struct term *new[12];'
-
@jwdonahue 当我擦除指针时,它说'表达式必须具有指针类型'
标签: c