如何测试变量是否有效或在C中是否初始化?
我正在从哈佛大学的CS50课程中从头开始学习C。 我得到了一个以这种方式初始化的数组:
int stuff[9][9];
现在我必须处理它。
我想检查数组的每个项目是否存在:如果不存在,制作stuck [i] [j] = 0
,否则,stuff [i] [j] ++
但是我正在搜索而没有导致如何检查我正在操纵的变量是否存在或有效或其他问题:没有! [i] [j]
或比较if(Quate [i] [j] =='undefined')
或null
或我的任何变体可以使用...
那么,如何检查是否尚未初始化声明的变量?
更新
我已经对此进行了测试:
int a[3];
for(int i = 0; i < 3; i++)
{
a[i] = a[i] || 0;
}
for(int i = 0; i < 3; i++)
{
printf("a[%i] -> %i\n", i, a[i]);
}
因此,如果a [i]
不存在(即没有分配的值),它将接收值0
。 这是printf
的输出:
a[0] -> 1
a[1] -> 1
a[2] -> 0
这很好,因为此方法没有丢失错误,但是...这些数字是多少?
I am learning C from scratch with Harvard's cs50 course.
I've been given an array that's been initialized this way:
int stuff[9][9];
now I have to handle it.
I want to check if each item of the array exists: if not, make stuff[i][j] = 0
, otherwise, stuff[i][j]++
But I am searching without resulting on how to check if the variable I am manipulating exists or is valid or whatever: there is no !!stuff[i][j]
, nor some typeof stuff[i][j]
or comparing if (stuff[i][j] == 'undefined')
or NULL
or any variations of that which I can use...
So, how can I check if a declared variable has not yet been initialized?
update
I've made a test with this:
int a[3];
for(int i = 0; i < 3; i++)
{
a[i] = a[i] || 0;
}
for(int i = 0; i < 3; i++)
{
printf("a[%i] -> %i\n", i, a[i]);
}
so, if a[i]
didn't exist (i.e. had no value assigned to it), it would receive value 0
.
this was the output of the printf
:
a[0] -> 1
a[1] -> 1
a[2] -> 0
That's good because this approach didn't throw an error, but... what are those numbers??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设上面的数组是局部变量而不是全局变量,则数组的值是 的,并且实际上您 chot 检查变量是否是非初始化的,因为简单地尝试读取这种变量可以触发 nofollow noreferrer“> nofection defined行为。
听起来您希望所有数组元素从值0开始。执行此操作的最简单方法是初始化数组:
它明确设置元素
[0] [0] [0] [0]
to 0并隐含将所有其他元素设置为0。或者,您可以创建一个循环以将所有值设置为0,然后在进行“常规”处理之前开始。
Assuming the above array is a local variable and not a global, the values of the array are uninitialized and in fact you can't check whether a variable is uninitialized or not, as simply attempting to read such a variable can trigger undefined behavior.
It sounds like you want all array elements to start with the value 0. The simplest way to do this is to initialize the array as such:
Which explicitly sets element
[0][0]
to 0 and implicitly sets all other elements to 0.Alternately, you can create a loop to set all values to 0 to start before doing your "regular" processing.