2

this is the code which is working fine...

int main()
{
    char c[]={'\t','\n','\0'};
    int i;
    char *p,*str;
    str=c;
    p=&c[1];
    printf("%d\n%d\n",*p,*str);
    system("pause");
    return 0;
}

My problem is why is it str=c; and not str=&c;(which gives errors) and its p=&c[1]; and not p=c[1]?

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
S. Gupta
  • 63
  • 8

2 Answers2

4

When you make an assignment, both sides of the assignment need to be type compatible.

In certain scenarios name of an array decays as an pointer to its first element. So c returns pointer to a char, i.e char * while &c gives address of an array, which is clearly not of the type char *(type of str is char*), the type mismatch gives you a diagnostic in the form of compilation error.

&c[1] gives you a char * while c[1] gives the value at that index, i.e: char. In this case type of p is again char * and hence the observed result.


Good Read:
How do I use arrays in C++?

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • 1
    It is not just the name of an array that is converted to a pointer to its first element. **Any** array expression is converted to a pointer to its first element (except when it is the operand of `sizeof`, `&`, or `_Alignof` or is a string literal initializing an array). So, if `x` is declared as `int x[3][4][5]`, then `*(x[2]+1)` is converted to a pointer to `int`, because it is a pointer to an array of five `int`. (The result of the conversion is the same as `&x[2][1][0]`.) – Eric Postpischil Jun 29 '13 at 14:25
3

When used in an expressions, references to objects of type array-of-T (i.e. array names) decay into pointers to their first element. [1] The resulting type of such pointers is pointer-to-T.

Also when you access to an array element by index, it gets dereferenced. That's why you use & to get its address.

To wrap it up, in the expressions you posted

  • c equates to &c[0]
  • c[1] is the value in second position in the array. &c[1] is its memory address, i.e. a pointer to it.

[1] There are four notable exceptions to this fact: when the array is the operand of a sizeof, & or - since C11 - _Alignof operator, or when it is a string literal initializer for a character array. Reference: http://c-faq.com/aryptr/aryptrequiv.html.

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235