相关疑难解决方法(0)

我是否施放了malloc的结果?

这个问题,有人建议意见,我应该不会投的结果malloc,即

int *sieve = malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)

而不是:

int *sieve = (int *) malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)

为什么会这样呢?

c malloc casting

2318
推荐指数
27
解决办法
22万
查看次数

使用和解除引用(void**)

我想传递一个指向函数的"多态"数组.

我可以在没有警告的情况下做以下事情:

foo (void* ptr);

bar()
{
  int* x;
  ...
  foo(x);
}
Run Code Online (Sandbox Code Playgroud)

gcc显然会自动转换x为a (void*),这只是花花公子.

但是,当我执行以下操作时,我会收到警告:

foo (void** ptr);

bar()
{
  int** x; // an array of pointers to int arrays
  ...
  foo(x);
}

note: expected ‘void **’ but argument is of type ‘int **’
warning: passing argument 1 of ‘foo’ from incompatible pointer type [enabled by default]
Run Code Online (Sandbox Code Playgroud)

我的问题是:为什么一个传递(int*)(void*)参数不是"不兼容",但(int**)作为一个(void**)论据是什么?

由于所有指针类型都是相同的大小(对吗?因为我使用了C已经有一段时间了),我仍然可以做类似的事情:

void mainFunc1(int** arr, int len)
{
    //goal is to apply …
Run Code Online (Sandbox Code Playgroud)

c pointers void-pointers pointer-to-array

8
推荐指数
1
解决办法
3928
查看次数

C可变函数与Fortran的互操作性

有没有办法声明一个C variadic函数并从Fortran调用它?我需要调用此函数来计算用字符串标记的向量之间的一些点积.我的想法是声明类似下面的内容,其中变量参数列表包含字符串文字.如果变量参数列表为空,那么我将在标准标签之间进行查找并执行计算.如果用户指定了两个标签,我会检索这两个向量并得到它们的点积:

extern "C" void compute_dot_product(double * dot_product, ...)
{
    va_list args;
    va_start(args, NULL);
    char * label1 = va_arg(args, char *);
    if (!label1)
    {
       // Do standard label lookup and compute dot product
    }
    else
    {
       // Compute dot product between the vectors with the specified labels
       char * label2 = va_arg(args, char *);
    }
    va_end(args);
}
Run Code Online (Sandbox Code Playgroud)

唯一的问题是我可以编译我的C库并将其链接到Fortran可执行文件,但是当我尝试访问变量参数列表时,我收到运行时错误.知道我想做什么是可能的吗?一个可能的解决方案是分成两个函数:一个执行标准标签查找(0参数情况),另一个执行非标准标签查找(2参数情况).我宁愿避免这个解决方案.

c fortran fortran90 fortran-iso-c-binding

7
推荐指数
1
解决办法
450
查看次数