C 遇到seg故障但不知道如何修复
下面的代码有一个seg错误,但我真的不知道如何调试它,可能是因为我的知识缺乏C语法,我读过TCPL,但仍然一无所获C 遇到seg故障但不知道如何修复,c,arrays,pointers,debugging,segmentation-fault,C,Arrays,Pointers,Debugging,Segmentation Fault,下面的代码有一个seg错误,但我真的不知道如何调试它,可能是因为我的知识缺乏C语法,我读过TCPL,但仍然一无所获 #include <stdio.h> #include <ctype.h> int main() { char *str[4]; char c[2]; for (int i = 0; i < 4; i++) scanf("%s", str[i]); int find = 0; while (fin
#include <stdio.h>
#include <ctype.h>
int main() {
char *str[4];
char c[2];
for (int i = 0; i < 4; i++)
scanf("%s", str[i]);
int find = 0;
while (find <= 2 && *str[0] != '\0' && *str[1] != '\0') {
if (isalpha(*str[0]) && *str[0] == *str[1]
&& *str[0] - 'A' >= 0 && *str[0] - 'A' <= 25) {
find++;
if (find == 1)
c[0] = *str[0];
else if (find == 2)
c[1] = *str[0];
}
str[0]++;
str[1]++;
}
/* ... */
}
#包括
#包括
int main(){
char*str[4];
charc[2];
对于(int i=0;i<4;i++)
scanf(“%s”,str[i]);
int find=0;
而(find=0&&*str[0]-“A”则会忘记为字符串分配的内存
您的代码具有动态分配内存
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h> //needed for malloc and free
int main() {
char *str[4];
//allocate memory
for (int i = 0; i < 4; ++i) {
//allocate 128B per string
str[i] =(char*) malloc(128 * sizeof(char));
//here you should check if malloc was succesfull
//if malloc failed you schould free previously allocated memory
}
char c[2];
for (int i = 0; i < 4; i++)
scanf("%s", str[i]);
int find = 0;
while (find <= 2 && *str[0] != '\0' && *str[1] != '\0') {
if (isalpha(*str[0]) && *str[0] == *str[1]
&& *str[0] - 'A' >= 0 && *str[0] - 'A' <= 25) {
find++;
if (find == 1)
c[0] = *str[0];
else if (find == 2)
c[1] = *str[0];
}
str[0]++;
str[1]++;
}
//delete memory
for (int i =0; i < 4; ++i) {
free(str[i]);
}
/* ... */
}
#包括
#包括
#包括//malloc和free所需
int main(){
char*str[4];
//分配内存
对于(int i=0;i<4;++i){
//为每个字符串分配128B
str[i]=(char*)malloc(128*sizeof(char));
//在这里,您应该检查malloc是否成功
//如果malloc失败,您将释放以前分配的内存
}
charc[2];
对于(int i=0;i<4;i++)
scanf(“%s”,str[i]);
int find=0;
而(find=0&&*str[0]-“A”在这里
一旦使用动态内存完成了任务,不要忘记为每个字符指针调用free(str[i])
来释放动态内存,以避免内存泄漏
char *str[4]; /* what str[0] contains ? some junk data, need to assign valid address */
for (int i = 0; i < 4; i++)
scanf("%s", str[i]); /* No memory for str[i] here */
char *str[4];
for (int i = 0; i < 4; i++) {
str[i] = malloc(MAX); /* define MAX value as per requirement */
scanf("%s", str[i]); /* Now str[i] has valid memory */
}