【问题标题】:How structure in c can be assesed and input is given through pointer variable?如何评估 c 中的结构并通过指针变量给出输入?
【发布时间】:2019-10-29 16:19:43
【问题描述】:

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

再举一个例子:

#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;
}

如果“&”给出正确运行 如果不是,则显示分段错误

【问题讨论】:

    标签: c pointers data-structures struct malloc


    【解决方案1】:

    &amp;(ptr+i)-&gt;marks 等价于&amp;((ptr+i)-&gt;marks),即等价于&amp;(ptr[i].marks)
    也就是说,&amp;不适用于指针ptr,它适用于结构体ptr[i]的成员。
    marks 成员是int,所以需要传递一个指针。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-31
      • 2021-04-06
      • 2019-08-01
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多