简体   繁体   English

将指针转换为 C 中的二维字符数组

[英]Convert pointer to 2D char array in C

This probably has been asked already, but I'm unable to find anything on it.这可能已经被问过了,但我找不到任何东西。

I have a string array, where the numbers of strings in it is determined at runtime (the max string length is known, if that helps).我有一个字符串数组,其中的字符串数是在运行时确定的(如果有帮助,最大字符串长度是已知的)。 Since I need global access to that array, I used a pointer and malloc'ed enough space to it when I actually know how much has to fit in there:由于我需要对该数组进行全局访问,因此当我真正知道必须放入多少空间时,我使用了一个指针并为其分配了足够的空间:

char *global_strings;

void some_func(int strings_nr, int strings_size)
{
    global_strings = (char*) malloc(strings_nr* strings_size* sizeof(char));
}

What would be the correct way in C to use this pointer like a two-dimensional char array equivalent to global_strings[strings_nr][strings_size] ? C 中使用这个指针的正确方法是什么,就像一个二维字符数组一样,相当于global_strings[strings_nr][strings_size]

As a global pointer to 2D data, whose N*M characteristics defined at run-time, I'd recommend a helper function to access the strings rather than directly use it.作为指向 2D 数据的全局指针,其 N*M 特性在运行时定义,我建议使用帮助程序 function 来访问字符串,而不是直接使用它。 Make it inline or as a macro if desired.如果需要,使其inline或作为宏。

char *global_strings = NULL;
size_t global_strings_nr = 0;
size_t global_strings_size = 0;

// Allocation -  
// OK to call again, but prior data may not be organized well with a new string_size
// More code needed to handle that.
void some_func(int strings_nr, int strings_size) {
  global_strings_nr = strings_nr;      // save for later use
  global_strings_size = strings_size;  // save for later use
  global_strings = realloc(global_strings,
      sizeof *global_strings * strings_nr * strings_size);
  if (global_strings == NULL) {
    global_strings_nr = global_strings_size = 0;
  }
}

// Access function
char *global_strings_get(size_t index)  {
  if (index >= global_strings_nr) {
    return NULL;
  }
  return global_strings + index*global_strings_size;
}

#define GLOBAL_STRINGS_GET_WO_CHECK(index) \
   (global_strings + (index)*global_strings_size)

Better to use size_t for array indexing and sizing than int .size_t用于数组索引和大小调整比使用int更好。

Casts not needed.不需要演员表。

Memory calculations should begin with a size_t rather than int * int * size_t . Memory 计算应该以size_t而不是int * int * size_t开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM