Sizeof数组通过C中的函数 [英] Sizeof array through function in C
问题描述
我不知道为什么在通过我的函数传递数组时不能使用 sizeof(array) 只输出值 1,而不是 1000000.在将数组传递给函数之前,我打印了 sizeof(array)得到 4000000,当我尝试在函数中打印 sizeof(array) 时,我只得到 4.我可以在函数和 main 中迭代数组以显示所有值,但我无法在函数中显示 sizeof.我是否错误地传递了数组?
I'm not sure why I cannot use sizeof(array) when passing the array through my function only outputs a value of 1, instead of 1000000. Before passing the array to the function, I printed out the sizeof(array) to get 4000000 and when I try to printout the sizeof(array) in the function, I only get 4. I can iterate through the array in both the function and the main to display all values, I just cannot display sizeof within the function. Did I pass the array through incorrectly?
#include <stdio.h>
#include <stdlib.h>
int
searchMe(int numbers[], int target)
{
printf("%d\n", sizeof(numbers));
int position = -1;
int i;
int k = sizeof(numbers) / sizeof(numbers[0]);
for (i = 0; i < k && position == -1; i++)
{
if (numbers[i] == target)
{
position = i;
}
}
return position;
}
int
main(void)
{
int numbers[1000000];
int i;
int search;
for (i = 0; i < 1000000; i++) {
numbers[i] = i;
}
printf("Enter a number: ");
scanf("%d", &search);
printf("%d\n", sizeof(numbers));
int position = searchMe(numbers, search);
printf("Position of %d is at %d\n", search, position);
return 0;
}
推荐答案
int searchMe(int numbers[], int target)
相当于
int searchMe(int *numbers, int target)
函数参数有一个特殊的 C 规则,即数组类型的参数调整为指针类型.
There is a special C rules for function parameters that says parameters of array type are adjusted to a pointer type.
这意味着在您的程序中,sizeof numbers
实际上产生了 int *
指针类型的大小,而不是数组的大小.
It means in your program that sizeof numbers
actually yields the size of the int *
pointer type and not of the array.
要获得大小,您必须向函数添加第三个参数,并在调用函数时显式传递数组的大小.
To get the size you have to add a third parameter to your function and explicitly pass the size of the array when you call the function.
这篇关于Sizeof数组通过C中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!