我对C语言非常陌生,我刚刚开始学习.如果这个问题看起来有点愚蠢,我很抱歉.

有没有人能解释一下为什么这个不起作用?有什么办法可以完成这样的事情吗? 非常感谢!

struct test{
    int arr[10];
};

void foo(struct test t){
    t.arr[0] = 1;
}

int main() {
    struct test t = {malloc(10*sizeof(int))};
    foo(t);
    printf("%d", t.arr[0]);
}

我不确定为什么t.arr[0]没有分配给1.

推荐答案

您需要将指向 struct 的指针传递给函数foo()以允许foo()更新 struct t.我已经在不同的地方用注释更新了您的代码.还请注意, struct t不需要Malloc(),因为它的声明方式...操作系统将为该 struct 预留堆栈空间.如果您只声明了一个 struct 类型的指针,那么是的,您将需要Malloc().

可运行代码可用here.

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

struct test{
    int arr[10];
};

void foo(struct test *t){  /* updated: pointer of type struct t */
    t->arr[0] = 1;      /* updated. Access pointer struct members like this ( -> ) -- not the dot syntax */
}

int main() {
    struct test t;  /*updated -- this declaration already allocates space for the array in t -- see output from printf() */
    foo(&t);    /* updated -- foo() needs a pointer to the struct.  So we pass the address of t (&t) */
    printf("t.arr[0] = %d\nsizeof(t) = %d\n", t.arr[0], sizeof(t));
}

输出:

t.arr[0] = 1  /* It works! */
sizeof(t) = 40  /* See?  40 bytes allocated already (on my platform). */

C++相关问答推荐

POSIX文件描述符位置

堆栈帧和值指针

难以理解Makefile隐含规则

ARM64 ASIMD固有的加载uint8_t* 到uint16x8(x3)?

C lang:当我try 将3个或更多元素写入数组时,出现总线错误

在创建动态泛型数组时,通过realloc对故障进行分段

在Linux上使用vscode和lldb调试用Makefile编译的c代码

C中的FREE函数正在触发断点

在C中包装两个数组?

GCC错误,共享内存未定义引用?

生产者消费者计数器意外输出的C代码

当用C打印过多的';\n';时输出不正确

如何找出C中分配在堆上的数组的大小?

Struct 内的数组赋值

std::malloc/calloc/realloc/free 与纯 C 的 malloc/calloc/realloc/free 有什么不同

尽管将其标记为易失性,但 gcc 是否优化了我的等待代码?

将数组返回到链表

为什么需要struct in_addr

比 * 更快的乘法

当循环变量在溢出时未定义时,可以进行哪些优化?