This is supposed to read a surname from a string and display it instead of the whole string. More specificaly, it reads a string, identifies the adress of the last space and copies to another string what's between it and '\0'.
Code:
The problem is here:
Code:
If I write it like this, the cmd crashes. The compiler doesn't show any error or warning (besides from "conflicting types strlen blah blah")
But if I write it like this, it works fine:
Code:
It also works just fine like this:
Code:
So the problem must be in the declaration of the string s.
What could be causing this?
Code:
#include <stdio.h>
int strlen (char*s)
{
int i;
for(i=0; s[i]!='\0'; i++)
;
return i;
}
char *strrchar(char *s, char ch)
{
int i;
for(i=strlen(s); i>=0 && s[i]!=ch; i--)
;
if (i>-1)
return s+i;
else
return NULL;
}
char *name(char *s)
{
int x;
char *string, *ptr;
for( x = 0, ptr = strrchar(s, ' ')+1; *ptr!= '\0'; x++, ptr++)
string[x] = *ptr;
string[x] = '\0';
return string;
}
main()
{
char *s = "JANE DOE";
if(strrchar(s, ' ')== NULL)
{
printf("Invalid String\n\n");
return;
}
else
printf("%s\n\n", name(s));
}
The problem is here:
Code:
main()
{
char *s = "JANE DOE";
if(strrchar(s, ' ')== NULL)
{
printf("Invalid String\n\n");
return;
}
else
printf("%s\n\n", name(s));
}
If I write it like this, the cmd crashes. The compiler doesn't show any error or warning (besides from "conflicting types strlen blah blah")
But if I write it like this, it works fine:
Code:
main()
{
printf("%s\n\n", name("JANE DOE"));
}
It also works just fine like this:
Code:
main()
{
if(strrchar("JANE DOE", ' ')== NULL)
{
printf("Invalid String\n\n");
return;
}
else
printf("%s\n\n", name("JANE DOE"));
}
So the problem must be in the declaration of the string s.
What could be causing this?