【问题标题】:Segmentation fault with strcpy() with array of pointers to structures带有指向结构的指针数组的 strcpy() 分段错误
【发布时间】:2013-03-31 02:33:52
【问题描述】:

常量:

#define MAX_OPCODE_NAME_LEN 4

我有一个结构数组:

OPCODE *mot[NUM_OPCODES];

结构定义:

typedef struct opcode {
char name[MAX_OPCODE_NAME_LEN + 1];
char format;
int type;
} OPCODE;

在我的代码中:

strcpy(mot[0]->name, "hlt");
strcpy(mot[1]->name, "add");
strcpy(mot[2]->name, "sub"); // seg fault on this command
strcpy(mot[3]->name, "mul");
// ...more code follows

我的代码在这里给了我一个分段错误,我不知道为什么,因为它应该有足够的空间来容纳 5 个字符(4 个字符后跟 '\0'),所以它不应该用完空间,而我只是将字符串文字复制到静态内存位置。也许是我错误地定义了结构或在错误的位置使用了指针箭头?

【问题讨论】:

  • 您是否分配了名为mot 的指针数组?
  • 我将其定义为OPCODE *mot[NUM_OPCODES];,但这就是我所做的一切。我需要 malloc 其他东西吗?
  • 这不会分配 4 个指针指向的任何内存。

标签: c string pointers segmentation-fault strcpy


【解决方案1】:
OPCODE *mot[NUM_OPCODES];

是一个指向OPCODE的指针数组。不是OPCODEs 的数组

您必须为存储在 mot 中的每个指针分配 OPCODE 内存,或者(对于当前代码更简单的方法)只需将 mot 设为 OPCODEs 的数组

OPCODE mot[NUM_OPCODES];
       ^^

并以如下方式访问值

strcpy(mot[0].name, "hlt");
strcpy(mot[1].name, "add");  ....
             ^^

【讨论】:

  • OPCODE mot[NUM_OPCODES];strcpy(mot[0].name, "hlt"); 工作,谢谢。
  • @ICantNameMe 很高兴为您提供帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-18
  • 1970-01-01
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
相关资源
最近更新 更多