Home > Software design >  Why can't I assign Array in a int pointer in implicit declaration in C?
Why can't I assign Array in a int pointer in implicit declaration in C?

Time:07-04

    int *p={1,2,3,4};
    printf("%d",(*p 1));
    return 0;

While I run it, it terminates with signal 11. And if I simply make an array and assign it to the pointer it works perfectly fine, what is the difference as {1,2,3,4} is also an array.

CodePudding user response:

The line

int *p={1,2,3,4};

will not declare an array, because you are not declaring p as an array. You are declaring it as a single pointer. Also, you are assigning the value 1 to this pointer, which is illegal in ISO C. You cannot assign an integer to a pointer in ISO C. If you attempt to compile this in strict ISO C18 compliance mode, it will fail to compile. It will also fail due to providing too many initializers.

If you want p to be an array of 4 int elements, then you can write it like this instead:

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

If you want p to be a pointer that points to the first element, then you can write it like this instead:

int arr[] = { 1, 2, 3, 4 };
int *p = arr;

Due to array to pointer decay, the line

int *p = arr;

is equivalent to:

int *p = &arr[0];

Also, the line

printf("%d",(*p 1));

is probably not doing what you think it does. Due to the rules on operator precedence, this line is equivalent to the following:

printf("%d",(*p) 1);

However, you probably want the following instead:

printf("%d",*(p 1));

which is equivalent to:

printf("%d",p[1]);

Since you have defined your array contents in such a way that both are equivalent (both have the value 2), you probably won't notice this bug. However, as soon as you change the array contents so that p[1] does not have the value p[0] 1, this bug will become visible.

Here is an example of what your entire code should probably look like:

#include <stdio.h>

int main( void )
{
    int arr[] = { 1, 2, 3, 4 };
    int *p = arr;
    printf( "%d\n", p[1] );
    return 0;
}

This program has the output 2.

Note that in this program, the line

int *p = arr;

is not necessary, because you can simply write arr[1] instead of p[1]. You don't need the variable p at all.

CodePudding user response:

There is no array in your code.

What you posted is equivalent to

int *p = 1;

You could create an anonymous array as follows:

int *p = ( int[] ){ 1, 2, 3, 4 };

This is the same thing as

int anon[] = { 1, 2, 3, 4 };
int *p = anon;
  • Related