我有以下代码

#include <stdio.h>
#include <string.h>

int main()
{
  char a[10000] = "aaaaaaaa"; // this attribute may vary, so the length isn't going to be constant
  int aLength = strlen(a);
  int someParameter = aLength /4; // some attribute that's computed dynamically

  char table[aLength][someParameter];
}

在表声明中,我得到错误->“表达式必须有一个常量值”。我怎么能克服这个?

最佳答案

创建table作为矩阵,您可以使用malloc设置其大小:

#include <stdio.h>
#include <string.h>

int main()
{
  char a[10000] = "aaaaaaaa"; // this attribute may vary, so the length isn't going to be constant
  int aLength = strlen(a);
  int someParameter = aLength /4; // some attribute that's computed dynamically
  char **table;

  // Allocate aLength arrays of someParameter chars
  table  = malloc(aLength * sizeof(*table));
  for(i = 0; i < aLength; i++)
     table[i] = malloc(someParameter * sizeof(*table[i]));
}

一般来说,要使用可变大小的数组,可以使用malloc
// For example, allocate n chars
char *str  = malloc(length * sizeof(*str));

关于c - C中的动态数组大小,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18867801/

10-13 08:20