I am trying to teach myself C language. My transition from C has been rough so far. I am doing a problem from the Book "Intro to C language" and there is a problem that should read a line from the user and then ask the user for an int. My job was to find that particular word corresponding to the int.
Example
Hello World, How are you all doing. // This is the line being read
2 // the word to be printed to the console
Expected Output
World
Below is a snippet of my code that i think is giving me the bus error.
void corrspndToInt (char *theLine, int word, char *result ) {
int start;
int end;
int spaces = 1;
result = "";
//int i;
//search for the nth non-blank character
for(start = 0; start < strlen(theLine) && (spaces < word); start++ ) {
if( isspace ( theLine[ start ] ) ) {
spaces++;
} // end if
} // end for loop
//only need to continue if we haven't gone past the end of the string
if( start < strlen(theLine) ) {
//the next blank character is the end
for ( end = start; end < strlen(theLine) && ( !isspace ( theLine[ end ] ) ) ; end++ ) {
;
} // end for loop
//we now have the word
result = strncpy ( result, theLine+start, end - start);
} // end if
}
This is how i am printing the result in main
function.
printf("%s\n", result );
Now that i have been teaching C language to myself and through SO i learned that returning char arrays should not be done. There were two methods dynamic allocation using function malloc
and there was another method which is the one i implemented in my code. I have checked my other method and there seems to be nothing wrong with that. The problem here is with this method as it is not getting the correct word.
I have been trying to debug my program but apparently Mac doesn't accept the gdb
command. I have installed the command line tools and everything else but it still says
Command not found
Can anyone please guide me in the right direction here? I have been overthinking this problem from the last 1 hour now.