1

I tried a code to see what is the difference between &i and i if i is an array. My assumption was that i represents the starting address of the array, and I had no idea what will happen if I print &i as well. The result was surprising (to me), as both i and &i was the starting address of the array.

#include<stdio.h>

int main()
{
    char str[25] = "IndiaBIX";

    int i[] = {1,2,3,4};

    printf("%i\n", &i);
    printf("%i\n", i);
    return 0;
}

The result will be:

2686692  
2686692

This is the same address.

But if I use a pointer to int:

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

int main()
{
    int *j = (int *) malloc(sizeof(int));
    *j = 12;

    printf("%i %i %i\n", *j,j,&j);
    return 0;
}

The result will be:

12
5582744
2686748

Here I assume the first is the value of the memory area pointed to by j,the second is the address of the memory area pointed to by j, the third is the memory address of the pointer itself. If I print i and &i, why does &i not mean the memory address of the pointer i?

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
Fekete Ferenc
  • 119
  • 2
  • 11

2 Answers2

4
int i[] = {1,2,3,4};

The difference is their type, i has a type of integer array, &i has a type of a pointer of an integer array.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
2

Yeah, both i and &i leads to print the same answer but they are not exactly same,

-> i represents the address of the first element in an array named i.
-> &i represents the address of the whole array(though values of both are same, their types are different)

For more info, please refer this [link]http://publications.gbdirect.co.uk/c_book/chapter5/arrays_and_address_of.html

                    int ar[10];
                    ip = ar;                /* address of first element */
                    ip = &ar[0];            /* address of first element */
                    ar10i = &ar;            /* address of whole array */
Raju
  • 1,149
  • 1
  • 6
  • 19