How to add a structure member dynamically in C? - c

struct point {
int x;
int y;
};
main() {
struct point a;
a.x = 5;
a.y = 10;
printf("%d %d", a.x, a.y);
}
Output:
5 10
Here if I want add a member (int z) int the same structure dynamically.
What is the procedure?
What I have tried:
struct point {
int x;
int y;
};
struct newpoint {
struct point a;
int z;
};
I have tried the above steps, through which we have added a new member and the old structure point to new structure newpoint. But this is not what I want, I want to add the new member the same structure dynamically. I got this question in an interview.

The interviewer that asked you this has set you on a trap.
It's impossible to "dynamically define a struct" in C. It's possible to do "duck-typing in other languages, for example JavaScript, but C structures are compile time definitions and are as static as it gets.

Related

How do I implement a struct with two floats in C?

error: must use "struct" tag to refer to type 'point'
All I want to do is store a coordinate as a struct.
This seems maddeningly simple to do but yet I cannot do it after visiting 20 websites and scouring Kernaghan's book.
What am I missing?
#include <stdio.h>
int main()
{
struct point
{
float x;
float y;
};
point.x = 0.0;
point.y = 1.9;
return 0;
}
You defined a type called struct point, not a variable name using that definition. You'd want to either define an instance of the struct using that type:
struct point mypoint; // In C, you could change mypoint to point, but that gets confusing
or (less common) declare variables with a type of the (possibly anonymous) struct definition by putting the name after the struct definition, before the semi-colon:
struct {
float x;
float y;
} point;
All you've declared is a type named struct point ; you haven't created an object named point to manipulate. You need a separate object definition, either by writing:
struct point {
float x;
float y;
};
struct point pvar;
or
struct point {
float x;
float y;
} pvar;
then you can manipulate the members of the object:
pvar.x = 0.0;
pvar.y = 1.9;
etc.
The "point" in your example is a struct tag, not a variable name. You have declared a type named struct point, but not any variable having that type. Where that declaration is in scope, you can declare variables having that type with the form
struct point my_point;
and then assign to their members as
my_point.x = 0.0;
my_point.y = 1.9;
What you have done, is similar to saying int = 3; This is more like it:
#include<stdio.h>
int main(void) {
struct point {
float x;
float y;
} s;
s.x = 0.0;
s.y = 1.9;
return 0;
}
But you should see compiler warnings, because the code assigns double values to float. It is better not to use the inferior float type unless you are forced to.
You need to have a structure object, ie instantiate the structure.
struct point obj;
obj.x = 0.0;
obj.y = 1.9;
Other options available are
struct point // Note,structure is tagged 'point' which enables multiple instantiations
{
float x;
float y;
}obj;
and
struct // Anonymous structure with one & only one instance possible
{
float x;
float y;
}obj;
and finally a typedef which is also a common practice
typedef struct point
{
float x;
float y;
}point;
point obj;
obj.x = 0.0;
obj.y = 1.9;

How to make a pointer to a varible inside nested structs in C?

In the following code,how to create a pointer to the variable triangle.pluto.mars.a so it becomes unnecessary in the printf line to repeat the whole path for member a.
#include <stdio.h>
int main(){
struct euler {
int a;
int b;
};
struct gauss {
int f;
int g;
struct euler mars;
};
struct aristotle{
int x;
int y;
struct gauss pluto;
} triangle;
triangle.pluto.mars.a = 151;
printf("\nThe value is: %d\n\n",triangle.pluto.mars.a );
return 0;
}
The band-aid solution:
int * someVariable = &(triangle.pluto.mars.a);
The long solution: Do a redesign.
If you are willing to rearrange your structures, you will have a more "intuitive" means of accessing your members. While C does not offer inheritance, it does guarantee that the pointer to the first member of a structure is equal in value to the pointer to the containing structure. This allows you to mimic inheritance like behavior via pointer conversion.
struct euler {
int a;
int b;
};
struct gauss {
struct euler mars;
int f;
int g;
};
struct aristotle{
struct gauss pluto;
int x;
int y;
} triangle;
triangle.pluto.mars.a = 151;
struct euler *e = (void *)&triangle;
struct gauss *g = (void *)&triangle;
printf("\nThe value is: %d\n\n", e->a );
This guarantee is stated in C.11 §6.7.2.1 ¶15 (emphasis mine, and similar language exists in C.99):
Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.
This does not take away from #LawrenceAiello's answer, which still works after the reorganization suggested above.
int *num = &(triangle.pluto.mars.a);
I suggest you redesign your structs fields to be pointers.
Such as
struct euler {
int *a;
int *b;
};

typedef, structure and type compatibiliy

If I have these two structs:
struct
{
int x;
} A;
struct
{
int x;
} B;
then making A = B; results in a compilation error because the two anonymous structs are not compatible.
However if I do:
typedef struct
{
int x;
} S;
S A;
S B;
A = B; is a legal assignment because they are compatible.
But why? With typedef I understand that the compiler makes this when meet S A and S B:
struct { int x; } A;
struct { int x; } B;
so A and B should not be compatible...
Each anonymous struct declaration is a distinct type; this is why you get a type mismatch when trying to assign one to the other.
A typedef, however, declares an alias (i.e. a new name for something that already exists) for a type (it does not create a new type).
A typedef is also not a simple text replacement, like a preprocessor macro. Your statement
I understand that the compiler make this when meet S A and S B:
struct { int x; } A;
struct { int x; } B;
is where your understanding is wrong.
When you use the type alias S, as in
S A;
S B;
the types of both objects A and B are the same by definition and assigning one to the other is possible.
This is because C treats every untagged struct as a new kind of struct, regardless of the memory layout. However, typedef struct { } name; cannot be used if you want to use the struct in a linked list. You'll need to stick with defining a structure tag in this case, and typedef the tagged struct instead.
struct DistanceInMeter /* Anonymous 1 */
{
int x; /* distance */
};
struct VolumeInCC /* Anonymous 2 */
{
int x; /* volume */
};
struct DistanceInMeter A;
struct VolumeInCC B;
...
A = B; /* Something is wrong here */
Equating different type doesn't always make sense and thus is not allowed.
typedef struct DistanceInMeter /* Anonymous 1 */
{
int x; /* distance */
} Dist_t;
Dist_t C, D;
...
C = D; /* Alright, makes sense */

Initializing structure array inside a structure array

I have a question in initializing my structure array inside a structure array. for example if I have a code as below:
#include <stdio.h>
int main() {
typedef struct {
int a;
int b;
int c;
} FIRST_T;
typedef struct {
int x;
int y;
int z;
FIRST_T *p;
} SECOND_T;
FIRST_T p1[]={{1,2,3},{3,4,5},{6,7,8}};
FIRST_T p2[]={{4,5,6},{7,8,9}};
SECOND_T my_second[]=
{
{1,2,3,p1},
{4,5,6,p2}
};
}
if I have to initialize my first array in second array intialization part itself, then how would I write my typedef of SECOND_T?
like
SECOND_T my_second[]=
{
{1,2,3,{{1,2,3},{4,5,6},{7,8,9}}},
{4,5,6,{{1,1,1},{2,2,2}}}
};
then how should be my SECOND_T?
I am sure I can't define it as:
typedef struct {
int x;
int y;
int z;
FIRST_T p[]; //(I know its a blunder)
} SECOND_T;
Please help.
You can't define a type with unbounded array in C, you have to specify the dimension. So you either do:
typedef strut {
int x;
int y;
int z;
FIRST_T f[SOME_VALUE];
} SECOND_T;
and then initialize SOME_VALUE count of members always, or do it the way you did.
I don't think you can do this, i.e, initialize the FIRST_T inside the initialization of SECOND_T, other than the first way you do it. Think about it, how can the compiler tell how many FIRST_T are there in SECOND_T? The problem here is, you can NOT define an array of flexible size struct statically.
you can't to do like that:
SECOND_T my_second[]=
{
{1,2,3,{{1,2,3},{4,5,6},{7,8,9}}},
{4,5,6,{{1,1,1},{2,2,2}}}
};
with
typedef struct {
int x;
int y;
int z;
FIRST_T p[]; //(I know its a blunder)
} SECOND_T;
becase the compiler don't know how to malloc memory for this struct. if you must do like this, you should define
typedef struct { int x,y,z; FIRST_T p[CONST_VALUE];}SECOND_T;
but I advise you use the first style that you write.
I don't know if I completely capture the question that you have. If it is that you want to avoid to have to declare an auxiliary variable for the pointers in the structure you can use a compound literal as follows:
SECOND_T my_second[] = {
{1,2,3, &(FIRST_T){{1,2,3},{3,4,5},{6,7,8}}},
{4,5,6, &(FIRST_T){{4,5,6},{7,8,9}}}
};
You'd have a compiler that complies to C99 for that.

What is this operator(->) in C? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Arrow operator (->) usage in C
As far as i know only C++ can use classes(obj->something) however i have seen this operator in numerous C applications.
And a small side-question. Usually one uses structures in C like this:
structname.somevariable
However i have seen them used like:
structname.something1.something2
Does it have something to do with the keyword union?
struct A
{
int b;
};
struct A *a;
a->b == (*a).b;
And no, that has nothing to do with unions. It's just getting a member of a member.
if you have a pointer to a struct object, like
struct P * p;
you access members with ->
p->member
if p is not a pointer, you access members with .
struct P p;
p.member
Any C book covers this :P
Operator -> is used to access a member of a struct through a pointer to that structure. The second part of your question is used when accessing nested structures, it is not restricted to the use of unions. For instance:
struct A {
int a;
};
struct B {
struct A baz;
};
int main()
{
struct A foo;
struct B bar;
(&foo)->a = 10;
bar.baz.a = 20;
return 0;
}
C++ classes are an extension of C structs, and an object is just a pointer to a struct. C++ didn't actually invent a whole lot of new stuff; it's called C ++ for a reason.
structs can be nested. Given
struct a {
int a_a;
int a_b;
}
struct b {
int b_a;
struct a b_b;
} a;
you can refer to a.b_b.a_b.
A union uses similar syntax to a struct, but all the members overlap each other. This is useful when you need to interpret a chunk of memory in multiple ways.
I strongly suggest picking up a C book.
x.y.z is used when you want to access a member of a struct that is itself a member of another struct.
typedef struct _POINT
{
int x;
int y;
} POINT;
typedef struct _RECT
{
POINT topLeft;
POINT bottomRight;
} RECT;
int main()
{
RECT r;
r.topLeft.x = 0;
t.topLeft.y = 0;
int width = r.bottomRight.x - r.topLeft.x;
}
I've written a small example in C.
#include <stdio.h>
#include <stdlib.h>
struct a_t {
int a;
/* ... */
};
struct b_t {
struct a_t a;
/* ... */
};
int main()
{
struct a_t a;
struct a_t *b;
b = malloc(sizeof(struct a_t));
a.a = 1;
b->a = 2;
printf("%d; %d;\n", a.a, b->a);
(&a)->a = 3;
(*b).a = 4;
printf("%d; %d;\n", a.a, b->a);
free(b);
struct b_t c;
c.a.a = 5;
printf("%d;\n", c.a.a);
return 0;
}
If I remember correctly, in C++
class IDENTIFIER {
// stuff, possibly including functions
};
is exactly the same as
struct IDENTIFIER {
private:
// stuff, possibly including functions
};
and
struct IDENTIFIER {
// stuff, possibly including functions
};
is exactly the same as
class IDENTIFIER {
public:
// stuff, possibly including functions
};

Resources