相关疑难解决方法(0)

在C中通过引用传递数组?

如何在C中通过引用传递一组结构?

举个例子:

struct Coordinate {
   int X;
   int Y;
};
SomeMethod(Coordinate *Coordinates[]){
   //Do Something with the array
}
int main(){ 
   Coordinate Coordinates[10];
   SomeMethod(&Coordinates);
}
Run Code Online (Sandbox Code Playgroud)

c arrays pass-by-reference

64
推荐指数
6
解决办法
22万
查看次数

正确分配多维数组

这个问题的目的是提供一个关于如何在C中动态正确分配多维数组的参考.这是一个经常被误解的主题,即使在一些C编程书籍中也很难解释.因此,即使是经验丰富的C程序员也很难做到正确.


我从编程教师/书籍/教程中了解到,动态分配多维数组的正确方法是使用指针指针.

然而,SO上的几个高代表用户现在告诉我这是错误和不好的做法.他们说指针到指针不是数组,我实际上并没有分配数组,而且我的代码不必要地慢.

这就是我教我分配多维数组的方法:

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

int** arr_alloc (size_t x, size_t y)
{
  int** pp = malloc(sizeof(*pp) * x);
  assert(pp != NULL);
  for(size_t i=0; i<x; i++)
  {
    pp[i] = malloc(sizeof(**pp) * y);
    assert(pp[i] != NULL);
  }

  return pp;
}

int** arr_fill (int** pp, size_t x, size_t y)
{
  for(size_t i=0; i<x; i++)
  {
    for(size_t j=0; j<y; j++)
    {
      pp[i][j] = (int)j + 1;
    }
  }

  return pp;
}

void arr_print (int** pp, size_t x, size_t y) …
Run Code Online (Sandbox Code Playgroud)

c arrays dynamic-arrays dynamic-allocation variable-length-array

51
推荐指数
1
解决办法
4882
查看次数

我们在 C 中可以拥有的指向指针的指针数量的限制是多少?

在 C 中,我知道我们可以用指针来做到这一点:

int *p;          /* an int pointer (ptr to an int) */
int **pp;        /* a pointer to an int pointer (ptr to a ptr to an int) */
Run Code Online (Sandbox Code Playgroud)

乃至:

int **app[];            /* an array of pointers to int pointers */
int (**ppa)[];          /* a pointer to a pointer to an array of ints */
int (**ppf)();          /* a pointer to a pointer to a function returning an int */
int *(*pap)[];          /* a pointer to an array …
Run Code Online (Sandbox Code Playgroud)

c pointers limit language-lawyer

8
推荐指数
2
解决办法
279
查看次数