#include <stdio.h>
void printarray(const int arr[][3]);
int main()
{
    int arr[][3] = {{1,2,3},{4,5,6}};
    
    printarray(arr);
    
    getchar();
    return 0;
}

void printarray(const int arr[][3])
{
     int i,j;
     
     for(i=0;i<2;i++)
     {
        for(j=0;j<3;j++)
        printf("%d\t", arr[i][j]);
        
        printf("\n");
     }
        
}

This above code tends to give me a warning.

9 D:\cprogramming\arr1.c [Warning] passing argument 1 of 'printarray' from incompatible pointer type

but if i specify the arr in the main as const everything goes well.

But the same code with just 1D array it dons't tend to give me any warning, i dont understand why?

#include <stdio.h>
void printarray(const int arr[]);
int main()
{
    int arr[] = {1,2,3,4,5,6};
    
    printarray(arr);
    
    getchar();
    return 0;
}

void printarray(const int arr[])
{
     int i;
     
     for(i=0;i<6;i++)
        printf("%d\t", arr[i]);
}

Can anyone please explain why?

ssharish

Recommended Answers

All 3 Replies

This is a tricky one. The two arrays are incompatible because of the const just like you noticed. The first dimension of an array turns into a pointer so int arr[][3] becomes int (*)[3] . But a pointer to an array of int isn't convertible to a pointer to an array of const int and your compiler complains on the first program. A pointer to int is convertible to a pointer to const int so the compiler doesn't complain on the second program.

I know that this is the rule, but I can't decipher the standard legalese enough to tell you exactly why it doesn't work. :( Maybe someone smarter than me can translate it for you.

Hey thanks for the reply, ya i know this rule before. But why is it like that, there should be some reason, for coming up with this rule.

but anyway thanks for your rely.

ssharish

I know it says so in section 6.3.2.1 but I can't put all of the pieces together enough to answer your question. Sorry. :(

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.