我想从用户处取一个字符串打印出来,然后访问它的第一个字符,但是下面的代码我得到了
分段错误(Core dumped)
代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define GROW_BY 10
int main(){
char *str_p, *next_p, *tmp_p;
int ch, need, chars_read = 0;
if(GROW_BY < 2){
fprintf(stderr, "Growth constant is too small\n");
exit(EXIT_FAILURE);
}
str_p = (char *)malloc(GROW_BY);
next_p = str_p;
while((ch = getchar()) != EOF){
if(ch == '\n'){
printf("%s\n", str_p);
//Here is the error I also tried *(str_p + 0), (*str_p)[0]
printf("%s\n", str_p[0]);
free(str_p);
str_p = (char *)malloc(GROW_BY);
next_p = str_p;
chars_read = 0;
continue;
}
if(chars_read == GROW_BY - 1){
*next_p = 0;
need = next_p - str_p + 1;
tmp_p = (char *)malloc(need + GROW_BY);
if(tmp_p == NULL){
fprintf(stderr, "No initial store\n");
exit(EXIT_FAILURE);
}
strcpy(tmp_p, str_p);
free(str_p);
str_p = tmp_p;
next_p = str_p + need - 1;
chars_read = 0;
}
*next_p++ = ch;
chars_read++;
}
exit(EXIT_SUCCESS);
}
答案 0 :(得分:1)
str_p[0]
是一个不是字符串的字符
所以你应该使用 %c
printf("%c\n", str_p[0]);
这是因为变量参数没有类型安全性,在 printf()
中,如果格式说明符错误,代码将从内存中读取无效结果,可能会崩溃。
帮助您进行调试的一个有用提示是启用编译器警告,例如在GCC中:
gcc -Wall main.c -o main
这将显示您的程序的以下警告。
warning: format specifies type 'char *' but the argument has type 'char' [-Wformat]
printf("%s\n", str_p[0]);
~~ ^~~~~~~~
%c
1 warning generated.
强烈建议使用-Wall
标志来解决程序中的这些问题。