gpt4 book ai didi

c - 通过指针访问结构数组

转载 作者:太空宇宙 更新时间:2023-11-04 03:05:19 24 4
gpt4 key购买 nike

这里我有一个结构定义:

typedef struct person {
unsigned int ssn, age, height, weight, income;
char name[MAXS+1], job[MAXS+1], religion[MAXS+1], major[MAXS+1], minor[MAXS+1], gender;
}PERSON;

这里我有一个函数内结构数组,类型为 PERSON 定义:

    PERSON record[MAXR+1];

我如何将此数组传递给另一个函数以进行实时更新(即作为指针)?

我的直觉和先验知识告诉我执行以下操作:

PERSON *rp[MAXR+1];
for(i=0; i<MAXR; i++){
*rp[i]=&record[i];
}
valid=readfile(fp, rp);

但是,我收到“赋值中不兼容的类型”错误。这样做的正确方法是什么?

完整代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAXS 19
#define MAXR 999

typedef struct person {
unsigned int ssn, age, height, weight, income;
char name[MAXS+1], job[MAXS+1], religion[MAXS+1], major[MAXS+1], minor[MAXS+1], gender;
}PERSON;


//get and check ssn
int getssn(){
int num;

printf("\nSSN: ");
scanf("%d", &num);

if(num<=99999999 || num>999999999){
printf("\nPlease input a valid SSN.\n");
return 0;
}
else
return num;
}

int readfile(FILE *fptr, PERSON **rptr){
int v=0, i, j;

for(i=0; i<MAXR; i++){
j=i;
if(fscanf(fptr, "%c\n%d\n%19s\n%d\n%19s\n%d\n%19s\n%19s\n%d\n%d\n%19s\n\n",
&rptr[j]->gender, &rptr[j]->ssn, rptr[j]->name, &rptr[j]->age,
rptr[j]->job, &rptr[j]->income, rptr[j]->major, rptr[j]->minor,
&rptr[j]->height, &rptr[j]->weight, rptr[j]->religion)==EOF)
i=MAXR;
if(&rptr[MAXR]->ssn==&rptr[j]->ssn)
v=j;
}


return v;
}

int main(){
int valid=0, i;
char filename[MAXS]="clients.txt";
FILE *fp;
PERSON record[MAXR+1], *rp[MAXR+1];

do{
record[MAXR].ssn=getssn();
}while(record[MAXR].ssn==0);

printf("Name of file of records: ");
//gets(filename);

if((fp=fopen(filename, "r"))==NULL)
printf("\nCould not open file\n");
else{
printf("\njur doing gohd\n");
for(i=0; i<MAXR; i++){
*rp[i]=&record[i];
}
valid=readfile(fp, rp);
if(valid==0){
printf("\nSSN %d is not found in file %s.\n", record[MAXR].ssn, filename);
}
else {
printf("%d", valid);
}
}



return 0;
}

最佳答案

您正在尝试将 PERSON 变量的地址分配给实际的 PERSON 变量(不是地址),您可能打算这样做:

rp[i]=&record[i];

请注意,它将复制指向结构的指针,而不是结构本身。如果要复制结构,需要使用memcpymemmove

关于c - 通过指针访问结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6097892/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com