c - 如何在运行时在 c 中给出结构数组成员的大小

标签 c arrays data-structures struct structure

我的结构看起来像-

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/

相关文章:

c - 从回调线程安全实现中检索信息

c - 在 C 中重新分配数组

c - 使用动态数组实现堆栈

arrays - 如何在 hive sql 中将数组转换为字符串?

java - 具有日期范围的 HashMap

java - TreeSet 在应该返回 true 时返回 false?

python - GCC 不使用安装到虚拟环境的库进行编译

c - 从 header 自动生成 C 代码

c# - 使用数组作为 string.Format() 的参数

algorithm - 支持基于范围的最常出现元素查询的数据结构