How to access a pointer inside a structure?

Posted on

Question :

I need to know how to access the first position of the vector of pointers * c_parte_real, as shown below:

typedef struct{

   struct char_vector{
      char *c_parte_real[2], *c_parte_imag[2];
   }c_vector;

   struct int_vector{
      int *i_parte_real[2], *i_parte_imag[2];
   }i_vector;

   struct complex_num{
      float real1,real2,imag1,imag2;
   }comp_num;

}expressao_complexa;

    

Answer :

I made a simplified to make it clearer, I created a variable to receive the position value

#include "stdio.h"

int main(void) {


typedef struct char_vector{
char *c_parte_real[2], *c_parte_imag[2];
}c_vector;



char  a,b;//variƔvel que recebe o valor
c_vector x;

x.c_parte_real[0]='2';
a = x.c_parte_real[0];

x.c_parte_real[1]='3';
b = x.c_parte_real[1];

printf("a=%cn",a);//imprime na tela
printf("b=%cn",b);//imprime na tela

return 0;
}

test no: link

    

Assuming you declare a variable x , of type expressao_complexa , access can be done directly:

...
expressao_complexa x;

// atribui um valor
x.c_vector.c_parte_real[0] = "1.0"; 

// imprime o valor atribuĆ­do
printf("%sn", x.c_vector.c_parte_real[0]); 
...

    

The above answers are correct, but, your code is wrong, you can not declare structures within structure declarations. What you can do is have structures as components of structure declarations.

    

Leave a Reply

Your email address will not be published. Required fields are marked *