-1

I want to assign value of an array to a pointer or need a better way to do the below operation .

I have a structure

struct ver{
    int *a;
    int *b
    int *c;
}

struct Versions{
    int ver1[3];
    int ver2[3];
    int ver3[9];
}

static const Versions versionsinfo[] {
    "001234",
    {0,18,0},
    "000000"
};

static Temp_Data;

Versions * GetVersions() {
    Versions * pt = NULL;
    memcpy(&Temp_Data,&versionsinfo[1]);
    pt = &Temp_Data;
    return pt ;
}

struct Versions *pointer;
pointer = GetVersions();    

struct ver *newVer;
newVer->a= pointer->ver1;
newVer->b= pointer->ver2;
newVer->c= pointer->ver3;

I want to assign the value of Ver1 to a member of struct ver , either a, b or c.

can anyone please let me know if this is possible in C.

Prajval M
  • 2,298
  • 11
  • 32
pranathi
  • 383
  • 4
  • 6
  • 16

2 Answers2

1

Well,

int Ver1[3];
int Ver2[9];
int Ver3[9];

They are initializing arrays of type int. So if you want to get those numbers (which are the sizes of the arrays in the above) you need to do

int Ver1 = 3;
int Ver2 = 9;
int Ver3 = 9;

The allocate some memory for the pointer

struct ver *newVer = malloc(sizeof(newVer));

and then put the values in the struct

newVer[0].a = Ver1;
newVer[0].b = Ver2;
newVer[0].c = Ver3;
PerfectContrast
  • 144
  • 2
  • 2
  • 14
1

Hope this helps

struct ver
{
  int *a;
  int *b;
  int *c;
};

int Ver1[3] = {1,2,3};
int Ver2[3] = {1,2,3};;
int Ver3[9];

struct ver *newVer;

int main()
{
   struct ver newV;/*the memory for struct var is allocated in main */

   newVer = (struct ver *)malloc(sizeof(struct ver));/*memory allocated in heap*/

   newV.a = Ver1;/*OR newVar.a = &Ver1[0];*/
   newV.b = Ver2;
   newV.c = Ver3;
   printf("newV->a[0] is %d", newV.a[0]);
  /*OR*/
  newVer->a = Ver1;
  newVer->b = Ver2;
  newVer->c = Ver3;
  printf("\nnewVar->a[1] is %d", newVer->a[1]);
  free(newVer); 

  return 0;
}
H.cohen
  • 517
  • 3
  • 9