我在使用xCode的macbook上运行此代码,它运行完美,没有任何错误。但是,当我尝试在Red Hat Linux服务器上编译并运行确切的代码时,我在第25行遇到了分段错误。我不确定为什么这对一台机器起作用,而不是另一台机器。
#include <stdio.h>
#include <string.h>
//Count the number of times the letter appears in the string
int count_letter(char str[], char * ch)
{
int i, num = 0;
for(i=0; i < strlen(str)-1; i++)
if(str[i] == *ch)
{
//printf("The character is %c", ch);
num++;
}
return num;
}
//Get the sentence and character to search for from the user
char * get_info(char * ch)
{
char *str;
//int i=0;
printf("Enter a sentence to search: ");
while((str[i++]=getchar())!='\n');
str[i]='\0';
printf("Enter a character to search for: ");
*ch=getchar();
return str;
}
//Get a sentence and character from the user and count the number
//of times the character is found in the sentence.
int main()
{
char *sentence;
char ch;
int num_letters;
sentence = get_info(&ch);
num_letters = count_letter(sentence, &ch);
printf("%c is found %d times.\n", ch, num_letters);
return 0;
}
谢谢
答案 0 :(得分:2)
char *str;
您尚未在get_info()
中为其分配任何内存。
首先为它分配内存。比如
str= (char *)malloc(MAX_LEN*sizeof(char)); //MAX_LEN=define yourself what you want