如何在C中指定非空指针参数 [英] How to specify a non-null pointer argument in C
问题描述
问题
你想确保一个函数的指针参数
是非空的。
解决方案
int fn(double data [static 1]);
这意味着数组(作为指针传递) )
必须至少有1个元素,即不能为NULL。
我直到在comp讨论时才意识到这一点。 std.c
jacob navia写道:
问题
您希望确保函数
的指针参数为非null。
解决方案
比较指向空指针的指针,如果没有调用该函数
他们比较相等。
问题
你想假设一个指针函数参数是非空的。
解决方案
int fn(双数据[静态1]);
这个表示数组(作为指针传递)
必须至少有1个元素,即不能为NULL。
这样可以确保一切,但允许某些原本无效的优惠
优化,这可能就是你想要的。一个小问题,
虽然:
#include< stdlib.h>
void f(double data [静态1]){}
void g(double * data){
if(data!= NULL)
f(data) ;
}
int main(无效){
双x;
g(& x + 1);
double * p = malloc(1);
g(p);
免费(p) ;
}
如果静态1,则对f的潜在调用都是有效的。只是意味着
" non-null"仅此而已。
在comp.std.c
<讨论之前,我没有意识到这一点br />
jacob navia写道:
问题
你想要确保函数的指针参数
非空。
解决方案
int fn(double data [静态1]);
这意味着数组(作为指针传递)
必须至少有1个元素,即可以'不是。
我在comp.std.c讨论之前我不知道这个。
如何根据一般情况推断上述内容?
难道只是简单地将NULL与一种更简单的方法进行比较?
jacob navia schrieb:
问题
你想要的确保一个poi函数的nter参数
非空。
解决方案
int fn(double data [static 1]);
这意味着数组(作为指针传递)
必须至少有1个元素,即不能NULL。
我在comp.std.c讨论之前我没有意识到这一点
以什么方式如果p恰好为NULL,那么
x = fn(p);
会失败吗?
Problem
You want to ensure that a pointer argument to a function
is non-null.
Solution
int fn(double data[static 1]);
This means that the array (that is passed as a pointer)
must have at least 1 element, i.e. can''t be NULL.
I wasn''t aware of this till a discussion in comp.std.c
jacob navia wrote:Problem
You want to ensure that a pointer argument to a function
is non-null.Solution
Compare the pointer to a null pointer, and don''t call the function if
they compare equal.
Problem
You want to assume that a pointer function parameter is non-null.
Solution
int fn(double data[static 1]);
This means that the array (that is passed as a pointer)
must have at least 1 element, i.e. can''t be NULL.This ensures nothing, but allows certain otherwise invalid
optimisations, which may well be what you wanted. A minor point,
though:
#include <stdlib.h>
void f(double data[static 1]) {}
void g(double *data) {
if(data != NULL)
f(data);
}
int main(void) {
double x;
g(&x + 1);
double *p = malloc(1);
g(p);
free(p);
}
Both potential calls to f would be valid if "static 1" only meant
"non-null" and nothing more.
I wasn''t aware of this till a discussion in comp.std.c
jacob navia wrote:Problem
You want to ensure that a pointer argument to a function
is non-null.
Solution
int fn(double data[static 1]);
This means that the array (that is passed as a pointer)
must have at least 1 element, i.e. can''t be NULL.
I wasn''t aware of this till a discussion in comp.std.cHow''s the above to be extrapolated for the general case?
Isn''t simply comparing against NULL a simpler approach?
jacob navia schrieb:
Problem
You want to ensure that a pointer argument to a function
is non-null.
Solution
int fn(double data[static 1]);
This means that the array (that is passed as a pointer)
must have at least 1 element, i.e. can''t be NULL.
I wasn''t aware of this till a discussion in comp.std.cIn what way then will
x = fn(p);
fail if p happens to be NULL?
这篇关于如何在C中指定非空指针参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!