我有一个结构:
struct numbers_struct {
char numbers_array[1000];
};
struct numbers_struct numbers[some_size];
创建结构后,有一个整数作为输入:
scanf("%d",&size);
我需要使用malloc(size)
并指定数组编号的大小。(而不是 some_size 使用大小)
在 C 语言中这样的事情可能吗?
是的,但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).
也许你可以这样做
struct numbers_struct {
char numbers_array[1000];
};
scanf("%d",&size);
struct numbers_struct *numbers = malloc(sizeof(numbers_struct) * size);
请参阅文档中的“calloc”、“alloc”和“realloc”用法。
#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);
}
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.