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: �