Basic C programming help

HAL9000

Lifer
Oct 17, 2010
22,021
3
76
Can anyone explain to me how to do the following:

I have this code
Code:
typedef struct name{
some irrelevant crap}

name nam[10][15];

How do I get it to print out 15 or 10? Or whatever values are in those spots.

Basic, badly explained but I'm tired and stressed, anyone?
 
Last edited:

Cogman

Lifer
Sep 19, 2000
10,286
147
106
You have to go through each element of the struct that you want to print out and do it in whatever fashion you need.

For example (and pardon my C++ code if it sneaks in, I'll try and keep things close to C, but c++ still might slip in).

Lets say your stuct looked like this.

Code:
struct myStruct
{
   float a;
   int b;
   int d;
}

To display the data in the struct, you would do something like this
Code:
void displayStruct(myStruct* thing)
{
   printf("a: %f, b: %d, c: %d\n", thing->a, thing->b, thing->c);
}

if you had an array of structs, then you would just loop through each and print out their data. So something like this

Code:
for (int i = 0; i < numStructs; ++i)
{
   displayStruct(&structArray[i]);
}

A 2d array is the same thing but with more loops.
 

HAL9000

Lifer
Oct 17, 2010
22,021
3
76
You have to go through each element of the struct that you want to print out and do it in whatever fashion you need.

For example (and pardon my C++ code if it sneaks in, I'll try and keep things close to C, but c++ still might slip in).

Lets say your stuct looked like this.

Code:
struct myStruct
{
   float a;
   int b;
   int d;
}

To display the data in the struct, you would do something like this
Code:
void displayStruct(myStruct* thing)
{
   printf("a: %f, b: %d, c: %d\n", thing->a, thing->b, thing->c);
}

if you had an array of structs, then you would just loop through each and print out their data. So something like this

Code:
for (int i = 0; i < numStructs; ++i)
{
   displayStruct(&structArray[i]);
}

A 2d array is the same thing but with more loops.

That's very helpful thankyou. :)
 

uclabachelor

Senior member
Nov 9, 2009
448
0
71
Can anyone explain to me how to do the following:

I have this code
Code:
typedef struct name{
some irrelevant crap}

name nam[10][15];

How do I get it to print out 15 or 10? Or whatever values are in those spots.

Basic, badly explained but I'm tired and stressed, anyone?

sizeof(name) gives you the # of bytes allocated per instance of name.

sizeof(nam) gives you the total bytes allocated for the array nam.
 

slpaulson

Diamond Member
Jun 5, 2000
4,414
14
81
If your code is going to rely on the size of your array dimensions, I'd use #defines to define the dimensions.

I'm always paranoid that using sizeof(variablename) is going to include some padding bytes which might throw your logic off.