0

The code gives me the error: lvalue required as increment operand

But if I increment str by 1 it must point to the next character in the string.

#include <stdio.h>
#include <stdlib.h>


int main()
{
    char str[50];
    scanf("%s", str);
    while(*str != 0)
    {
        printf("%c", *str);
        str++;
    }
    return 0;
}
Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
Rahul Ranjan
  • 135
  • 1
  • 8

3 Answers3

3

str is not a pointer but an array. In many cases, the array decays to a pointer to its first element, but that doesn't make it a pointer itself.

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
2

str is a 50 element char array, not a pointer. An array decays (gets converted into) to a pointer to the first element in most circumstances, but you can't modify the decayed pointer unless you do so with a copy of that pointer.

#include <stdio.h>
#include <stdlib.h>


int main()
{
    char str[50];
    char* ptr = str;
    scanf("%s", str);
    while(*ptr != 0)
    {
        printf("%c", *ptr);
        ptr++;
    }
    return 0;
}

As Ulrich Eckhardt pointed out, a better way to implement this is to use a for loop:

#include <stdio.h>
#include <stdlib.h>


int main()
{
    char str[50];
    scanf("%s", str);
    for(char* ptr = str; *ptr != 0; ++ptr)
    {
        printf("%c", *ptr);
    }
    return 0;
}

It's more clear this way, and the scope of ptr is limited to the loop which is good because we don't need it later.

eesiraed
  • 4,626
  • 4
  • 16
  • 34
-1

You can simply use it as an array

int i;
for (i=0; i<sizeof(str); i++)
{
        printf("%c", str[i]);
}
  • First of all, `sizeof()` is the syntax for a type (e.g. `sizeof(int)`) there are no parens when the parameter is an expression: `sizeof str` in your case is the appropriate syntax, although what you wrote compiles and runs as expected. I'd also like to add that this only works when `str` is a char array in the current scope. If it is passed to a function, it will decay to a pointer and `sizeof str` will be equivalent to `sizeof(char*)`... – joH1 Jul 21 '18 at 10:17