gpt4 book ai didi

检查结构数组的 NULL

转载 作者:太空宇宙 更新时间:2023-11-04 05:27:39 26 4
gpt4 key购买 nike

struct student
{
int roll;
char *name;
};

int main()
{
int i;
struct student arr[2];
arr[0].roll = 12;
arr[1].name = "John";

arr[1].roll = 13;
arr[1].name = "Craig";

struct student *ptr;

ptr=arr;

// This is perfect.

for(i = 0; i<2; i++)
{
printf("%d %s", ptr->roll, ptr->name);
}

// This is also ok.
printf("%d %s", ptr->roll, ptr->name);

ptr++ // getting to next structure.

printf("%d %s", ptr->roll, ptr->name);

// But this isn't ok

while(*ptr || ptr->name != NULL)
{
ptr++;
}

return 0;
}

如何在while循环中检查指针?

最佳答案

ptr 指向一个数组,如果你递增它,ptr 开始指向一个非空的内存不足大小的数组。你可以这样做:

ptr = arr;
while (ptr < (arr + sizeof(arr)/sizeof(arr[0])) ){
ptr++;
}

注意:此技术不适用于动态数组。

要了解此公式的含义,请阅读:Weird behavior when printing array in C?

关于检查结构数组的 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18910690/

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