Why can't we use double pointer to represent two dimensional arrays?

前端 未结 5 985
我在风中等你
我在风中等你 2020-11-22 02:23

Why can\'t we use double pointer to represent two dimensional arrays?

arr[2][5] = {\"hello\",\"hai\"};
**ptr = arr;

Here why doesn\'t the d

5条回答
  •  悲&欢浪女
    2020-11-22 03:15

    Making an array of pointers to each row in order to obtain an object that "looks like" a multidimensional array of variable size is an expensive design choice for the sake of syntactic sugar. Don't do it.

    The correct way to do a variable-sized multidimensional array is something like:

    if (w > SIZE_MAX/sizeof *m/h) goto error;
    m = malloc(w * h * sizeof *m);
    if (!m) goto error;
    ...
    m[y*w+x] = foo;
    

    If you want it to "look pretty" so you can write m[y][x], you should be using a different language, perhaps C++.

提交回复
热议问题