Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 将数组作为参数传递并分配内存_C_Pointers_Malloc - Fatal编程技术网

C 将数组作为参数传递并分配内存

C 将数组作为参数传递并分配内存,c,pointers,malloc,C,Pointers,Malloc,请找个人帮我做这件事 #include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct{ int id; char nama[50]; } test_t; void test(int* count, test_t* t){ (*count) = 5; t = (test_t*)malloc(sizeof(*t)*5); for(int

请找个人帮我做这件事

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

typedef struct{
    int id;
    char nama[50];
} test_t;

void test(int* count, test_t* t){
    (*count) = 5;
    t = (test_t*)malloc(sizeof(*t)*5);
    for(int i=0;i<5;i++){
        t[i].id = i;
        strcpy(t[i].nama, "test");
        printf("id: %i\nnama: %s\n", t[i].id, t[i].nama);
    }


 printf("t size: %lu\n", sizeof(t));
}

int main(int argc, char** argv){
    int a = 1;
    test_t* item;
    test(&a, item);
    for(int i=0;i<a;i++){
        printf("id: %i\nnama: %s\n", item[i].id, item[i].nama);
    }
    return 0;
}

参数将值传递给函数。他们什么也不传回去。要将值传递回调用方,必须将其作为函数的返回值返回,或者将其放置在调用方可以看到的位置。(例如参数指向的位置,但此处不需要。)参数是按值传递的,因此,如果在
test()
中为
t
赋值,调用函数将看不到这一点。为什么不直接返回
t
?这是一个常见问题;这是许多问题的重复。困难在于找到一个很好的参考副本。您在编写代码时没有理解。你和自己冲突。请参见
测试(&a,项目)
。对于第一种情况,您传递了要修改的变量的地址,为什么不传递第二种情况?非常感谢您的帮助。。。
id: 0
nama: test
id: 1
nama: test
id: 2
nama: test
id: 3
nama: test
id: 4
nama: test
t size: 8
id: 1
nama: 
id: -767851619
nama: �
id: -767851396
nama: �
id: -767849773
nama: �
id: -767849398
nama: �