【问题标题】:How to give size of a structure array member in c at runtime如何在运行时在c中给出结构数组成员的大小
【发布时间】:2016-10-27 14:15:01
【问题描述】:

我的结构看起来像 -

struct stack{
 int top;
 char string[size][80];
}stackV;

我想给用户一个在运行时分配 char 字符串数组大小的选项。 我曾使用 scanf 函数来执行此操作 -

我试图通过这样做来实现它-

int size=0;
 struct stack{
  int top;
  char string[size][80];
 } stackV;

但是通过这样做,我得到了警告,上面写着 - 在文件范围内可变地修改了“字符串”

有什么方法可以为结构成员数组分配大小。 我无法在任何函数内创建结构,因为该结构成员也被其他函数使用。

【问题讨论】:

  • 寻找“灵活数组成员”。
  • 如果您使用堆栈数据结构,您应该尝试使用动态内存分配。
  • 你可以使用malloc
  • @Swanand 我试过这样做 - int size;大小 = (int)malloc(1*sizeof(int));结构栈{int top;字符字符串[大小][80]; }stackV;但我收到警告消息,显示此行有多个标记,其他警告说一元''的无效类型参数(有'int')
  • @SwetaSingh 您应该使用 malloc 将用户输入大小的内存分配给string

标签: c arrays data-structures struct structure


【解决方案1】:

您可以使用灵活的数组成员来实现您所需要的:

#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) 因此只会给出除最后一个成员之外的所有其他成员的大小(在本例中为整数)。

【讨论】:

    【解决方案2】:

    您不知道堆栈中有多少元素。 只有用户在运行时给你“大小”;所以你不能静态分配一个数组(编译时),而是在从用户那里获取大小时动态分配它(运行时)。 您收到“警告”,因为您从大小“0”定义“大小”,然后您尝试声明此大小的数组,根据规范,据我所知,没有大小为 0 的数组):

    ISO 9899:2011 6.7.6.2:
    
        If the expression is a constant expression, it shall have a value greater than zero.
    

    如何将数组动态分配为包含“大小”元素且每个元素为 80 个字符的字符串的结构?

    #define STR_LEN 80
    struct stack {
       int top;
       char *string;
    } stackv;
    
    enum {
        SUCCESS = 0,
        FAILURE,
    };
    
    int InitStack(stackv *stackv, int size) {
        if (size <= 0)
            return FAILURE;
    
        stackv->string = (char *)malloc(size*sizeof(char)*80);
        if (stackv->string == NULL)
            return FAILURE;
    
        stackv->top = 0;
    
        return SUCCESS;
    }
    

    在主函数中,您声明变量“stackv”并通过引用(指针)将其传递给我编写的初始化函数。

    【讨论】:

    • 我收到 Field 'string' could not be resolved 和 Field 'top' could not be resolved 警告
    • 确实不允许使用零大小的数组(包括 VLA),但警告的实际原因是您不能声明具有静态存储持续时间的 VLA - 这不会任何意义。如果你想这样做,你会使用一个普通的数组。
    【解决方案3】:

    这段代码对我来说是正确编译的:

    int size = 10;
    
    typedef struct 
    {
       int top;
       char string[size][80];
    } stackv;
    

    我正在使用:

    $ gcc --version
    gcc (Debian 5.4.1-3) 5.4.1 20161019
    Copyright (C) 2015 Free Software Foundation, Inc.
    

    【讨论】:

    • 因为你没有把它放在文件范围内,很明显。这没有回答问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 2013-12-14
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    相关资源
    最近更新 更多