0

I´m working on my program, that loads data from external .txt file - it is structure of 3 integers. Now Im struggling with function that allocates memory. I want to allocate memory for structure of 9 members (108 bytes).

My main program was too large to mess with so I created a smaller program to help me more easily figure out what is going on. Previous questions I went through seemed too complicated and unclear to me, that´s why I made my own.

Id like to know why the third printf, prints 4 and how to correctly allocate required memory (108 bytes)

Glad for any advice

 #include <stdio.h>
 #include <math.h>

    int main(){
        int object_counter = 9;

        typedef struct myStruct {
         int name;
         int age;
         int height;
        } myStruct;

        myStruct* dynamicStruct;
        dynamicStruct = malloc(object_counter*sizeof(myStruct));
        if (dynamicStruct == NULL) {
            printf("ERROR\n");
            return (-1);
        } else {
            printf("SUCCESS\n");
        }
        printf("Size is: %lu\n", sizeof(myStruct));             // prints 12, thats 3 times int, OK
        printf("Size is: %lu\n", object_counter*sizeof(struct myStruct));   // prints 108, obviously 9 times 4 bytes
        printf("Size is: %lu\n", sizeof(dynamicStruct));        // prints 4 ?? (expected 108)
        return 0;
    }
Michael91
  • 1
  • 2

1 Answers1

0

The sizeof any pointer is constant (8 bytes on my Linux/x86-64 system, which is also the sizeof(uintptr_t), etc....). It is unrelated to the runtime size of the pointed memory zone. In other words, the sizeof operator always gives a compile-time constant (except for VLAs).

You practically need to keep elsewhere the allocated size of a malloc-ed pointer. For example, you could keep the pointer value in one variable, and its allocated size in another variable.

You could consider an abstract data type (using flexible array members) approach like here.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547