【发布时间】: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而不是&p。但是,这不应该是问题的原因。 -
在for循环上触发,应该确定第一个数组的元素
-
OTOH,调用
temp = malloc(sizeof(char) * (strlen(p)));没有为字符串末尾的空字节分配足够的空间;这很容易成为问题。 -
malloc(sizeof(char) * possibilities(count,strlen(p))*MAXSIZE)应该改为sizeof(char *)。或者更好sizeof(*u)