如何检查结构中的变量是否未在 C 中使用?
How can I check if a variable in a struct is not used in C?
这是我目前的代码。
我试图判断结构中的某个变量是否为空。我将创建一个结构,其中一些变量被填充,一些变量不需要,并且需要知道哪些需要我做某事,哪些不需要。
#include <stdio.h>
#include <stdlib.h>
struct nums {
int a;
int b;
int c;
int d;
} typedef numbers;
int main() {
numbers bob;
bob.a = 69;
if (bob.b == NULL) {
printf("no number stored in b");
}
return 0;
}
但我刚收到错误
warning: comparison between pointer and integer
有什么想法吗?
通常无法判断您是否确实在 int
变量中存储了一些内容。
不过,对于您的情况,您可以:
- 初始化你的结构:
numbers bob = { 0 }; // <-- this makes a, b, c, d equal to zero
然后检查您是否有任何数字 与 0
:
不同
if(bob.b == 0){
printf("no non-zero number stored in b");
}
你正在尝试做的事情在 C 中没有意义。
唯一的解决方案是分析您的代码并通过逻辑分析证明使用(或不使用)某个变量。
无论如何,我将提供两个可以帮助您的想法。
1.初始化为虚拟值
可以在我们程序处理的值中我们知道它没有意义的变量类型范围内选择一个值。
例如,对于 int
类型,可以选择 INT_MIN
作为虚拟值。
这是 int
类型可以容纳的最小负值。
在 32 位 2 的补码中 int
s 这个值是 -2147483648
,这可能是你的情况。
[INT_MAX
在 <limits.h>
中定义,所以你必须 #include
它。]
#include <limits.h>
numbers bob = { INT_MIN, INT_MIN, INT_MIN, INT_MIN};
if (bob.b == INT_MIN) puts("Unused object.");
此方法有效,前提是您永远不会将 INT_MIN
作为程序其余部分的有效值。
2。改变你的方法
可以使用 pointer to an int
而不是 int
:
#include <stdio.h>
#include <stdlib.h>
typedef struct { int *a, *b, *c, *d; } pnumbers;
int main(void) {
pnumbers bob = { NULL, NULL, NULL, NULL };
int val = 32;
bob.a = &val;
bob.c = malloc(sizeof(int));
bob->c = 20;
if (bob.a != NULL) printf("%d\n", bob->a);
if (bob.b == NULL) puts("Unused member");
if (bob.c != NULL) printf("%d\n", bob->c);
}
这是我目前的代码。
我试图判断结构中的某个变量是否为空。我将创建一个结构,其中一些变量被填充,一些变量不需要,并且需要知道哪些需要我做某事,哪些不需要。
#include <stdio.h>
#include <stdlib.h>
struct nums {
int a;
int b;
int c;
int d;
} typedef numbers;
int main() {
numbers bob;
bob.a = 69;
if (bob.b == NULL) {
printf("no number stored in b");
}
return 0;
}
但我刚收到错误
warning: comparison between pointer and integer
有什么想法吗?
通常无法判断您是否确实在 int
变量中存储了一些内容。
不过,对于您的情况,您可以:
- 初始化你的结构:
numbers bob = { 0 }; // <-- this makes a, b, c, d equal to zero
然后检查您是否有任何数字 与
不同0
:if(bob.b == 0){ printf("no non-zero number stored in b"); }
你正在尝试做的事情在 C 中没有意义。
唯一的解决方案是分析您的代码并通过逻辑分析证明使用(或不使用)某个变量。
无论如何,我将提供两个可以帮助您的想法。
1.初始化为虚拟值
可以在我们程序处理的值中我们知道它没有意义的变量类型范围内选择一个值。
例如,对于 int
类型,可以选择 INT_MIN
作为虚拟值。
这是 int
类型可以容纳的最小负值。
在 32 位 2 的补码中 int
s 这个值是 -2147483648
,这可能是你的情况。
[INT_MAX
在 <limits.h>
中定义,所以你必须 #include
它。]
#include <limits.h>
numbers bob = { INT_MIN, INT_MIN, INT_MIN, INT_MIN};
if (bob.b == INT_MIN) puts("Unused object.");
此方法有效,前提是您永远不会将 INT_MIN
作为程序其余部分的有效值。
2。改变你的方法
可以使用 pointer to an int
而不是 int
:
#include <stdio.h>
#include <stdlib.h>
typedef struct { int *a, *b, *c, *d; } pnumbers;
int main(void) {
pnumbers bob = { NULL, NULL, NULL, NULL };
int val = 32;
bob.a = &val;
bob.c = malloc(sizeof(int));
bob->c = 20;
if (bob.a != NULL) printf("%d\n", bob->a);
if (bob.b == NULL) puts("Unused member");
if (bob.c != NULL) printf("%d\n", bob->c);
}