Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistent lvalue required error when incrementing array variable

Tags:

c++

c

pointers

I am getting "lvalue required as increment operand" while doing *++a. Where I am going wrong? I thought it will be equivalent to *(a+1). This behaviour is weird as *++argv is working fine. Please help.

#include <stdio.h>

int main(int argc, char *argv[])
{    
  printf("Arg is:  = %s\n", *++argv);

  int a1[] = {1,2,3,4,5,6};    
  int a2[] = {7,8,9,10,11,12};
  int *a[2];

  a[0] = a1;
  a[1] = a2;

  printf("ptr  = %d\n", *++a);

  return 0;
}
like image 643
Bhaskar Avatar asked Dec 16 '22 08:12

Bhaskar


1 Answers

a is a constant(array name) you can't change its value by doing ++a, that is equal to a = a + 1.
You might wanted to do *a = *a + 1 (increment 0 indexed value), for this try *a++ instead. notice I have changed ++ from prefix to postfix.

Note: char* argv[] is defined as function parameter and argv is pointer variable of char** type ( char*[]).
Whereas in your code int* a[] is not a function parameter. Here a is an array of int type (int*)(array names are constant). Remember declaration in function parameter and normal declarations are different.

Further, by using ++ with argv and a you just found one difference, one more interesting difference you can observe if you use sizeof operator to print there size. for example check this working code Codepade

int main(int argc, char* argv[]){
    int* a[2];
    printf(" a: %u, argv: %u", sizeof(a), sizeof(argv));
    return 1;
}

Output is:

a: 8, argv: 4

Address size in system is four bytes. output 8 is size of array a consists of two elements of type int addresses (because a is array), whereas 4 is size of argv (because argv is pointer).

like image 83
Grijesh Chauhan Avatar answered May 15 '23 02:05

Grijesh Chauhan