我的结构看起来像-
struct stack{
int top;
char string[size][80];
}stackV;
我想为用户提供在运行时分配 char 字符串数组大小的选项。 我曾使用 scanf 函数来执行此操作 -
我试图通过做 -
int size=0;
struct stack{
int top;
char string[size][80];
} stackV;
但是通过这样做我得到警告说 - 在文件范围可变修改'string'
有什么方法可以将大小分配给结构成员数组。 我无法在任何函数内创建结构,因为结构成员也被其他函数使用。
最佳答案
您可以使用一个灵活的数组成员来实现您所需要的:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef struct
{
int top;
char string[][80];
} stackv;
int main()
{
size_t strings = 3;
stackv* s = malloc(sizeof(stackv) + strings*80);
strcpy(s->string[0], "test");
strcpy(s->string[1], "hello");
strcpy(s->string[2], "world");
for(size_t i=0; i<strings; i++)
{
puts(s->string[i]);
}
free(s);
return 0;
}
char string[][80];
的声明告诉编译器在结构的末尾会有未知数量的 char [80]
数组.
sizeof(stackv)
因此只会给出除最后一个成员之外的所有其他成员的大小(在本例中为整数)。
关于c - 如何在运行时在 c 中给出结构数组成员的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40286964/