我在 main 中有这个数组。
int main()
{
int list[] = {1,2,3};
print_list(list);
}
根据编译器警告,列表以 NULL
终止。
当我尝试打印列表时,我将打印一个额外的元素,因为 sizeof(list) 似乎是 +1。
void print_list(const int *list)
{
int i;
for(i=0; i < sizeof(list); i++)
printf(list[i]);
}
对于任何类似这样的情况,我应该使用 sizeof(list) - 1
运行 for 循环吗?
或者我应该在循环内部检查 if(list[i] == NULL
?
如果我的函数没有从列表中创建指针,我可以使用:sizeof(list)/sizeof(list[0])
该函数正在将数组转换为指针。那么如何才能得到准确的尺寸呢?
确实,我的问题对某些人来说非常简单和微不足道。我相信我已经付出了足够的努力,请帮忙。
[编辑] Why isn't the size of an array parameter the same as within main? 这就是我已经知道的,它仍然没有回答我的问题,所以不是重复的。
最佳答案
sizeof
返回其参数的大小(以字节为单位)。在大多数架构中,sizeof(int*)
将返回 4。使用指针不可能获取数组的大小。阅读 this
使用此代码:
主要:
int main()
{
int list[] = {1,2,3};
print_list(list, sizeof(list) / sizeof(int));
}
打印列表:
void print_list(const int *list, int size)
{
int i;
for(i=0; i < size; i++)
printf(list[i]);
}
关于c - Sizeof List 和遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20531542/