【发布时间】:2020-10-20 00:07:29
【问题描述】:
这很好用:
#include <unistd.h>
const char error[] = “Not enough arguments\n”;
int main(void)
{
write(2, error, sizeof(error));
return (0);
}
Output: Not enough arguments
但是在这种情况下 sizeof 会返回指针的大小:
#include <unistd.h>
const char *error[] = {
"Not enough arguments\n",
"Malloc failed\n",
"Etc...\n",
NULL
};
int main(void)
{
int i = 0;
while (error[i])
{
write(2, error[i], sizeof(error[i]));
i++;
}
return (0);
}
Output: Not enouMalloc fEtc...
显然,我可以只使用 strlen 或 printf 或大量其他解决方案。但我主要想知道 sizeof() 是否可行,但没有明确声明其大小(例如 char error[4][12])。
【问题讨论】:
-
不,这是不可能的。
error的元素是指针,而不是数组。 -
对于第一个例子:几乎完美,或+1字节;
sizeof(error)返回 22,覆盖数组显示的 21 个字节 + 空终止符;尝试将输出通过管道传输到cat -v或xxd -g 1
标签: c