在C语言中。结构体变量之间可以相互赋值吗?

Python017

在C语言中。结构体变量之间可以相互赋值吗?,第1张

可以直接赋值。定义结构体类型,然后用这个类型定义出来的变量就是结构体变量。

C语言在相同类型的变量间赋值时是直接内存复制的,即将他们的内存进行复制,这里因为同样结构体变量,属于同一种变量,所以赋值时是按照他们的内存分布来直接拷贝的。

举例:

voidmain()

STUstu1={0,10};

STUtemp={12,88};

STU*p1=&stu1;

STU*p2=&temp;

printf("%d-%d\n",temp.name,temp.num);

temp=stu1;

printf("%d-%d\n",temp.name,temp.num);

temp={10,10};

printf("%d-%d\n",stu1->name,stu1->num);

printf("%ld-\n",&stu1);

printf("%ld-\n",stu1);

printf("%ld-\n",&temp);

printf("%ld-\n",temp);

change(stu1,temp);

temp=stu1;

p2=p1;

printf("%d-%d\n",p2->name,p2->num);

扩展资料:

C语言中变量间互相赋值很常见,例如:

inta,b;

a=b;

结构体也是变量(自定义变量),两个结构体之间直接赋值按道理应该也是可以的吧,将一个结构体对象赋值给另一个结构体对象的。

例:

#include"stdio.h"

structtest

inta;

intb;

intc;

char*d;

};

intmain()

structtestt1={1,2,3,"tangquan"};

structtestt2={0,0,0,""};

printf("%d,%d,%d,%s\r\n",t2.a,t2.b,t2.c,t2.d);

t2=t1;

printf("%d,%d,%d,%s\r\n",t2.a,t2.b,t2.c,t2.d);

return0;

intmain(void){

structstudentsbao={}

printf("%d,%s\n",bao.id,bao.name)//输出是4224528,空(应该是null)

//structstudentsbao={3,"123"}可以。第一种赋值方法

//strcpy(bao.name,"bao")//可以,

//printf("%d,%s\n",bao.id,bao.name)

//bao.name="bao"错误“stray'\351'inprogram”其他是乱码,

//bao.name[0]='a'

//bao.name[0]='/0'

//printf("%d,%s\n",bao.id,bao.name)

/*这样可以,*/

//chararr[10]="baobao"

////bao.name=arr//error"assignmenttoexpressionwitharraytype"

//scanf("%s",bao.name)//可以,

//printf("%d,%s\n",bao.id,bao.name)

//所以scanf那一类函数都可以。

//还有就是memcpy函数也是可以的

return0

}

扩展资料

C语言结构体数组的直接赋值及数组的长度计算:

#include<stdio.h>

//自定义一个字符串的结构体,包含字符串和字符串长度两个变量

typedefstructStr{

charch[100]

intlength//char数组(字符串)的长度

}myStr

//刚开始声明变量时每个变量的字符串长度length都为0

//这里以长度为10的数组为例,数组长度是1000

//对第0个到第9个结构体数组的长度同时赋值为0

myStrmyStr1[10]={

[0...9]={

.length=0,

}

}

intmain(){

inti

for(i=0i<10i++){

printf("%d\n",myStr1[i].length)

}

return0

}