Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays decaying into pointers

Tags:

c

Please help me understand the programs below.

#include<stdio.h>
int main()
{
    int a[7];
    a[0] = 1976;
    a[1] = 1984;
    printf("memory location of a: %p", a); 
    printf("value at memory location %p is %d", a, *a); 
    printf("value at memory location %p is %d", &a[1], a[1]);
    return 0;
}

&a[1] and &a+1. Are they same or different?

#include <stdio.h> 
int main() 
{
    int v[10];
    int **p; 
    int *a[5];
    v[0] = 1234;
    v[1] = 5678;
    a[0] = v; 
    a[1] = v+1;
    printf("%d\t%d\t%d\t%d\n", *a[0],*a[1],a[0][0],**a);
    printf("%d\n", sizeof(v));
    return 0;
} 

I wanted to know how *a[5] is represented in memory. Is *a a base pointer that points to a[0],a[1],a[2],a[3],a[4]?

#include<stdio.h>

int main()
{
    int v[10];
    int **p;
    int (*a)[10];
    a=&v;
    printf("%d\n",*a);
        return 0;
}

a=v; // gives error why? does v here decay into *v. Then does &v get decayed into (*)[]v? & means const pointer. Here, how is it possible to set a const pointer to a non-const pointer without a typecast?

Where does the array get stored in the memory. Does it get stored onto the data segment of the memory.

#include<stdio.h>

int main()
{
    int carray[5]={1,2,3,4,5};
    printf("%d\n",carray[0]);
    printf("%d\t%d\t%d\n",sizeof(carray),sizeof(&carray),sizeof(&carray[0]));
    return 0;
}

EDITED:

I have gone through some of the articles which stated that the only two possible situations where an array name cannot be decyed into pointer is the sizeof and &. But in the above program sizeof(&carray) gives the size as 4. and &carray decays into (*)[]carray as its an rvalue.

Then the statement that array name cannot get decayed into pointers on two conditions sizeof and & becomes false here.

like image 320
Angus Avatar asked Nov 27 '22 16:11

Angus


1 Answers

&a[1] and &a+1. Are they same or different?

Different. &a[1] is the same as (a+1). In general, x[y] is by definition equivalent to *(x+y).

I wanted to know how *a[5] is represented in memory. Does *a is a base pointer that points to a[0],a[1],a[2],a[3],a[4].

In your second example, a is an array of pointers. *a[i] is the value of the object, the address of which is stored as the ith element in your array. *a in this case is the same as a[0], which is the first element in your array (which is a pointer).

a=v //why this gives error

Because a (in your last example) is a pointer to an array. You want to assign to a, then you need to assign the address of the array v (or any other array with correct dimensions);

a = &v;

This is very good that you've commited to understanding things, but nothing will help you better than a good C book.

Hope this helps.

like image 103
Armen Tsirunyan Avatar answered Jan 16 '23 03:01

Armen Tsirunyan