小编use*_*359的帖子

将指针传递给结构数组时出错

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

struct Point {
    double x;
};

void test(struct Point **a, int len)
{
    int i;

    printf("a = %p\n", a);
    for (i = 0; i < len; ++i)
        printf("%f\n", a[i]->x);
}

int main()
{
    int i;
    int len = 4;

    struct Point *P;

    P = malloc(len*sizeof(struct Point));

    for (i = 0; i < len; ++i) {
        P[i].x = i;
        printf("%f\n", P[i].x);
    }
    printf("&P = %p\n", &P);
    test(&P, len);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我试图将一个结构数组传递给一个函数(我想传递一个指向数组的指针,而不是复制).当我尝试在函数内部使用数组时,我遇到了访问冲突.这样做的正确方法是什么?我究竟做错了什么?a == &P,所以它应该工作,对吗?

c arrays struct pointers function

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

可以在C中返回并释放动态分配的数组吗?

是否可以返回并释放动态分配的数组?

int *mycopy(int *from, int len)
{
    int i;
    int *to;

    to = malloc(len*sizeof(int));

    for(i = 0; i < len; ++i) {
        to[i] = from[i]
    }

    return to;

    // how do I free the "to" array?
    // do i even need to, or does the array only have function scope
    // and get deleted when the function exits?
}
Run Code Online (Sandbox Code Playgroud)

或者是

void mycopy(int *from, int *to, int len);
Run Code Online (Sandbox Code Playgroud)

我唯一的选择?

mycopy函数只是一个简单的例子,但在实际代码中我想嵌套它们,比如调用它

a = mycopy(mycopy(b, 5), 5)
Run Code Online (Sandbox Code Playgroud)

每次调用函数时如何在不分配更多内存的情况下执行此操作?谢谢.

c malloc function dynamic-arrays

4
推荐指数
2
解决办法
1469
查看次数

为什么在创建结构时需要地址运算符 (&amp;)?

我有一些有效的代码,但我不明白为什么。这是有问题的代码:

struct SceneInterface *TitleAsScene = &(struct SceneInterface) {
    .update = (void (*)(void *)) title_update,
    .render = (void (*)(void *)) title_render,
};
Run Code Online (Sandbox Code Playgroud)

我得到了函数指针和指定的初始值设定项,但是&(struct SceneInterface)部分在做什么?通常它表示address of,但是括号中的东西是一个类型,而不是一个变量,那么它指向的是什么?如果它返回一个指向 struct SceneInterface 的指针,那么左侧已经是那个,所以我不明白为什么需要它,以及为什么如果我删除它会出现分段错误。

这是完整的工作代码供参考:

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

struct SceneInterface {
    void (*update)(void *instance);
    void (*render)(void *instance);
};

struct Scene {
    void *instance;
    const struct SceneInterface *interface;
};

struct Scene *scene_create(void *instance, struct SceneInterface *interface)
{
    struct Scene *scene = (struct Scene *) malloc(sizeof(struct Scene));
    scene->instance = instance;
    scene->interface = interface;

    return …
Run Code Online (Sandbox Code Playgroud)

c struct pointers reference designated-initializer

3
推荐指数
1
解决办法
43
查看次数