Reputation: 13
I would like to truncate a string with a function.
I am getting the error: main.c:7: error: lvalue expected
What am I doing wrong?
char *stringtest;
int main()
{
&stringtest=strtrunk("hello world!", 3);
printf("%s", &stringtest);
return 0;
}
char *strtrunk(char *string, int offset)
{
int stringlen = strlen(string);
string[stringlen - offset] = 0;
return string;
}
Upvotes: 0
Views: 251
Reputation: 20244
Your function strtrunk
returns a char*
and stringtest
is already of type char*
. So use
stringtest=strtrunk("hello world!", 3);
instead of
&stringtest=strtrunk("hello world!", 3);
%s
expects a char*
as its argument and since stringtest
is already a char*
, use
printf("%s", stringtest);
instead of
printf("%s", &stringtest);
The error "lvalue expected" occurs because &stringtest
isn't a valid lvalue.
Oh, and as mentioned in other answers, modifying a string literal invokes Undefined Behavior.
And you need to add a function prototype just after including the headers:
char* strtrunk(char*, int);
or otherwise simply move the definition of strtrunk
before the definition of main
.
Upvotes: 3
Reputation: 1644
You can use the below code
char *strtrunk(char *string, int offset);
char *stringtest;
char Char_array[]="hello world!";
int main()
{
stringtest=strtrunk(Char_array, 3);
printf("%s", stringtest);
getch();
return 0;
}
char *strtrunk(char *string, int offset)
{
int stringlen = strlen(string);
string[stringlen - offset] = 0x00;
return string;
}
Please read this link which explains your problem in detail Why do I get a segmentation fault when writing to a string initialized with "char *s" but not "char s[]"?
Upvotes: 0
Reputation: 4035
Make the changes as suggested by CoolGuy. However that won't be sufficient.
You cannot modify a string literal. Even if your program would compile, it would crash since it is illegal to modify the string literal. Use something i have shown below:
char p[20] = "hello world!"
strtrunk (p, 3);
Upvotes: 0