c - 如何在C中检测未初始化的字符串

标签 c arrays string

我有一个尚未初始化的 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/

相关文章:

c - Ardu-IMU将数据发送到Arduino

mmap可以通过函数传递地址吗?

javascript - 在 JavaScript 中的同一对象中重用 key

c++ - 用空格初始化字符数组

c - 是否可以在 #define 中使用 if 语句?

javascript - 在 React Native 中更新嵌套状态对象?

c - 打印字符串会产生垃圾,即使(我认为)它们是空终止的

ios - Xcode 错误 - 文件中缺少所需的架构 i386

java - HashMap.put() 正在覆盖不同键的现有项目

c - 在两个 channel 上播放单声道 WAV