【发布时间】: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