嗨朋友们,因为我是 C 的新手,我努力练习以理解 C 中的所有 nitygrity 事物。在尝试结构时,我设法编写了一段代码,我试图通过值和引用将结构传递给函数。但是我认为我做错了什么...请帮助朋友...如果你们能指导我获得有关结构的适当深入教程,那将是一个很大的帮助...谢谢
#include <stdio.h>
#include <stdlib.h>
struct foo{
char arr[200];
int x_val;
int y_val;
float result;
};
struct foo my_foo;
int foo_fun(struct foo var); //proto declearation
int foo_fun1(struct foo *var1); //proto declearation
int main()
{
//As I was not getting prover string printed by using function foo_fun1
// I have tried to print directrly calling another ptr here
int i = 0;
struct foo *ptr;
ptr = (struct foo *)malloc(sizeof(struct foo)*10);
ptr->arr[0] = "calculator";
printf("Ptr zero contains a string %s\n",ptr->arr[0]); //even here prints wrong value
i = foo_fun(my_foo);
printf("Result from foo_fun is %d\n",i);
//Expecting this function to print string ....but getting some unexpected result
foo_fun1(&my_foo);
system("pause");
return 0;
}
// pass by value
int foo_fun(struct foo var)
{
int i;
int total = 0;
for(i=0;i<sizeof(var.arr); i++)
{ var.arr[i] = i;
total = total+var.arr[i];
}
var.x_val = 230;
var.y_val = 120;
return total;
}
// pass by reference
int foo_fun1(struct foo *var1)
{
int i = 0;
var1 = (struct foo *)malloc(sizeof(struct foo)*20);
var1->arr[0] = "A";
printf("%s\n",var1->arr);
return 0;
}