下面的代码有一个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 (find <= 2 && *str[0] != ' ' && *str[1] != ' ') {
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]++;
}
/* ... */
}
这里
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 */
str
是字符指针数组,它们是未初始化的,即不指向任何有效地址。解决此问题的一种方法是为每个字符指针分配内存,然后您可以将一些数据放入str[i]
。例如
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 */
}
一旦使用动态内存完成工作,不要忘记通过为每个字符指针调用free(str[i])
来释放动态内存,以避免内存泄漏。
您忘记为字符串分配了内存。
具有动态分配内存的代码。
#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] != ' ' && *str[1] != ' ') {
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]);
}
/* ... */
}