【问题标题】:Char** in a structure in C : segmentation fault 11C 中结构中的字符**:分段错误 11
【发布时间】:2014-10-19 12:40:30
【问题描述】:

我有一个问题,试图在 C 语言的结构中使用 char**。

我的代码的目的是保留字符串的历史记录。该结构有 2 个变量:

codeJuste,它是一个 NB_PION 字符的字符串。 codeProposes,它是一个 NB_COUPMAX 案例的数组。每个案例都有一个代码,它是一个 NB_PION 字符的字符串。

我正在尝试写入代码建议的每种情况,但出现分段错误错误。提前感谢您尝试帮助我(对不起我的英语,我是法国人)。

这是我的测试代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

#define NB_PION 4
#define NB_COULEUR 4
#define NB_COUPMAX 6

//Définition d'une structure
typedef struct _Partie{
    char* codeJuste;
    char** codesProposes;
} Partie;


int main (int argc,char** argv[]){
    Partie maPartie;

    maPartie.codeJuste = malloc((NB_PION+1) * sizeof(char));
    strcpy(maPartie.codeJuste,"AAAA");

    maPartie.codesProposes = malloc(NB_COUPMAX * ((NB_PION + 1) * sizeof(char)));
    strcpy(maPartie.codesProposes[0],"BBBB");
    strcpy(maPartie.codesProposes[1],"CCCC");

    printf("1:%s \n",maPartie.codeJuste);
    printf("2:%s \n",maPartie.codesProposes[0]);
    printf("3:%s \n",maPartie.codesProposes[1]);
}

【问题讨论】:

  • 你从哪里得到错误(哪一行),它到底说了什么?
  • o_weisman :编译后启动程序时出现错误。错误是“分段错误:11”

标签: c string struct char


【解决方案1】:

改变这个:

maPartie.codesProposes = malloc(NB_COUPMAX * ((NB_PION + 1) * sizeof(char)));

到这里:

maPartie.codesProposes = malloc(NB_COUPMAX * sizeof(char*));
for (i=0; i<NB_COUPMAX; i++)
    maPartie.codesProposes[i] = malloc((NB_PION+1) * sizeof(char));

并且不要忘记在程序执行的稍后时间取消分配所有内容:

for (i=0; i<NB_COUPMAX; i++)
    free(maPartie.codesProposes[i]);
free(maPartie.codesProposes);

【讨论】:

  • 谢谢,但它也不起作用。我在程序开始时遇到同样的错误:分段错误:11.
  • @clmt974:嗯,它对我来说非常好用......我之前“错过了[i]”,也许你在我修复它之前尝试使用它......
  • 谢谢,修改前我试过了。实际上,您的代码有效:) 再次感谢您。
【解决方案2】:

改成这样:

typedef struct _Partie{
    char *codeJuste;
    char (*codesProposes)[NB_PION+1];
} Partie;


maPartie.codesProposes = malloc(NB_COUPMAX * sizeof(char [NB_PION+1]));

【讨论】:

  • 非常感谢。它完美运行 BLUEPIXY!你能解释一下你的解决方案和我的旧解决方案之间的区别吗?
  • @clmt974 如果你想使用双指针,你必须像 barak manos。 MaPartie.codesProposes[0] 在这种情况下是一个指针,但这需要指向char [NB_PION+1] 的区域。我的代码只需要确保区域大小,因为在我的方式中是 codesProposes 指向 char [NB_PION+1] 的指针。
猜你喜欢
  • 2015-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-21
  • 1970-01-01
相关资源
最近更新 更多