How to make a pointer to an array of structures?

Go To Last Post
4 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hello everybody :D

I just can't seem to get something right.

I want to use a pointer to an array of structures

struct foo{int A, int B}foo_array[10]; 

struct foo *ptr1; // declare pointer to struct

prt1 = foo_array; // assign address of foo_arrary[0]

for(i=0;i<10;i++, ptr1++)
{
 ptr1->A = 1;
}


I would expect that all the values of A are set to 1 as a result, but this is not the case.
This is not the exact code, but very simular to what I am actually using.
Anyone got suggestions?

"Digital is a special case of analog" - George Philbrick

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi xenobinol,

what compiler are you using? the code snipped you posted does not compile on GCC for several reasons:

1) The structure declaration is wrong: you can't use colons in the variable definition. I don't know what your struct is, probably an aggregate of 3 int variables: "A", "int" and "B". A valid definition would be

struct foo{ int A; int B; } ...

2) prt1 does not exist
3) i does not exist

Please post code we can compile and run on the target. I suspect that during the process of shaping the code into a presentable form you'll find the error yourself.

If not, please post a syntax-correct file and we will be happy to test it.

HTH
Thomas

pycrc -- a free CRC calculator and C source code generator

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

PS: I tend also to simplify struct declarations by using "typedef", e.g.

typedef struct { int A; int B; } foo_t;
foo_t foo_array[10];
foo_t *ptr1;
...

Thomas

pycrc -- a free CRC calculator and C source code generator

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

tpircher wrote:
PS: I tend also to simplify struct declarations by using "typedef", e.g.

typedef struct { int A; int B; } foo_t;
foo_t foo_array[10];
foo_t *ptr1;
...

Thomas

Ok, thanks Thomas for your interest, I apologize for the typos

I made use of your tip about the typedef statement, good idea :idea:

I had some problems with my hardware instead with the software :roll:
Got it to work now after a few games of poker cleared my head :)

"Digital is a special case of analog" - George Philbrick