Sizeof array through function in C [duplicate]

北城以北 提交于 2019-12-29 02:09:10

问题


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;
}

回答1:


int searchMe(int numbers[], int target)

is equivalent to

int searchMe(int *numbers, int target)

There is a special C rules for function parameters that says parameters of array type are adjusted to a pointer type.

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.




回答2:


Because arrays are passed as reference. Meaning only pointer to array is passed. Sizeof inside the function would only print the size of pointer, not the size of array.

Besides just making sure you know, size of returns number of bytes, so if you have an integer array (where int is of size 4 for e.g. sizeof would give elements * 4 as output.



来源:https://stackoverflow.com/questions/24897716/sizeof-array-through-function-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!