如何在C语言中初始化并保存数据到二维数组?

问题描述 投票:0回答:1

如果我有一个有多个c字符串的二维数组,在不知道有多少c字符串将被添加到数组中的情况下,我将如何初始化数组。

我试着像下面这样初始化,但是当我尝试添加一个c字符串时,我在编译时得到了一个错误.Error : explicit dimensions specification or initializer for an auto or static array.

static Char data[][100]; 

int main(){
  int i;
  char word[5];

  strcpy(word,"data");

  For(i=0; i < rows; i++){
    strcpy(data[i],word);
  }

}

因此,数组应该包含以下内容

data[][100]= {"data","data"};

行值取决于从sql中检索到多少行,所以我的问题是,我想以某种方式动态地创建数组,以适应从sql中检索到的行的大小。

任何帮助或信息将是巨大的。

c multidimensional-array proc
1个回答
0
投票

你可以使用指向数组的指针和重新分配。

#include <stdlib.h> /* for realloc() */
#include <string.h> /* for strcpy() */

int rows = 100; /* for example */

static char (*data)[100] = NULL;

int main(){
  int i;
  char word[100]; /* allocate array, not a single char */

  strcpy(word,"data");

  for(i=0; i < rows; i++){
    char (*newData)[100] = realloc(data, sizeof(*data) * (i + 1));
    if (newData == NULL) { /* allocation error */
      free(data);
      return 1;
    }
    data = newData;
    strcpy(data[i],word);
  }

}

0
投票

如果你事先不知道会有多少个字符串,你要么给数组设置一个固定的最大限制,要么给数组设置一个固定的最大限制。static 数组,或者使用动态分配一个数组的 char 指针。

当使用动态分配时,您可以 malloc 一开始是一个 "相当大的数字",记住有多少个字符串,然后是 realloc 当你的空间用完的时候。

EDIT: 没有错误处理、free()等的伪代码示例。

int main (void)
{
  size_t alloc_size = sizeof(char*[100]);
  char** data = malloc(alloc_size); 

  for(size_t i=0; i<rows; i++){
    if(i > alloc_size)
    {
      alloc_size *= 2;
      data = realloc(data, alloc_size);
    }

    size_t str_size = strlen(input)+1;
    data[i] = malloc(str_size);
    memcpy(data[i], input, str_size);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.