1、首先在电脑中打开visual studio新建项目,给这个结构体取个名字叫student。
2、然后添加变量,如下图所示。
3、然后给结构体类型指针p申请堆空间,如下图所示。
4、接着使用for循环给结构体赋值,如下图所示。
5、最后在通过for循环打印输出,这样就完成就结构体的基本创建,结尾不要忘了使用free(p):释放申请的堆空间。
直接把结构体变量传递参数是传值,
st *fun(struct st x)
这里的形参x其实是传递的实参y的拷贝,这和形参不能影响实参是同样的道理。而且x在fun函数结束后就被系统回收了,取得的地址当然就成野指针了,所以应该用结构体指针传递参数:
#include "stdio.h"#include "string.h"
struct st
{
int a
char b[10]
}
void fun(struct st *px)
{
px->a = 100
strcpy(px->b,"99999")
}
int main()
{
struct st y, *p
p = &y
y.a = 999
strcpy(y.b,"0")
printf("y.a=%d y.b=%s\n",y.a,y.b)
fun(p)
printf("(*p).a=%d (*p).b=%s\n",(*p).a,(*p).b)
}
#include<stdio.h>#include<string.h>
#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std
typedef struct point{ //结构体设计
int A, B, C, a, b, c, id, n
}point
point *ReadFile(){
static point ss[110]
char data[50] = {'\0'}
int m1 = 0, n = 0, k, i
for(int i = 0 i < 100 i++){
ss[i].id=rand()%10
ss[i].A=rand()%10
ss[i].B=rand()%10
ss[i].C=rand()%10
ss[i].D=rand()%10
ss[i].E=rand()%10
ss[i].F=rand()%10
}
return ss
}
void main(){
point male[110], female[110], players[110]
male = ReadFile()
}
ss是局部变量,有效范围只局限于定义ss的函数体内,即只在函数ReadFile里有效,函数返回后,ss就失效了。
你可以在ReadFile里定义ss的前面加上static修饰,表示这个是静态局部变量,静态局部变量的内存有效范围可以全局有效。
static point ss[110]
另外,结构体的typedef定义不完整。