0

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;
}
Peter Neyens
  • 9,770
  • 27
  • 33
  • Modifying a string literal is Undefined Behavior (http://stackoverflow.com/questions/1614723/why-is-this-string-reversal-c-code-causing-a-segmentation-fault). – cadaniluk Jul 17 '15 at 11:39

3 Answers3

3

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.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
  • now the error is: main.c:14: error: incompatible types for redefinition of 'strtrink' – Simone Greco Jul 17 '15 at 11:51
  • @SimoneGreco Updated answer. In simple words, move `char *strtrunk(char *string, int offset){...}` before `main` or add `char* strtrunk(char*, int);` just after the `#include`s – Spikatrix Jul 17 '15 at 12:23
0

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);
Sumit Trehan
  • 3,985
  • 3
  • 27
  • 42
0

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[]"?

Community
  • 1
  • 1
Sorcrer
  • 1,634
  • 1
  • 14
  • 27