user4421858
user4421858

Reputation:

How do I set a variable as value in a pointer array

I am working with C and I was wondering if there is a way to do this.

int main ()
{

  int *p = {5,6};


int a = *(p + 1);


 printf("%d", a);

 return 0;
 }

Upvotes: 0

Views: 39

Answers (2)

BLUEPIXY
BLUEPIXY

Reputation: 40145

#include <stdio.h>

int main(void){
    int *p = (int[]){5,6};
    int a = *(p + 1);

    printf("%d", a);

    return 0;
}

Upvotes: 3

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

Yes there is,

#include <stdio.h>

int main ()
{

    int  x[] = {5,6};
    int *p   = x;
    int  a   = *(p + 1);

    printf("%d", a);

    return 0;
}

the {5, 6} is for array initialization, you can't initialize a pointer as if it was an array, but you can have a pointer to an array, and you can initalize an initialized array with {5, 6}, so define the array, define a pointer that points to the array, and then a = *(p + 1); will work.

Upvotes: 0

Related Questions