Hello,
I am writing a program for the problem: Write a function that receives a string, and returns a pointer to the first non space character in the string.
I could do it more simply by just passing a pointer to the string and changing that but I want to get it to work the way the problem is stated. Here is the code I have written:
Code:
#include <stdio.h>
char *space_finder(char strng[]); /* Function prototype for finding the first string in a character */
int main(){
char test_string[] = "Where is the first space?"; /* test string */
char *return_ptr; /*pointer for the pointer space_finder returns */
return_ptr = space_finder(test_string); /* send test string to space_finder function and assign returned pointer to return_ptr */
/* test to see if the return_ptr equals the first char of the array(empty string) or if it is the end of string character(no spaces) */
if((return_ptr == test_string)||(*return_ptr== '\0')){
printf("\n\nNo spaces were in the sentence.\n\n");
}else{
printf("The first character after the space is \n%c\n%c\n%c\n", *(return_ptr-1),*(return_ptr),*(return_ptr+1));
}
return(0);
}
char *space_finder(char strng[]){
char *ptr; /* temporary local pointer */
int i; /* loop control variable */
int loopmax; /* loop max size */
ptr = strng; /* point ptr to first address of strng */
/* Loop control uses a -1 to account for the null character*/
loopmax = (sizeof(strng)/sizeof(char))-1;
for(i=0;i<loopmax;i++){
if(*(ptr+i)== ' '){
/* printf is for debugging and showing what the characters are that border the current pointer value(ptr+1) */
printf("\n\nInside If:\n\n%c\n%c\n%c\n\n",*(ptr+i-1),*(ptr+i),*(ptr+i+1));
/* violate loop enter conditions */
i=loopmax;
ptr_return = (ptr+i);
return ptr_return;
}else if(*(ptr+i)== '\0'){
/* return the null pointer to main */
return ptr+i;
}
}
}
When I run the code I get the output:
Code:
Inside If:
e
i
The first character after the space is
i
s
This tells me that inside the if statement the pointer is correctly pointing to the first space. When the pointer is returned to main though, it is pointing to the second character after the first space.
If anyone can offer insight into where I am going wrong I would appreciate it. I am doing this for giggles so I am mostly interested in the why as I want to get a good grasp of pointers.
Thank you for reading this!