arrays - 二维字符串数组获取一行中的列数,除法错误
问题描述
我这里有问题。我无法获得一行二维字符串数组中有多少个指针。错误说:
除法'sizeof(char **)/ sizeof(char *)'不计算数组元素的数量[-Werror=sizeof-pointer-div]
我知道我们需要做什么才能得到这个数字,但不知何故我无法划分字节:/。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char ***array;
array = malloc(1* sizeof(char**));
array[0] = malloc(5 * sizeof(char*));
size_t size = sizeof array[0] / sizeof(char*); //error
printf("%lu\n", size);
return 0;
}
解决方案
这种方法适用于静态数组,但在动态数组上失败,因为您正在计算 'sizeof (*array) / sizeof(*char) // 8 / 8` 将始终为 1。
我建议定义尺寸并相应地使用它们
#define MAX_HEIGHT 10
#define MAX_WIDTH 10
...
array = malloc(MAX_HEIGHT * sizeof(char**));
// do not forget to test the malloc result
if (!array) // do something
for (int i = 0; i < MAX_HEIGHT; i++){
array[i] = malloc(MAX_WIDTH * sizeof(char*));
if (!array[i]) // do something
}
height = MAX_HEIGHT;
width = MAX_WIDTH;
// from here you can allocate the strings and run some code with the base size
推荐阅读
- python - 来自 __init__.py 的 Usign 函数
- firebase - 如何获取文档,按照文档 ID 存储在某个变量列表/数组中的顺序,在云 Firestore Firebase 中?
- c++ - 我怎样才能拥有一个可以通过不同命名空间中的定义参数化数据成员的类?
- java - 如何获得 Gradle 工件转换的输出?
- javascript - 带有 :after 的按钮不使用 JavaScript 文件中的事件处理程序
- python - 编写一个不带括号的列表的字典值
- java - Java:如何等待监听器执行下一行?
- dll - cc_import 用于调试和发布版本?
- javascript - 有没有办法从 Skyscanner API 中的 DestinationID 获取机场/城市名称?
- .net - 使 Infragistics Ultragrid 看起来“已禁用”