How can I implement an array whose size is not known at compile time in C89? [closed]

StackOverflow https://stackoverflow.com/questions/20802302

  •  22-09-2022
  •  | 
  •  

문제

Sorry, I'm a bit of a newbie to C and was wondering how you could create an array whose size is not known at compile time before the C99 standard was introduced.

도움이 되었습니까?

해결책

It's very easy. For example, if you want to create a variable length 1D int array, do the following. First, declare a pointer to type int:

int *pInt;

Next, allocate memory for it. You should know how many elements you will need (NUM_INTS):

pInt = malloc(NUM_INTS * sizeof(*pInt));

Don't forget to free your dynamically allocated array to prevent memory leaks:

free(pInt);

다른 팁

Use malloc function from stdlib.h to create a dynamic array object.

the ordinary way would be to allocate the data on the heap

  #include <stdlib.h>
  void myfun(unsigned int n) {
    mytype_t*array = (mytype_t*)malloc(sizeof(mytype_t) * n);
    // ... do something with the array
    free(array);
  }

you could also allocate on the stack (so you don't need to free manually):

  #include <alloca.h>
  void myfun(unsigned int n) {
    mytype_t*array = (mytype_t*)alloca(sizeof(mytype_t) * n);
    // ... do something with the array
  }

You can do this by dynamic memory allocation. Use malloc function.

malloc or calloc

YourType* ptr = malloc(sizeof(YourType)*NumberOfItemsYouNeed)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top