gpt4 book ai didi

c - C:将数组传递给函数并在接收者函数中进行迭代

转载 作者:行者123 更新时间:2023-12-04 10:33:25 24 4
gpt4 key购买 nike

我想将数组传递给C中的函数并对其进行迭代。我有此代码:

#include <stdio.h>

int funct(int * a);

int main(int argc, char ** argv){
int a[5] = {0};
int b[5] = {1, 1};

printf("Size of cache: %d\n", sizeof(a));
printf("Array values:\n");
printf("Numb of elments in a[]: %d\n", (sizeof(a) / sizeof(a[0])));

for(int i = 0; i < (sizeof(a) / sizeof(a[0])); i++){
printf("for loop\n");
printf("%d\n", a[i]);
}
printf("\n");

printf("Size of cache: %d\n", sizeof(b));
printf("Array values:\n");
printf("Numb of elments in a[]: %d\n", (sizeof(b) / sizeof(b[0])));

for(int i = 0; i < (sizeof(b) / sizeof(b[0])); i++){
printf("for loop\n");
printf("%d\n", b[i]);
}
printf("\n");

funct(a);
funct(b);

return 0;
}

int funct(int * a){

printf("Size of cache: %d\n", sizeof(a));
printf("Numb of elements in a[]: %d\n", (sizeof(a) / sizeof(a[0])));
printf("Array values:\n");

for(int i = 0; i < (sizeof(a) / sizeof(a[0])); i++){
printf("sizeof(a): %d\n",sizeof(a));
printf("sizeof(a[0]): %d\n",sizeof(a[0]));
printf("for loop\n");
printf("%d\n", a[i]);
}
printf("\n");

return 0;
}


结果是:


Size of cache: 20
Array values:
Numb of elments in a[]: 5
for loop
0
for loop
0
for loop
0
for loop
0
for loop
0

Size of cache: 20
Array values:
Numb of elments in a[]: 5
for loop
1
for loop
1
for loop
0
for loop
0
for loop
0

Size of cache: 4
Numb of elements in a[]: 1
Array values:
sizeof(a): 4
sizeof(a[0]): 4
for loop
0

Size of cache: 4
Numb of elements in a[]: 1
Array values:
sizeof(a): 4
sizeof(a[0]): 4
for loop
1



请解释为什么我不能遍历函数内部的数组-我在做什么错(i)以及如何正确地做到这一点(ii)。谢谢

最佳答案

因为sizeof运算符为您提供指针的大小,而不是数组中的元素数,所以您应该这样编写函数

int funct(int * a, int count){

printf("Size of cache: %d\n", sizeof(a));
printf("Numb of elements in a[]: %d\n", (sizeof(a) / sizeof(a[0])));
printf("Array values:\n");

for(int i = 0; i < count; i++){
printf("sizeof(a): %d\n",sizeof(a));
printf("sizeof(a[0]): %d\n",sizeof(a[0]));
printf("for loop\n");
printf("%d\n", a[i]);
}
printf("\n");

return 0;
}


然后在 main()函数调用中

funct(a, sizeof(a) / sizeof(a[0]));
funct(b, sizeof(b) / sizeof(b[0]));


您无法获得指针指向的元素数,因此唯一的方法是将其作为函数参数与数组一起传递。

另请注意,您没有正确初始化数组,并且在尝试打印数组的元素时这将是未定义的行为。

关于c - C:将数组传递给函数并在接收者函数中进行迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27731351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com