C, The problem of getting the size of an array of structures

I am trying to get the number of elements in an array of structures so that I can pass it to another function. Struct:

struct info{
    char string1[30];
    float float1;
    int int1;
    char string2[30];
};

The section I'm trying to run:

void function1(){
    struct info* temp = build();
    printf("flag: %lu %lu %lu\n", sizeof(temp), sizeof(temp[0]), sizeof(temp)/sizeof(temp[0]));
    sortFloat(temp, sizeof(temp)/sizeof(temp[0]), 1);
    free(temp);
}

build () returns an array of structures after reading in the data from the file, where each row will be a structure in the array. I'm having trouble passing the size of the array to sortFloat (). Print line returns

flag: 8 72 0

when there are only two lines in the data file. Hard coding this argument as 2 makes the whole program workable. Why is this method of counting the elements of an array of structures not?

+4
source share
3 answers
sizeof(temp)

. .

, :

build :

struct info* build(int* sizePtr);

, sizePtr .

, :

int size;
struct info* temp = build(&size);
+3

, , . , , function1(). build() , .

- build(), , . - int build(int *countp) build(int *countp) int, ++*countp;, *countp = n;, n - , build(...) .

+1

temp . . sizeof .

, C ( , ) , . , .

sizeof - , . , - .

What you create and return from build()is most likely a dynamically allocated (through mallocor friends) memory buffer. In this case, it was never a real array! This is just a pointer to a piece of memory on the heap. This piece of memory is not a single value, and its size cannot be determined using sizeof. Thus, you have no choice but to count the number allocated structand get this information to the caller.

+1
source

All Articles