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