3

我有一个结构:

struct numbers_struct {
char numbers_array[1000];
};

struct numbers_struct numbers[some_size];

创建结构后,有一个整数作为输入:

scanf("%d",&size);

我需要使用malloc(size)并指定数组编号的大小。(而不是 some_size 使用大小)

在 C 语言中这样的事情可能吗?

4

5 回答 5

5

是的,但malloc()需要数组所需的内存总量,而不是元素的数量:

struct numbers_struct* numbers = malloc(size * sizeof(*numbers));
if (numbers)
{
}

请注意,您必须scanf()在使用之前检查返回值size(在这种情况下这是一个糟糕的名称),否则如果失败,代码可能正在使用未初始化的变量scanf()

int number_of_elements;
if (1 == scanf("%d", &number_of_elements))
{
    struct numbers_struct* numbers =
        malloc(number_of_elements * sizeof(*numbers));
    if (numbers)
    {
        free(numbers); /* Remember to release allocated memory
                          when no longer required. */
    }
}

Variable length arrays were introduced in C99 but there are restrictions around their use (they cannot be used at file scope for example).

于 2012-10-12T07:38:48.823 回答
4

也许你可以这样做

 struct numbers_struct {
char numbers_array[1000];
};

scanf("%d",&size);

struct numbers_struct *numbers = malloc(sizeof(numbers_struct) * size);
于 2012-10-12T07:37:56.390 回答
1

请参阅文档中的“calloc”、“alloc”和“realloc”用法。

于 2012-10-12T07:36:05.477 回答
1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int  main(void){
    struct numbers_struct {
        char numbers_array[1000];
    };

    int size = 10;
    int i;
    struct numbers_struct *s= malloc(size * sizeof(struct numbers_struct));

    for (i=0;i<size;i++){
        snprintf(s[i].numbers_array, 20, "test index %d", i);
    }

    for (i=0;i<size;i++){
        printf("%s\n", s[i].numbers_array);
    }

    free(s);
}
于 2012-10-12T07:52:07.370 回答
1

VLA is possible in C99.

you can do it

int main()
{
char *p;//I have used char you can use any pointer
int k;
scanf("%d",&k);
p=malloc(k);//just allocated the memory and given the  memory address to p

//after use 
free(p);
}

It will compile without any error.

于 2012-10-12T09:31:05.490 回答