0

i am a student and i try to teach myself code. My question:

i have two structs:

struct1{
int a;
char name[20];}

struct 2{
struct struct1 *objekt;
int number;
double dNumber;}

I wanted to dynamically allocate memory in order to create at least one new Objekt(for lack of a better word). I know for example that i can allocate memory by using malloc or calloc. Which is fine. But how can i add a new object dynamically and via the console input, without defining a new struct? I am a complete novice and sorry. Thank you.

1 Answers1

1

Consider the following example:

#include <stdio.h>
#include <stdlib.h>

struct Struct {
    int a;
    char name[20];
};

struct Struct struct1;

int main()
{
    struct Struct *struct1_p;
    struct1_p = &struct1;
    struct1.a = 1; 
    printf("struct1->a = %d\n", struct1_p->a);
    // Now let's create new structure dynamically
    struct Struct * struct2 =  malloc(sizeof(struct Struct));
    // Now check if the allocation succeeded?
    if(struct2 != NULL) { 
        //Success
        //struct2 now is a pointer to the memory which is reserved for struct2. 
        struct2->a = 2;
    } else {
        // Allocation failed
    }
    printf("struct2->a = %d\n", struct2->a);


    return 0;
}

This way, having the type of the desired object, you can dynamically create new object in the memory. Accessing the newly created object via pointer returned by malloc. Remember that malloc returns void*, no need for explicitly cast.

Hairi
  • 3,318
  • 2
  • 29
  • 68
  • [It's better not to cast the result of malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). There is little sense in explicit casting a `void *` pointer. – KamilCuk Nov 26 '18 at 17:45
  • @Hairi This is helpful and adds a lot to my understanding. Thank you very much. – Herro Phong Nov 26 '18 at 17:58
  • @KamilCuk I think you are right. Though I have seen the explicit cast many times. I don't know why would they do that. I changed the answer. – Hairi Nov 26 '18 at 18:01
  • @HerroPhong I am glad to here that it helped you. – Hairi Nov 26 '18 at 18:02
  • @HerroPhong You can check as correct answer if you find it satisfactory – Hairi Nov 26 '18 at 19:23