Home > Enterprise >  Determine the length of a dynamic array after creation time in C
Determine the length of a dynamic array after creation time in C

Time:06-17

int *p = malloc(sizeof(int)*10);
size_t val = sizeof(p)/sizeof(int);

printf("this array (p) can content %lu elements \n",val);

Hi everyone,

  1. I've been trying to make this program print "this array (P) can content 10 elements". But it doesn't work. ( for me, the value of val is suppose to be the length of this array. size of total elements of p divided by one element of p)

  2. and when i try to print the sizeof(p) after malloc, it's not equal to 4*10 (40);

May someone tell me what's going wrong?

CodePudding user response:

p is a pointer, sizeof(p) is not the size of the array that was allocated by malloc(), it is just the size of the pointer itself, which may be 4 or 8 depending on the platform (among other more exotic possibilities).

The expression sizeof(a) / sizeof(a[0]) only works for arrays, defined as int a[10]; or possibly with a length determined at compile time from the intializer: int a[] = { 0, 2, 4 };.

There is no portable way to retrieve the size of the block allocated by malloc() from the pointer. You must keep track of the size separately.

CodePudding user response:

See the other answer, and the comments under the question. You must keep track of the size yourself. Here is a basic demo:

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

int main()
{
    const size_t NUM_INTS = 10;
    
    int *p = (int*)malloc(sizeof(int)*NUM_INTS);
    printf("p can hold %zu integers\n", NUM_INTS);

    return 0;
}

Output:

p can hold 10 integers

How to containerize a dynamically-allocated array in C

1. Make an array_int_t "array of ints" container

Let's take it one step further and containerize it as an array of integers.

Container:

/// A container represending a dynamically-allocated array of integers
typedef struct array_int_s
{
    /// Pointer to the first element in a dynamically-allocated array
    /// of ints
    int * start;

    /// Number of elements in the array
    size_t size;
} array_int_t;

Usage:

array_int_t array_int;
array_int.start = (int*)malloc(sizeof(int)*NUM_INTS);
array_int.size = NUM_INTS;
    
printf("array_int can hold %zu integers\n", array_int.size);

2. [best] Add an array_int_create() constructor or "factory" function to create an array of ints

And one step further:

Add a create function:

/// Dynamically create and return an array of `num_elements` of type `int`.
array_int_t array_int_create(size_t num_elements)
{
    array_int_t dynamic_array = 
    {
        .start = (int*)malloc(sizeof(int)*num_elements),
        .size = num_elements,
    };
    
    return dynamic_array;
}

And use it:

array_int_t array_int2 = array_int_create(NUM_INTS);
printf("array_int2 can hold %zu integers\n", array_int2.size);
  • Related