0

I know C requires that size of array be explicitly defined before use. But if I malloc a pointer variable of struct type and use its arrays without previously declaring its size.

  • 3
    Your title says you're allocating 'an array of pointers' but your question says 'malloc a pointer variable of struct type', so I'm confused. Can you show us a simple code example what you mean? – Rup Apr 14 '20 at 14:16
  • 1
    When you call `malloc`, you must also specify the size of the allocation. Therefore, I see no advantage, other than that you can change the size of the allocation at run-time (whereas the size of static arrays must be specified at compile-time). – Andreas Wenzel Apr 14 '20 at 14:16
  • 1
    If you have an array of pointers and want to extent it, [`realloc`](https://en.cppreference.com/w/c/memory/realloc) is your friend. – Ted Lyngmo Apr 14 '20 at 14:23

1 Answers1

0

Yes this is entirely possible:

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

int main() {
    char *array = (char *) malloc(64);
    strncpy(array, "Hello World", 64);
    printf("%c \n  %s",array[0], array);
    return 0;
}

results in
/home/pixel/Desktop/programs/c_programs/cmake-build-debug/stout H Hello World Process finished with exit code 0

Be sure you bounds check your array when using it, as going over your malloc'd bytes will cause undefined behaviour

Pixel
  • 31
  • 1
  • 5