首页 > 解决方案 > 二维字符串数组获取一行中的列数,除法错误

问题描述

我这里有问题。我无法获得一行二维字符串数组中有多少个指针。错误说:

除法'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;
    }

标签: arrayscpointers

解决方案


这种方法适用于静态数组,但在动态数组上失败,因为您正在计算 '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

推荐阅读