【问题标题】:Dynamically allocated multidimensional array动态分配的多维数组
【发布时间】:2020-04-24 13:11:30
【问题描述】:

我正在尝试使用malloc 定义一个字符串数组,但某些值返回访问冲突错误。由于整个程序很广泛,我只添加了声明矩阵的部分:

int main(void)
{
    char* temp;
    char p[MAXSIZE];
    printf("This program lists the possible permutations of a character sequence\n");
    printf("Enter your sequence: ");
    scanf_s("%s", &p, MAXSIZE);
    temp = malloc(sizeof(char) * (strlen(p)));
    int count[MAXSIZE / 2] = { 0 };
    char* y = checkforrepetition(p, count);
    char** u = malloc(sizeof(char) * possibilities(count,strlen(p))*MAXSIZE);
    for (int i = 0; i <= (possibilities(count,strlen(p)) - 1); i++)
    {
        u[i] = malloc(sizeof(char)*MAXSIZE);
    }
    recursivepermute(p, 0, temp, strlen(p), u, possibilities(count,strlen(p)));
}

我正在使用scanf_s,因为 Visual Studio 要求我这样做。 我想知道错误是数组本身的声明有问题,还是代码中的其他地方有错误。

简单的解释是:可能性函数返回用户提供的字符串可能的组合数量。数组u的目的是存储已经做出的排列,以避免相同的组合在字符串中出现重复字符。

【问题讨论】:

  • 访问冲突在哪一行代码上触发?
  • scanf_s() 调用看起来没问题,只是您应该传递 p 而不是 &amp;p。但是,这不应该是问题的原因。
  • 在for循环上触发,应该确定第一个数组的元素
  • OTOH,调用temp = malloc(sizeof(char) * (strlen(p))); 没有为字符串末尾的空字节分配足够的空间;这很容易成为问题。
  • malloc(sizeof(char) * possibilities(count,strlen(p))*MAXSIZE) 应该改为 sizeof(char *)。或者更好sizeof(*u)

标签: c arrays pointers dynamic


【解决方案1】:
  1. 第 8 行:temp 未初始化。试试

    temp = malloc(sizeof(char) * (strlen(p)+1));
    strcpy(temp,p);
    

    注意:strlen() 返回从缓冲区开始到(不包括)第一个空终止符 '\0' 的字符数,但 strcpy 复制包括第一个空终止符在内的所有内容。因此上面的strlen(p) + 1

  2. 第 10 行:您似乎没有使用char* y?确保 checkforrepetition(p, count) 返回堆内存并清理主范围内的 y
  3. 第 11 行:双数组 char** u 的 malloc 错误。模式是:

    //malloc the container
    char** stringArray = (char**)malloc(numberOfArrayElements * sizeof(char*));
    //malloc the elements
    for (int i = 0; i < numberOfArrayElements; i++)
    { 
      stringArray[i] = (char*)malloc((sizeOfElement + 1) * sizeof(char));
      strcpy(stringArray[i], "");
    }
    

    或等效的速记(指针算术)。破坏遵循相反的步骤(首先是元素,然后是容器)。您的代码可能是:

    char** u = malloc(sizeof(char*) * possibilities(count,strlen(p)));
    for (int i = 0; i < possibilities(count,strlen(p)); i++)
    {
        u[i] = malloc(sizeof(char) * (MAXSIZE + 1));
    }
    

【讨论】:

    猜你喜欢
    • 2017-03-18
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 2012-10-07
    • 1970-01-01
    • 2013-11-24
    相关资源
    最近更新 更多