rhr
rhr

Reputation:

Can you define the size of an array at runtime in C

New to C, thanks a lot for help.

Is it possible to define an array in C without either specifying its size or initializing it.

For example, can I prompt a user to enter numbers and store them in an int array ? I won't know how many numbers they will enter beforehand.

The only way I can think of now is to define a max size, which is not an ideal solution...

Upvotes: 8

Views: 33146

Answers (10)

Nagendra
Nagendra

Reputation: 121

Above given answers are correct but there is one correction, the function malloc() reserve a block of memory of specified size and return a pointer of type void* which can be casted into pointer of any form. Syntax: ptr = (cast-type*) malloc(byte-size)

#include<stdio.h>
#include<cstdlib>
int main(int argc,char* argv[]){
int *arraySize,length;
scanf("%d",&length);
arraySize = (int*)malloc(length*sizeof(int));
for(int i=0;i<length;i++)
    arraySize[i] = i*2;
for(int i=0;i<length;i++)
    printf("arrayAt[%d]=%d\n",i,arraySize[i]);
free(arraySize);
}

Upvotes: 0

Joel
Joel

Reputation: 197

Yes, absolutely. C99 introduced the VLA or Variable Length Array. Some simple code would be like such:

#include <stdio.h>

int main (void) {

    int arraysize;
    printf("How bid do you want your array to be?\n");
    scanf("%d",&arraysize);
    int ar[arraysize];  
    return 0;
}

Upvotes: 4

fortran
fortran

Reputation: 76057

If you're a beginner, maybe you don't want to deal with malloc and free yet. So if you're using GCC, you can allocate variable size arrays on the stack, just specifying the size as an expression.

For example:

#include <stdio.h>
void dyn_array(const unsigned int n) {
        int array[n];
        int i;

        for(i=0; i<n;i++) {
                array[i]=i*i;
        }
        for(i=0; i<n;i++) {
                printf("%d\n",array[i]);
        }
}
int main(int argc, char **argv) {
        dyn_array(argc);
        return 0;
}

But keep in mind that this is a non standard extension, so you shouldn't count on it if portability matters.

Upvotes: 1

Richie
Richie

Reputation: 9266

If all you need is a data structure where in you can change its size dynamically then the best option you can go for is a linked list. You can add data to the list dynamically allocating memory for it and this would be much easier!!

Upvotes: 2

BobbyShaftoe
BobbyShaftoe

Reputation: 28499

Well, you can dynamically allocate the size:

#include <stdio.h>

int main(int argc, char *argv[])
{
  int *array;
  int cnt;
  int i;

  /* In the real world, you should do a lot more error checking than this */
  printf("enter the amount\n");
  scanf("%d", &cnt);

  array = malloc(cnt * sizeof(int));

  /* do stuff with it */
  for(i=0; i < cnt; i++)
    array[i] = 10*i;

  for(i=0; i < cnt; i++)
    printf("array[%d] = %d\n", i, array[i]);

  free(array);

  return 0;
}

Upvotes: 15

blwy10
blwy10

Reputation: 4892

If you're looking for array facilities and don't want to roll your own, try the following:

  1. Glib
  2. Apache APR
  3. NSPR

Upvotes: 0

Matthew
Matthew

Reputation: 1

For something like this, you might want to look into data structures such as: Linked Lists (Ideal for this situation) Various Trees (Binary Trees, Heaps, etc) Stacks & Queues

But as for instantiating a variable sized array, this isn't really possible.

The closest to a dynamic array is by using malloc and it's associated commands (delete, realloc, etc).

But in this situation, using commands like malloc may result in the need to expand the array, an expensive operation where you initialize another array and then copy the old array into that. Lists, and other datatypes, are generally much better at resizing.

Upvotes: 0

Joel
Joel

Reputation: 11851

Perhaps something like this:

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

/* An arbitrary starting size. 
   Should be close to what you expect to use, but not really that important */
#define INIT_ARRAY_SIZE 8

int array_size = INIT_ARRAY_SIZE;
int array_index = 0;
array = malloc(array_size * sizeof(int));

void array_push(int value) {
  array[array_index] = value;
  array_index++;
  if(array_index >= array_size) {
    array_size *= 2;
    array = realloc(array, array_size * sizeof(int));
  }
}

int main(int argc, char *argv[]) {
  int shouldBreak = 0;
  int val;
  while (!shouldBreak) {
    scanf("%d", &val);
    shouldBreak = (val == 0);
    array_push(val);
  }
}

This will prompt for numbers and store them in a array, as you asked. It will terminated when passed given a 0.

You create an accessor function array_push for adding to your array, you call realloc from with this function when you run out space. You double the amount of allocated space each time. At most you'll allocate double the memory you need, at worst you will call realloc log n times, where is n is final intended array size.

You may also want to check for failure after calling malloc and realloc. I have not done this above.

Upvotes: 6

hasen
hasen

Reputation: 166122

You can use malloc to allocate memory dynamically (i.e. the size is not known until runtime).

C is a low level language: you have to manually free up the memory after it's used; if you don't, your program will suffer from memory leaks.

UPDATE

Just read your comment on another answer.

You're asking for an array with a dynamically-changing-size.

Well, C has no language/syntactic facilities to do that; you either have to implement this yourself or use a library that has already implemented it.

See this question: Is there an auto-resizing array/dynamic array implementation for C that comes with glibc?

Upvotes: 0

Tordek
Tordek

Reputation: 10872

Arrays, by definition, are fixed-size memory structures. You want a vector. Since Standard C doesn't define vectors, you could try looking for a library, or hand-rolling your own.

You need to do dynamic allocation: You want a pointer to a memory address of yet-unkown size. Read up on malloc and realloc.

Upvotes: 3

Related Questions