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

标签 c pointers data-structures struct malloc

我正在尝试用指针实现结构。我遇到了一个大问题,我引入了一个结构指针变量并使用 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/

相关文章:

javascript - 对形状进行分组和取消分组的最佳数据结构是什么

C - 创建一个字符串 "from"结构参数

c++ - 使用 C 预处理器确定编译环境

c - 为什么使用这样的定义?

c - 将新节点添加到我的链表堆栈中会将所有旧节点更新为新节点

c - 熟悉指针吗?

java - 这种类型的数据格式应使用什么类型的数据结构?

java - 修改其副本时保持原始 Vector 完整

c - 无明显原因增加++ 值的无符号整型变量

c - 如何在 c 中打印结构成员的值(使用指向结构的指针)