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.
Asked
Active
Viewed 37 times
0
-
3Your 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
-
1When 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
-
1If 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 Answers
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