【问题标题】:How to store string in a struct array?如何将字符串存储在结构数组中?
【发布时间】: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]-&gt;number吗?
  • main 的第一行是 'struct term *new[12];'
  • @jwdonahue 当我擦除指针时,它说'表达式必须具有指针类型'

标签: c


【解决方案1】:

struct term *new[12] 是一个指针数组,它们未初始化,为了在其中存储任何内容,您必须使指针指向某个有效的内存位置,或者为它们分配内存:

struct term *new[12];

for (int i = 0; i < 12; i++)
{
    new[i] = malloc(sizeof **new);
}

或者通过其他方式为它们分配有效的struct term 变量,

struct term st;
new[0] = &st;

无论如何,对于这么小的数组,您可以只使用固定大小的数组, struct term new[12]

malloc 是一个涉及多个系统调用的繁重函数,如果可以的话,你应该避免它。

为了更好地了解应该在何时何地使用动态内存分配,请查看以下内容:

When and why to use malloc?

When do I need dynamic memory?


您应该在代码中解决另一个问题,char word2[13] = "hello new world" 格式错误,字符串对于其容器来说太大了。它需要至少 16 个字符的空间。

在分配字符串时使用空边界,char word2[] = "hello new world",编译器将推断出字符串所需的大小,避免出现此类错误。


脚注

new 是 C++ 中的保留关键字,用于分配内存,在功能上等同于 C 的 malloc,虽然在 C 中允许使用,但我会避免使用它来命名变量。

【讨论】:

  • 所以你的意思是添加这样的东西? 'struct term *new = malloc(12*sizeof(struct term));'
  • 不,您已经在堆栈上分配了指针数组。这是您需要使用new[0] = malloc(sizeof(struct term));分配的指针
  • @beautifulworld,对于所有的指针,我编辑了我的答案。
  • @anastaciu,或者 OP 可以通过简单地声明 struct term new[MAX_TERMS]; 然后使用 dot 取消引用它们来避免所有麻烦。我认为 OP 还不了解本地存储和堆存储之间的区别。
  • 我可以添加那个名字new 不是好的选择。最好改一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-22
  • 2011-07-04
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
相关资源
最近更新 更多