【发布时间】:2014-09-27 10:25:04
【问题描述】:
` 结构 mylist_in{ int 注册号; 字符串名称; 年龄; 字符串地址; mylist_in *下一个; }; 结构 mylist_out{ 诠释; }; 节目记录{ 版本 REC_VER{ mylist_out recdis(mylist_in) = 1; } = 1; } = 0x31240000;
#include "student.h"
#include <string.h>
#include <malloc.h>
int main(int argc, char **argv)
{
CLIENT *c1;
char name,address;
c1 = clnt_create(argv[1],RECORD,REC_VER,"tcp");
int n,i,j,k;
printf("Enter the no. of records to store\n");
scanf("%d",&n);
mylist_in data[n+1];
mylist_out *result;
printf("Enter the details.\n");
for(i=0;i<n;i++)
{
printf("Enter space separated enrollment_no, name, age, address.\n");
scanf("%d %s %d %s",&data[i].enrollment_no,&name,&data[i].age,&address);
data[i].name = name;
data[i].address = address;
}
for(j=0;j<n-1;j++)
{
data[j].next = &data[j+1];
}
data[n-1].next = NULL;
if((result = recdis_1(&data[0],c1))==NULL)
{
printf("Error\n");
return(0);
}
printf("%d records written to the file\n",result->res);
exit(0);
}
#include "student.h"
#include <stdio.h>
mylist_out*
recdis_1_svc(mylist_in *inp, struct svc_req *rqstp)
{
printf("Start \n");
static mylist_out out;
int k=0;
FILE *f = fopen("record.txt", "w");
if (f == NULL)
{
out.res = -1;
exit(1);
}
out.res = 0;
;
while (inp != NULL)
{
fprintf(f, "RECORD # %d\nenr_no = %d, name = %s, age = %d, address = %s \n",k+1,inp>enrollment_no,inp->name,inp->age,inp->address);
k++;
inp = inp->next;
}
out.res = k;
fclose(f);
return(&out);
}
`我有一个 char 数组 name,我使用 c 中的 scanf() 函数将一些值存储在 for 循环中。有一个 struct 包含一些元素以及一个字符指针 data.name。现在,当我尝试将 name 的值存储在结构的不同元素的 data.name 字段中并且在执行循环之后,当我尝试打印data.name 一个一个,它们都给出相同的值,即 name 中取的最后一个值。我猜是因为所有数据元素都指向 name 变量,并且在 scanf() 操作期间值会覆盖。有人可以帮我解决这个问题吗?
【问题讨论】:
-
可以分享一下有问题的代码吗?
-
.. 那样会很方便
-
任何代码来代表你的长文本?
-
记住:我们无法从这里看到您的屏幕!所以请发布您的代码!
-
@Rahul 不要发表评论。使用此评论编辑您的问题。