Home > OS >  overwriting array indice of struct using short name
overwriting array indice of struct using short name

Time:01-03

Here's what I'm trying to do. I'm trying to create a short variable name to reference and even change the contents of a struct at a specific index (in this case the index number is 1). It would make my code cleaner.

The problem is if I use these lines:

AB C=aridiculouslylongstructname[1];
C.a=20;
C.b=200;

I can't make aridiculouslylongstructname[1].a equal C.a when I set the value of C.a. Is there a better way to modify the value instead of having to always set the value in aridiculouslylongstructname[1].a?

Heres the complete code:

  #include <stdio.h>
  #include <stdlib.h>

  typedef struct{
int a,b;
  }AB;

  int main(){
AB aridiculouslylongstructname[2];
aridiculouslylongstructname[1].a=10; //set member a and member b to 10 and 100 respectively
aridiculouslylongstructname[1].b=100;
AB C=aridiculouslylongstructname[1];
printf("A=%d B=%d\n",aridiculouslylongstructname[1].a,aridiculouslylongstructname[1].b);
C.a=20; //trying to overwrite member a and member b to 20 and 200 respectively
C.b=200;
//and reading it with original member
printf("A=%d B=%d\n",aridiculouslylongstructname[1].a,aridiculouslylongstructname[1].b);
return 0;
  }

CodePudding user response:

You can make a pointer to the struct, and access members of it through the pointer.

#include <stdio.h>
#include <stdlib.h>

typedef struct{ int a,b;}MyStructType;

int main(){
  MyStructType aridiculouslylongstructname[2]; //create array of 2 MyStructType's
  aridiculouslylongstructname[1].a=10; //set member a and member b to 10 and 100 respectively
  aridiculouslylongstructname[1].b=100;
  MyStructType * shortname=&aridiculouslylongstructname[1]; //create a pointer to the original instead of a new copy
  printf("A=%d 
  B=%d\n",aridiculouslylongstructname[1].a,aridiculouslylongstructname[1].b);
  shortname->a=20; //because shortname points to aridiculouslylongstructname[1], this overwrites aridiculouslylongstructname[1].a
  shortname->b=200;
  printf("A=%d 
  B=%d\n",aridiculouslylongstructname[1].a,aridiculouslylongstructname[1].b);
  return 0;
}

note that to access the fields of a struct from a pointer, you use the arrow -> operator. This is equivalent to dereferencing the pointer first, then accessing normally via the dot operator . i.e. shortname->b=200 is equivalent to (*shortname).b=200

CodePudding user response:

I figured it out.

I had to declare C this way in my code

AB *C=aridiculouslylongstructname;

then I can modify the values for each member in the struct like so:

 C[n].a = 20;
 C[n].b = 200;
  • Related