Can you define the size of an array at runtime in

2020-02-28 19:15发布

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...

10条回答
趁早两清
2楼-- · 2020-02-28 19:17

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;
}
查看更多
SAY GOODBYE
3楼-- · 2020-02-28 19:17

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.

查看更多
相关推荐>>
4楼-- · 2020-02-28 19:24

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);
}
查看更多
闹够了就滚
5楼-- · 2020-02-28 19:27

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.

查看更多
We Are One
6楼-- · 2020-02-28 19:29

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?

查看更多
我只想做你的唯一
7楼-- · 2020-02-28 19:34

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.

查看更多
登录 后发表回答