New to C, here is a simple Struct I have created.
typedef struct car {
float x, y;
unsigned char width, height;
} Cars;
My attempt to assign the x and y property of car:
Cars sedan;
sedan.x = 20;
sedan.y = 10;
Error
error: expected '=', ',', ';', 'asm' or 'attribute' before '.' token
Any ideas? Please help!
I'm guessing that you have the lines
Cars sedan;
sedan.x = 20;
sedan.y = 10;
outside a function. You cannot use
sedan.x = 20;
sedan.y = 10;
outside a function. Move those lines inside a function.
Another choice is to initialize the members of the struct using (Thanks #JonathanLeffler)
Car sedan = { .x = 20, .y = 10 };
Maybe you could try defining one member of struct in one line.
typedef struct car {
float x;
float y;
unsigned char width;
unsigned char height;
} Cars;
#include <stdio.h>
#include <string.h>
typedef struct car {
float x, y;
unsigned char width, height;
} Cars;
int main( ) {
Cars sedan;
sedan.x = 20;
sedan.y = 10;
printf( "value one : %f\n", sedan.x);
printf( "value two : %f\n", sedan.y);
}
Output :
value one : 20.000000
value two : 10.000000
You can also code structure as follow, :)
struct car {
float x, y;
unsigned char width, height;
};
int main( ) {
struct car sedan; /* Declare sedan of type car */
sedan.x = 20;
sedan.y = 10;
printf( "value one : %f\n", sedan.x);
printf( "value two : %f\n", sedan.y);
}
Related
Is there any syntax similar to doing something like this
typedef struct foo
{
int X;
int Y;
int Z;
} foo;
int main()
{
// Initialize everything
foo Variable = (foo){
.X = 10;
.Y = 15;
.Z = 20;
};
// Assign the X and Y variables, but keep Z the same
Variable = (foo){
.X = 15;
.Y = 20;
// .Z stays the same
};
}
Would be nice to have this type of QOL syntax instead of having to type
int main()
{
foo Variable = {bla bla};
// Keep having to type Variable. to access struct members
Variable.X = 10;
Variable.Y = 15;
}
This gets really annoying with structs in structs i.e.
Struct1->Struct2.Struct3.Element.X = 10;
Struct1->Struct2.Struct3.Element.Y = 15;
No, C does not support this style of initialization or assignment.
If you want to access only a part of a structure, you need to express this explicitely.
EDIT:
You can get away with:
Variable = (foo){
.X = 15;
.Y = 20;
.Z = Variable.Z;
};
At least an optimizing compiler will just generate the operations for the changing elements. But it is more source than single assignments.
You can use the preprocessor to save your fingers (or copy/paste)...
struct {
int f1;
int f2;
struct {
int b1;
int b2;
int b3;
} bar;
} foo = {
1, 2, { 42, 43, 44 },
};
printf( "%d %d %d\n", foo.bar.b1, foo.bar.b2, foo.bar.b3 );
#define S foo.bar
S.b1 = 7;
S.b2 = 8;
printf( "%d %d %d\n", S.b1, S.b2, S.b3 );
#undef S
it showing error in union item i1;
it says storage size of i1 isn't known
how to recover from this error
#include<stdio.h>
#include<string.h>
int main()
{
union item i1;
i1.x = 5;
printf("\n%d",i1.x);
i1.y = 3.5;
printf("\n%f",i1.y);
strcpy(i1.z,"C Programming");
printf("\n%s",i1.z);
return 0;
}
union item
{
int x;
float y;
char z[20];
};
please solve this problem
You should move the definition of item before declaring it in main(), otherwise the compiler will view it as an incomplete (undefined) type. This should work:
#include<stdio.h>
#include<string.h>
union item
{
int x;
float y;
char z[20];
};
int main()
{
union item i1;
i1.x = 5;
printf("\n%d",i1.x);
i1.y = 3.5;
printf("\n%f",i1.y);
strcpy(i1.z,"C Programming");
printf("\n%s",i1.z);
return 0;
}
I'm fairly new to C/C++, but I'm trying to debug some code. It uses a vector that someone had called CART8 and is structured as such:
typedef struct crt8 {
double x;
double y;
double z; } CART8;
Now my question is this. How do I create and populate an instance of an vector of type CART8 called vector1? I've read through a lot of material, and even found a site that indicate how you would create the vector...as indicated above, but no information on HOW to actually use it.
typedef is used extensively in C to refer to struct variables without specifying the struct prefix, for example if I had:
struct vector {
double x;
double y;
double z;
};
than to initialize it I'd have to do:
struct vector vector1;
vector1.x = 1.11;
vector1.y = 1.22;
vector1.z = 1.33;
But if I used a typedef in the declaration:
typedef struct vector {
double x;
double y;
double z;
} vector_type;
than I could simplify this initialization like so (note the struct prefix is not needed now):
vector_type vector1;
vector1.x = 1.11;
vector1.y = 1.22;
vector1.z = 1.33;
Of course, I could still use the full struct vector initialization in this case as well
So in your case:
#include <stdio.h>
typedef struct crt8 {
double x;
double y;
double z;
} CART8;
int main(int argc, char** argv)
{
CART8 vector1;
vector1.x = 2.526;
vector1.y = 3.416;
vector1.z = 4.32;
printf("%f %f %f\n", vector1.x, vector1.y, vector1.z);
}
Alternatively, you can always resort to the original struct definition:
#include <stdio.h>
typedef struct crt8 {
double x;
double y;
double z;
} CART8;
int main(int argc, char** argv)
{
struct crt8 x;
x.x = 2.341;
x.y = 3.43;
x.z = 4.521;
printf("%f %f %f\n", x.x, x.y, x.z);
}
You wrote:
typedef struct crt8 {
double x;
double y;
double z;
} CART8;
This defined a new 'type'. The 'typename' is struct crt8 or the alias you defined CART8. This is how you instantiate an object from that type in C:
struct crt8 myVector;
or you can use the alias 'CART8' that you've defined:
CART8 myVector;
Either way, this is how you populate the 'members' of your object:
CART8 x; // Creation of object
x.x = 100;
x.y = 101;
x.z = 102;
Here is a demonstrative program that shows various ways how objects of the structure can be created, initialized, and used.
#include <stdio.h>
#include <math.h>
typedef struct crt8 {
double x;
double y;
double z; } CART8;
int main( void )
{
CART8 vector1 = { 1.1, 2.2, 3.3 };
CART8 vector2 = { .x = 1.1, .y = 2.2, .z = 3.3 };
CART8 vector3;
vector3.x = 1.1;
vector3.y = 2.2;
vector3.z = 3.3;
CART8 vector4 = vector1;
CART8 vector5 = { vector1.x + vector2.z, vector1.y + vector2.y, vector1.z + vector2.x };
printf( "vector5 = { %lf, %lf, %lf }\n", vector5.x, vector5.y, vector5.z );
printf( "Magnitude = %lf", sqrt( pow( vector1.x, 2 ) + pow( vector1.y, 2 ) + pow( vector1.z, 2 ) ) );
return 0;
}
The output is
vector5 = { 4.400000, 4.400000, 4.400000 }
Magnitude = 4.115823
Im having a small math library for 3d vector and Im trying to "unify" it.
Instead of having multiple typedef struct for vector3f, vector3i, color3, angles etc... Im trying to put everything inside the same struct like this:
typedef struct
{
union
{
float x;
float r;
float ax;
int x_int;
};
union
{
float y;
float g;
float ay;
int y_int;
};
union
{
float z;
float b;
float az;
int z_int;
};
} vec3;
Everything works peachy as long as the type is float, however when it falls to int Im having some strange values (which is understandable). My question is: Is there a way to cast directly/automatically inside the structure definition or I have to create extra functions to typecast between float and int?
Due to the answers below, maybe I should modify my original question to the following:
What is the best way to "unify" (and by unify I mean have like 1 struct) to be able to handle at the same time the following:
vector3f (float x,y,z)
vector3i (int x,y,z)
RGB (float r,g,b)
RGB (unsigned char r,g,b)
euler angle (ax, ay, az)
Thanks in advance!
If you mean that you want to put '360.0f' into float z of a union and have int z_int == 3, or vice versa, you can't. That is not the purpose of a union, and the binary representation of 3 (an integer) and 3.0 (a floating point value) are dissimiliar.
However, you could just remove the int and cast one of the floats to an int.
#include <stdio.h>
#include <stdlib.h>
typedef struct genericStruct
{
void *valueOne;
void *valueTwo;
}GS;
int main()
{
GS *gs = malloc(sizeof(*gs));
int valueInt = 10;
float valueFloat = 3.141592653589;
int *inputIntPtr = (int*)malloc(sizeof(int));
float *inputFloatPtr = (float*)malloc(sizeof(float));
void *voidPtr = NULL;
*inputIntPtr = valueInt;
*inputFloatPtr = valueFloat;
voidPtr = inputIntPtr;
gs->valueOne = voidPtr;
int *outputIntPtr = (int*)malloc(sizeof(int));
outputIntPtr = gs->valueOne;
printf("Input ptr = %d\n", *inputIntPtr);
printf("Output ptr = %d\n", *outputIntPtr);
voidPtr = inputFloatPtr;
gs->valueTwo = voidPtr;
float *outputFloatPtr = (float*)malloc(sizeof(float));
outputFloatPtr = gs->valueTwo;
printf("Input ptr = %f\n", *inputFloatPtr);
printf("output ptr = %f\n", *outputFloatPtr);
free(gs);
free(inputIntPtr);
free(inputFloatPtr);
free(outputIntPtr);
free(outputFloatPtr);
return 0;
}
And this what I meant by using void types.
This is a small piece of code that i wrote for you.It should do the job.I hope i was able to do what you asked for...
typedef struct{
void *ptr1;
void *ptr2;
void *ptr3;
}VEC;
main(){
VEC v ;
VEC *ptr;
int a = 5;
double b = 6;
float c = 7;
v.ptr1 = NULL;
v.ptr2 = NULL;
v.ptr3 = NULL;
ptr = &v;
v.ptr1 = (int *)&a;
ptr->ptr1 = (int *)&a;
v.ptr2 = (double *)&b;
ptr->ptr2 = (double *)&b;
v.ptr3 = (float *)&c;
ptr->ptr3 = (float *)&c;
printf("%d\n",*(int *)v.ptr1);
printf("%d\n",*(int *)(ptr->ptr1));
printf("%lf\n",*(double *)v.ptr2);
printf("%lf\n",*(double *)(ptr->ptr2));
printf("%f\n",*(float *)v.ptr3);
printf("%f\n",*(float *)(ptr->ptr3));
}
Or change all variables to void pointer type and then cast them to float or integer. Is it OK?
I'm trying to make an array of structs where each struct represents a celestial body.
I don't have that much experience with structs, which is why I decided to try to use them instead of a whole bunch of arrays. However, I keep on running into numerous different errors. I've tried to implement the techniques that I've seen on various threads and on StackOverflow (such as Array of structs in C and C - initialize array of structs), however not all of them were applicable.
Further information for those who have read this far: I don't need any of this to be dynamic, I know/define the size of everything beforehand. I also need this to be a global array as I'm accessing this in several different methods which have defined arguments (i.e. GLUT methods).
This is how I'm defining the struct in my header:
struct body
{
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
};
I have a list of other global variables that I'm defining before I define the interior of the struct, and one of those is the array of this struct (basically, if I'm being too unclear in my fogged speak, the line below is above the stuff above):
struct body bodies[n];
Just so you know, n is something that I've legitimately defined (i.e. #define n 1).
I use this array in several different methods, but the easiest and least space consuming one is a simplified form of my main. Here I initialize all of the variables in each of the structs, just to set the variables for certain before I modify them in some way:
int a, b;
for(a = 0; a < n; a++)
{
for(b = 0; b < 3; b++)
{
bodies[a].p[b] = 0;
bodies[a].v[b] = 0;
bodies[a].a[b] = 0;
}
bodies[a].mass = 0;
bodies[a].radius = 1.0;
}
The current error that I'm facing is nbody.c:32:13: error: array type has incomplete element type where line 32 is where I'm making the array of the structs.
One last clarification, by header I mean the space above int main(void) but in the same *.c file.
#include<stdio.h>
#define n 3
struct body
{
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
};
struct body bodies[n];
int main()
{
int a, b;
for(a = 0; a < n; a++)
{
for(b = 0; b < 3; b++)
{
bodies[a].p[b] = 0;
bodies[a].v[b] = 0;
bodies[a].a[b] = 0;
}
bodies[a].mass = 0;
bodies[a].radius = 1.0;
}
return 0;
}
this works fine. your question was not very clear by the way, so match the layout of your source code with the above.
Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.
Use the typedef specifier to avoid re-using the struct statement everytime you declare a struct variable:
typedef struct
{
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
}Body;
Then declare your array of structs. Initialization of each element goes along with the declaration:
Body bodies[n] = {{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0},
{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0},
{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}};
To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.
So to put it all together by using malloc():
int main(int argc, char** argv) {
typedef struct{
char* firstName;
char* lastName;
int day;
int month;
int year;
}STUDENT;
int numStudents=3;
int x;
STUDENT* students = malloc(numStudents * sizeof *students);
for (x = 0; x < numStudents; x++){
students[x].firstName=(char*)malloc(sizeof(char*));
scanf("%s",students[x].firstName);
students[x].lastName=(char*)malloc(sizeof(char*));
scanf("%s",students[x].lastName);
scanf("%d",&students[x].day);
scanf("%d",&students[x].month);
scanf("%d",&students[x].year);
}
for (x = 0; x < numStudents; x++)
printf("first name: %s, surname: %s, day: %d, month: %d, year: %d\n",students[x].firstName,students[x].lastName,students[x].day,students[x].month,students[x].year);
return (EXIT_SUCCESS);
}
I think you could write it that way too. I am also a student so I understand your struggle. A bit late response but ok .
#include<stdio.h>
#define n 3
struct {
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
}bodies[n];
move
struct body bodies[n];
to after
struct body
{
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
};
Rest all looks fine.
Solution using pointers:
#include<stdio.h>
#include<stdlib.h>
#define n 3
struct body
{
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double *mass;
};
int main()
{
struct body *bodies = (struct body*)malloc(n*sizeof(struct body));
int a, b;
for(a = 0; a < n; a++)
{
for(b = 0; b < 3; b++)
{
bodies[a].p[b] = 0;
bodies[a].v[b] = 0;
bodies[a].a[b] = 0;
}
bodies[a].mass = 0;
bodies[a].radius = 1.0;
}
return 0;
}
That error means that the compiler is not able to find the definition of the type of your struct before the declaration of the array of structs, since you're saying you have the definition of the struct in a header file and the error is in nbody.c then you should check if you're including correctly the header file.
Check your #include's and make sure the definition of the struct is done before declaring any variable of that type.
You can do it in a same manner as you create the array of numbers but wrap the element's values in braces like this ->
struct Wrestler studs[count] = {
{"John", "Cena"},
{"The", "Undertaker"},
{"The", "Big Show"},
{"The", "Rock"},
{"Triple", "H"},
{"Scott", "Hall"},
{"Roman", "Reings"},
{"Dean", "Ambrose"}};
Here is full code
#include <stdio.h>
struct Wrestler
{
char firstName[20];
char secondName[20];
};
void pIntro(struct Wrestler *s)
{
printf("Hi, I am %s %s.\n", s->firstName, s->secondName);
};
int main(int argc, char const *argv[])
{
#define count 8
struct Wrestler studs[count] = {
{"John", "Cena"},
{"The", "Undertaker"},
{"The", "Big Show"},
{"The", "Rock"},
{"Triple", "H"},
{"Scott", "Hall"},
{"Roman", "Reings"},
{"Dean", "Ambrose"}};
for (int i = 0; i < count; i++)
{
pIntro(&(studs[i]));
}
return 0;
}