Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning structs

Tags:

c

I have a struct like

struct T {
   int *baseofint
}Tstruct, *pTstruct;

int one;
pTstruct pointer;

now i want to define

one = pointer.baseofint; //got filled with an integer; 
error message: **operator is not equal to operand**

I also tried

one = *(pointer.baseofint);
error message:**operand of * is no pointer*

Maybe someone can help, thanks.

like image 617
Starfighter911 Avatar asked Feb 11 '26 09:02

Starfighter911


2 Answers

First of all, I don't think the following code is what you think it is:

struct T {
   int *baseofint
}Tstruct, *pTstruct;

int one;
pTstruct pointer;

You're declaring a structure type struct T, and creating an instance of it called Tstruct and a pointer to it called pTstruct. But those aren't types you're creating, they're variables. That makes the pTstruct pointer; invalid code, too. What you probably intended was a typedef:

typedef struct T {
  int *baseofint;
} Tstruct, *pTstruct;

...to make Tstruct equivalent to struct T, and pTstruct equivalent to struct T *.

As for accessing and dereferencing the baseofint field, it's slightly different depending on whether you're accessing it through a pointer or not... but here's how:

Tstruct ts;          // a Tstruct instance
pTstruct pts = &ts;  // a pTstruct -- being pointed at ts

/* ...some code that points ts.baseofint at
 *    an int or array of int goes here... */

/* with * operator... */
int one  = *(ts.baseofint);   // via struct, eg. a Tstruct
int oneb = *(pts->baseofint); // via pointer, eg. a pTstruct

/* with array brackets... */
int onec = ts.baseofint[0];   // via Tstruct
int oned = pts->baseofint[0]; // via pTstruct
like image 68
Dmitri Avatar answered Feb 15 '26 18:02

Dmitri


pTstruct is a pointer to a struct. That struct contains a pointer to an int. So you need to dereference them both. Try:

*((*pointer).baseofint)

Also note

p->x

is an abbreviation of

(*p).x

so

*(pointer->baseofint)

is valid as well (and less difficult to read).

like image 27
Joseph Stine Avatar answered Feb 15 '26 18:02

Joseph Stine