This is a problem that I do not understand - I use fgets()mainly and it works. I use it (I think) in the same way in the function, and I get the error message [Reset Segmentation Kernel - Exit Code 139).
This code is based on the sample program in Ivor Horton's Beginning C (this is an old tile, but I just want to learn its basics).
My program is as follows. I am working on * nix using Geany (mainly with GCC). You can see what fgetsworks mostly (output is the line you enter). But this does not work in function str_in(). Before the second statement, printf()he enters a string, and not further. Note that in the book Horton uses gets(). I am trying to implement a more secure string input function here, but without joy.
By the way, the program should sort the lines stored in the array of line pointers.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
#define MAX_NUM_STRINGS 50
int str_in(char **);
void str_sort(char *[], int n);
void str_out (char *[], int n);
int main(){
char *pS[MAX_NUM_STRINGS] = { NULL };
int numStrings = 0;
char buffer[BUFSIZ];
printf("Enter a string\n");
fgets(buffer, BUFSIZ, stdin);
printf("%s", buffer);
printf("fgets works here\n\n");
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';
else
return FALSE;
if ( strlen(buffer) > 0 ){
strcpy(*pString, buffer);
return TRUE;
}
else
return FALSE;
}
else
return FALSE;
}
void str_sort(char* pStrings[], int n){
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){
int i = 0;
printf("Sorted strings:\n");
for(i = 0; i < n; i++){
printf("%s", pStrings[i]);
free(pStrings[i]);
}
}
source
share