这个阵列大小是如何产生的?

时间:2018-04-04 09:38:11

标签: c arrays multidimensional-array size

我已经设法生成了一个完全正常的代码并完全按照它应该做的。我的问题是:我完全不明白为什么。根据我的理解,它应该不起作用。

public class A {

   private int              id;
   private static Point2D[] myArray = new Point2D[10];

   public A(int id) {
      this.id = id;
      if (myArray[0] == null) { // I want the array to be initialized only once.
         initArray(id);
      }
   }

   private static void initArray(int id) {
      for (int i = 0; i < myArray.length; i++) {
         myArray[i] = new Point2D(id, id);
      }
   }

}

我可以发誓我必须在memcpy中指定#define PARAMS 12 char** parseFile(char* tmp[], char* location) { // Parse a file at <location> and retrieve 6 key: value pairs from it. // All key: value pairs are stored in tmp, resulting in an array of // 12 char pointers, each pointing to a char array that contains either // a key or a value. // ... do { yaml_parser_scan(&parser, &token); if (token.type == YAML_SCALAR_TOKEN && i<PARAMS) { strcpy(tmp[i], (char*)token.data.scalar.value); i++; } if (token.type != YAML_STREAM_END_TOKEN) { yaml_token_delete(&token); } } while (token.type != YAML_STREAM_END_TOKEN); // ... return tmp; } int main(int argc, char* argv[]) { int i=0; char **tmp = (char **)calloc(PARAMS, sizeof(char *)); char **params = (char **)calloc(PARAMS, sizeof(char *)); for (i=0; i<PARAMS; i++) { tmp[i] = (char *)calloc(32, sizeof(char)); params[i] = (char *)calloc(32, sizeof(char)); } memcpy(params, parseFile(tmp, argv[1]), sizeof(char) * 56); // WHY 56? for (i=0; i<PARAMS; i++) { printf("PARAM_[%d] = %s\n", i, params[i]); } free(tmp); free(params); return 0; } (1 * 12 * 32)的大小才能使代码生效。但如果我这样做,那就没有。如果我指定sizeof(char) * 384,它只能工作并产生正确的结果。为什么56?这个价值应该是什么意思?我确实知道我有6个键:值对,而6 * 8 + 8是56,但我仍然没有得到它。

[编辑]

用例是这样的:

程序根据yaml配置文件中提供的连接参数(IP地址,端口)连接到服务器。该文件的简约版本可能如下所示:

sizeof(char) * 56

程序需要key:value对的值,因为它们被传递给与服务器建立连接的函数。所以,我需要做的是解析配置文件并查找允许的键(参数可以是任何东西;我只知道键)。例如,如果找到密钥“tx_addr”,程序就知道该密钥的值应作为建立服务器连接的函数的IP地址参数传递。

1 个答案:

答案 0 :(得分:1)

我认为您的目标是将所有关键:值对从tmp复制到params

您无法使用单个tmpparams的所有键:值对复制到memcpy。您无法确定malloc已经为您提供了两个连续的内存区域。

您必须逐个复制字符串。

parseFile(tmp, argv[1]);
for (i=0; i<PARAMS; i++) {
    memcpy(params[i], tmp[i], 32);
}

为了获得两个连续的内存区域(以便您可以使用单个memcpy进行复制),您需要将变量分配为2D数组(https://stackoverflow.com/a/40847465/4386427https://stackoverflow.com/a/42094467/4386427)。

相关问题