这是我不理解的问题 - 我在主函数中使用
这段代码基于Ivor Horton的书籍“Beginning C”中的示例程序(虽然这是一本旧书,但我只想从中学习基础知识)。
我的程序如下。我正在*nix上使用Geany(基本上使用GCC编译)。您可以看到
顺便说一下,该程序应该对存储在字符串指针数组中的字符串进行排序。
fgets()
它可以工作。但是我认为在一个函数中以完全相同的方式使用它时,会出现错误(段错误核心已转储 - 退出代码 139)。这段代码基于Ivor Horton的书籍“Beginning C”中的示例程序(虽然这是一本旧书,但我只想从中学习基础知识)。
我的程序如下。我正在*nix上使用Geany(基本上使用GCC编译)。您可以看到
fgets
在主函数中工作(输出是您输入的字符串)。但是在函数str_in()
中无法正常工作。它最多只能执行第二个printf()
语句来输入字符串,没有更进一步了。请注意,在书中,Horton使用gets()
。我试图在这里实现一个更安全的字符串输入函数,但没有成功。顺便说一下,该程序应该对存储在字符串指针数组中的字符串进行排序。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
#define MAX_NUM_STRINGS 50
int str_in(char **); /*Pointer to a string pointer*/
void str_sort(char *[], int n); /*Array of pointers to strings, number of strings in array*/
void str_out (char *[], int n); /*Array of pointers to strings, number of strings in array*/
int main(){
char *pS[MAX_NUM_STRINGS] = { NULL }; /*Array of pointers to strings stored in str_space*/
int numStrings = 0; /*Count of strings*/
char buffer[BUFSIZ];
printf("Enter a string\n");
fgets(buffer, BUFSIZ, stdin);
printf("%s", buffer);
printf("fgets works here\n\n");
/* get string input from user - a pointer to each string is saved in pS */
while ( str_in(&pS[numStrings]) && numStrings < MAX_NUM_STRINGS)
numStrings++;
if ( numStrings > 0 ){
str_sort(pS, numStrings);
str_out(pS, numStrings);
}
return 0;
}
int str_in(char** pString){
char buffer[BUFSIZ];
char *p;
printf ("Enter string:\n");
fgets(buffer, 60, stdin);
printf("fgets doesn't work here!!\n");
if( buffer != NULL ){
printf("here");
if ((p = strchr(buffer, '\n')) != NULL)
*p = '\0'; /*replace newline with null character*/
else
return FALSE;
if ( strlen(buffer) > 0 ){
strcpy(*pString, buffer);
return TRUE;
}
else
return FALSE; /*blank line - end of input*/
}
else
return FALSE;
}
void str_sort(char* pStrings[], int n){
/*sort strings by manipulating array of string pointers*/
char *temp;
int sorted = FALSE;
int i = 0;
while (!sorted){
sorted = TRUE;
for(i = 0; i < n - 1; i++){
temp = pStrings[i];
if ( strcmp(temp, pStrings[i+1]) > 1 ){
pStrings[i] = pStrings[i+1];
pStrings[i+1] = temp;
sorted = FALSE;
break;
}
}
}
}
void str_out(char* pStrings[], int n){
/*print strings to standard output. Free memory as each string is printed */
int i = 0;
printf("Sorted strings:\n");
for(i = 0; i < n; i++){
printf("%s", pStrings[i]);
free(pStrings[i]);
}
}
buffer
是一个数组对象,不是一个指针;它会衰变为其第一个元素的指针,该指针永远不会是 null。 - Keith Thompson