![](/img/trans.png)
[英]Dynamic Memory Allocation in C ( return value 3221225477 & Segmentation fault: 11 )
[英]dynamical memory allocation and return value 3221225477
我正在做作業,問題如下:
例如,如果我輸入“apple,egg”,我會得到“elppa,gge”
到目前為止,我已經完成了大部分程序,當我輸入少於四個單詞時,程序運行良好,但是輸入超過四個單詞,例如“ybur,etaga,etiluzal,iluzal sipal,etihcalam”,程序不起作用並且它顯示返回值 3221225477。我剛剛學會了如何使用動態 memory 分配,所以我認為這可能是我沒有正確使用它的結果,如果這是真的,請糾正我。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int c=1,i,s;
char a[1000];
fgets(a,1000,stdin);
for(i=0;i<strlen(a);i++){
if(a[i]=='\n'){
a[i]='\0';
}
}
for(i=0;i<strlen(a);i++){
if(a[i]==','){
c++;
}
}
char **b;
b=(char**)malloc(sizeof(char)*c);
for(i=0;i<c;i++){
b[i]=(char*)malloc(sizeof(char)*100);
}
strcpy(b[0],strtok(a,","));
for(i=1;i<c;i++){
strcpy(b[i],strtok(NULL,","));
}
char **d;
d=(char**)malloc(sizeof(char*)*c);
for(i=0;i<c;i++){
d[i]=(char*)malloc(sizeof(char)*strlen(b[i]));
for(s=0;s<strlen(b[i]);s++){
d[i][s]=b[i][strlen(b[i])-s-1];
}
}
printf("%s",d[0]);
for(i=1;i<c;i++){
printf(",%s",d[i]);
}
for(i=0;i<c;i++){
free(b[i]);
free(d[i]);
}
free(b);
free(d);
return 0;
}
我希望無論我輸入什么單詞,該程序都能正常工作。
b=(char**)malloc(sizeof(char)*c);
應該
b = malloc(sizeof(char *) * c);
^--------------(sizeof pointer)
到目前為止,您只將sizeof char * c
分配給char **
因為它應該是sizeof pointer * c
。
此外,您不需要投射 malloc 返回。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.