分段错误malloc指针函数
大家好,这是我的代码:分段错误malloc指针函数,c,arrays,pointers,segmentation-fault,coredump,C,Arrays,Pointers,Segmentation Fault,Coredump,大家好,这是我的代码: #include <stdio.h> #include <stdlib.h> int power(int a, int b) { int exponent = b, result = 1; while (exponent != 0) { result = result * a; exponent--; } //printf("%d",result); return resul
#include <stdio.h>
#include <stdlib.h>
int power(int a, int b) {
int exponent = b, result = 1;
while (exponent != 0) {
result = result * a;
exponent--;
}
//printf("%d",result);
return result;
}
int fill_it(char ** p, int N, int fliptimes, int column2) {
if (N < 0) return 0;
int counter = 0, l;
char a = 'H';
for (l = 0; l < power(2, fliptimes); l++) {
p[l][column2] = a;
counter++;
if (counter == (power(2, N) / 2)) {
counter = 0;
if (a == 'H') a = 'T';
if (a == 'T') a = 'H';
}
}
fill_it(p, N--, fliptimes, column2++);
}
int main() {
int i, fores, j, l, m;
char ** p;
printf("how many times did you toss the coin?:");
scanf("%d", & fores);
p = (char ** ) malloc((power(2, fores)) * sizeof(char * ));
for (i = 0; i < fores; i++)
p[i] = (char * ) malloc(fores * sizeof(char));
fill_it(p, fores, fores, 0);
for (l = 0; l < power(2, fores); l++) {
for (m = 0; m < fores; m++) {
printf("%c", p[l][m]);
}
}
printf(",");
}
#包括
#包括
整数功率(整数a、整数b){
int指数=b,结果=1;
while(指数!=0){
结果=结果*a;
指数--;
}
//printf(“%d”,结果);
返回结果;
}
整数填充(字符**p,整数N,整数翻转时间,整数列2){
如果(N<0)返回0;
int计数器=0,l;
字符a='H';
对于(l=0;l
但当我运行程序时,它返回一个“segmantation fault(core dumped)”错误
我知道这意味着我试图访问内存,我没有访问权限,但我不知道程序的哪个部分有缺陷问题是,您没有分配足够的内存。这条线很好
p = (char ** ) malloc((power(2, fores)) * sizeof(char * ));
但是这个循环只是为二维数组的一部分分配内存
for (i = 0; i < fores; i++)
p[i] = (char * ) malloc(fores * sizeof(char));
(i=0;i
p[i]=(char*)malloc(fores*sizeof(char));
内存分配应该更像这样
foresSquared = power(2, fores);
p = malloc(foresSquared*sizeof(char *));
for (i = 0; i < foresSquared; i++)
p[i] = malloc(fores);
foresquared=幂(2,fores);
p=malloc(平方*大小)(字符*);
对于(i=0;i<1平方;i++)
p[i]=malloc(fores);
由于power
的结果将是一致的,因此将值存储在变量中并使用它而不是重新计算它是有意义的。这也会让代码更清晰
您也不需要强制转换
malloc
的返回值,因为C会为您处理它。而sizeof(char)
是不需要的,因为它保证始终为1。(与seggie无关,但是if(a=='H')a='t';if(a=='t')a='H';
在这两种情况下都将使a=='H'
成为1。您需要否则
在这里)。在调试器(即gdb)中运行您的代码它会告诉你在你的代码中哪里崩溃了当你必须找到内存错误时,你应该试试它(你递归地调用'fill_it',但是这里有一个尾部递归,你可以把它变成一个循环。在我看来,有了两个嵌套的循环,函数会更清晰。)@MOehm递归中的column2++
也有类似的问题call@Jean-MarcZimmer看不到我正在做的代码的固定版本在哪里?哦,哎呀,我的错,我误读了。它在第一个代码部分。我真的很难理解书面材料…@ChrisTurner非常感谢你,你让我开心了!:-)@dimitraaaa如果我的答案是正确的,那么传统做法是在上面打勾