Home > Software design >  What is the difference between (int *)array, (int *)&array, and &array in a pointer assignment?
What is the difference between (int *)array, (int *)&array, and &array in a pointer assignment?

Time:11-24

I have 3 lines of code that performs exactly the same but have different syntax, the base code being:

    int a, b;
    printf("Enter the size of your array [a][b]: ");
    scanf("%d %d", &a, &b);
    int arr[a][b];

    int *pa;

    pa = (int *)&arr;
     
    for (i = 0; i < a*b; i  )
    {
        printf("[%d] [%d] = ", i/b, i%b);
        scanf("%d", (pa   i));
    }

On the line pa = (int *)&arr;, I can switch that line to (int *)array, (int *)&array, and &array without encountering any issues, only experiencing a warning at the last one. I was wondering the correct syntax is and the difference between all 3 of them.

CodePudding user response:

Two key tidbits:

  1. The address of an array is the address of its first element.
  2. When treated as a pointer, an array degrades into a pointer to its first element

So,

  1. pa = arr;
    

    is equivalent to

    pa = &(arr[0]);   // Type mismatch: RHS is int (*)[b]
    

    You use a typecast to silence the warning when doing pa = (int *)arr;.

  2. pa = &arr;
    

    is equivalent to

    pa = &(arr[0]);   // Type mismatch: RHS is int (*)[b]
    

    You use a typecast to silence the warning when doing pa = (int *)&arr;.

I'm not sure if the typecast is safe according to the spec. If you want to treat it as a 1d array of int values, probably best to declare it that way too.

CodePudding user response:

  • The correct syntax is pa = arr; and if you find yourself in need to add a cast, you are doing something wrong. Bluntly put, if you are a beginner, you shouldn't be casting pointers ever.

  • pa = (int *)array is just a superfluous cast which achieves nothing since array when used in this expression has already "decayed" into a int*.

  • pa = &arr does not "only give a warning", it's invalid C. This is a so-called constraint violation - invalid assignment of non-compatible pointer types. Please study What compiler options are recommended for beginners learning C? and What must a C compiler do when it finds an error?

  • Similarly, pa = (int *)&array is an invalid pointer conversion between non-compatible types. It will compile but has a compiler-specific outcome. It's strictly speaking incorrect code but may work for the specific compiler and system.

  • Related