This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

struct and pointer

hi,
i need a solution on how to read a struct which includes serveral types of vars with a pointer of type char.

example:

 struct test
 {
  char a;
  int  b;
  int  c;
  char d;
 };

struct test s_test;
char *p_test;


p_test = &s_test.a;
...

the compiler display error like pointer not the type of struct.


  • You need a pointer that points to the proper type, in this case, a "struct test *". In your example code, just declare the pointer correctly.

    struct test
     {
      char a;
      int  b;
      int  c;
      char d;
     };
    
    struct test s_test;
    struct test *p_test;
    

    Then you can reference fields of the structure with the "arrow" operator:

    p_test->a;

    If you want pointers to fields inside the structure, then you need pointers to those types (in this case "char" and "int").

    char* p_char = &s_test.a;

    The code in your example looks like it should work to me.

    If you're passed in what you know is really a pointer to a s_test, but for some reason it's described as a pointer to char, you'll need to change the type of the pointer ("cast" it). Usually, this sort of thing happens when a pointer gets passed through a routine that handles "generic" objects and treats all pointers as void* or char*.

    struct test *p_test = (struct test *)p_char;
    mychar = p_test->a;

    You can do the casts in line without declaring another variable at some cost in readability:

    mychar = ((struct test*)pchar)->a;