我有一个尚未初始化的 char x[16]
,我需要测试是否已将某些内容分配给x
或者它是如何在运行。我该怎么做?谢谢
示例代码
int main(int argc, char** argv) {
char x[16];
//<other part of the code>
if(x is an empty char array (not assigned anything) then skip the next line) {
//blank
}else {
//<rest of the code>
}
return 0;}
PS:我尝试了 memchar(x, '\0', strlen(x))
、if(x[0] == '\0')
和if(!x[0])
但它不能按我想要的方式工作,因为 char 数组默认不包含 \0
。
最佳答案
您必须像这样初始化它:
char x[16] = { 0 }; // note the use of the initializer, it sets the first character to 0, which is all we need to test for initialization.
if (x[0] == 0)
// x is uninitialized.
else
// x has been initialized
另一种选择是alloca
(如果它适用于您的平台),它会在堆栈上为您分配数据。你可以像这样使用它:
char *x = NULL;
if (x == NULL)
x = alloca(16);
else
// x is initialized already.
由于 alloca
在堆栈上分配,因此您无需释放
您分配的数据,这使其比 malloc
具有明显的优势
关于c - 如何在C中检测未初始化的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10767529/