gpt4 book ai didi

c - 如何评估 c 中的结构并通过指针变量给出输入?

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

我正在尝试用指针实现结构。我遇到了一个大问题,我引入了一个结构指针变量并使用 malloc 分配了内存设指针变量为“ptr”,则ptr 将包含地址。那么为什么我们在 ptr 变量的形式中使用'&'。(scanf("%s %d", &(ptr+i)->主题, &(ptr+i)->标记);)

再举个例子:

#include <stdio.h>
#include <stdlib.h>

int main()
{
int n, i, *ptr, sum = 0;

printf("Enter number of elements: ");
scanf("%d", &n);

ptr = (int*) malloc(n * sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);
free(ptr);
return 0;
}

这里为什么我们不在 ptr 之前使用 '&' 来获取 ip??

澄清这两种情况?

我在使用结构时没有在 scanf 中使用“&”

struct course
{
int marks;
char subject[30];
};

int main()
{
struct course *ptr;
int i, noOfRecords;
printf("Enter number of records: ");
scanf("%d", &noOfRecords);

ptr = (struct course*) malloc (noOfRecords * sizeof(struct course));

for(i = 0; i < noOfRecords; ++i)
{
scanf("%s %d", &(ptr+i)->subject, &(ptr+i)->marks);
}

printf("Displaying Information:\n");

for(i = 0; i < noOfRecords ; ++i)
printf("%s\t%d\n", (ptr+i)->subject, (ptr+i)->marks);

return 0;
}

如果给定“&”运行正常如果不是,则显示段错误

最佳答案

&(ptr+i)->marks等价于&((ptr+i)->marks),相当于&( ptr[i].marks).
也就是说,&不适用于指针ptr,它适用于struct ptr[i]的成员。
marks成员是一个int,所以需要传递一个指针。

(ptr+i)->subject (ptr[i].subject) 前面的&不应该出现,因为它在传递给函数时已经转换为 char*

关于c - 如何评估 c 中的结构并通过指针变量给出输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56608152/

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