C 使用指针的输出结构没有变化
我试图学习数据结构的基本步骤,最近在执行一个程序后遇到了一个问题 我试图调用“按值调用函数”和“按引用调用函数”(在[]的注释中标记为1和2)C 使用指针的输出结构没有变化,c,data-structures,C,Data Structures,我试图学习数据结构的基本步骤,最近在执行一个程序后遇到了一个问题 我试图调用“按值调用函数”和“按引用调用函数”(在[]的注释中标记为1和2) #包括 #包括 结构日期 { 未签名整数年; 未签名字符月[30]; }; 结构出席 { 未签名字符名[30]; 长无符号整数记录\u编号; 双倍时间; 结构日期d; }stu1; 结构考勤变更(结构考勤stu); 作废显示(结构考勤); // 您的change\u ptr函数不会返回任何内容,即使它被声明为返回struct attention,因此结果
#包括
#包括
结构日期
{
未签名整数年;
未签名字符月[30];
};
结构出席
{
未签名字符名[30];
长无符号整数记录\u编号;
双倍时间;
结构日期d;
}stu1;
结构考勤变更(结构考勤stu);
作废显示(结构考勤);
// 您的change\u ptr
函数不会返回任何内容,即使它被声明为返回struct attention
,因此结果未定义
此外,将指针传递到函数并返回它以及副本也没有什么意义,但这不是您的问题
由于您已经传递了指针,您可以将其声明为无效并仍然打印修改的内容。change\u ptr
:没有返回值的代码。按引用/值传递的概念是错误的。如果change
函数是void
函数,则只有传递指针的函数才会更新amin
中的结构。但是如果你返回结构,当然,main
中的结构会被更新。我很困惑..对不起,数据结构是新的,特别是指针,它们非常令人头痛。如果你不介意的话,你能给我举个例子吗。我已经将函数改为>>void change_ptr(struct attention*p);并使用change_ptr(&stu2)调用该函数;但我仍然得到相同的输出没有改变请更新代码到当前版本。在没有看到发生什么的情况下,很难知道还有什么问题。Devolus我已经按照您的建议更改了代码,编辑了上面的代码,在注释中显示“编辑”。
#include<stdio.h>
#include<string.h>
struct date
{
unsigned int year;
unsigned char month[30];
};
struct attendance
{
unsigned char name[30];
long unsigned int record_no;
double time;
struct date d;
}stu1;
struct attendance change(struct attendance stu);
void display(struct attendance);
//<< declaring function using pointer structure [1]
void change_ptr(struct attendance *); //<<edit
int main()
{
char ch;
char buff[100];
struct attendance stu2;
printf("enter the name: \t record.no \t and time \n");
scanf("%s%lu%lf",stu1.name,&stu1.record_no,&stu1.time);
printf("\n");
stu2=stu1; //copied contents of structure 1 to 2
stu1=change(stu1);
display(stu1);
printf("\n");
printf("change using a pointer \n");
printf("\n");
change_ptr(&stu2); //<<function called <<edit
display(stu2); //no change in output ???
getch();
}
struct attendance change(struct attendance stu) //function by value
{
char tr[30]="good day ";
char fp[50];
stu.record_no +=1000;
strcpy(fp,stu.name);
strcpy(stu.name,tr);
strcat(stu.name,fp);
stu.time-=70.30;
return stu;
}
void display(struct attendance stu)
{
printf("%s \n record.no = %lu \t time = %lf \n",stu1.name,stu1.record_no,stu1.time);
}
//facing problem here;;
void change_ptr(struct attendance *p)// <<pointer function [2]
{
strcat(p->name," welcome ");
p->record_no+=5000;
p->time-=2000;
};