gpt4 book ai didi

c - 整数数组中元素的不同打印输出

转载 作者:太空宇宙 更新时间:2023-11-04 02:25:57 26 4
gpt4 key购买 nike

我尝试编写代码对数组中的元素进行计数,它有效。
问题是 gcc 使用 main() 中的 for 语句和函数调用 countreturn(size_t sz, int *arr) 打印不同的输出>.

下面是输出和代码..输出:

----------

1 1 1 1 1

1 1 1 1 32766

5

0


for 语句打印 1 而不是 32766,但在使用函数时它打印 32766。

#include<stdio.h>
int countreturn(size_t sz, int *arr){
int i=0, count = 0;
while(arr[i]!='\0'&&i<sz){
++i;
++count;
printf("%d ",arr[i]);
}
printf("\n");
return count;
}

int main(){
int store[5] = {[0 ... 4] = 1 };
printf("-----------------\n");
for(int i = 0; i <5; ++i){
printf("%d ", store[i]);
}
printf("\n");
printf("-----------------\n");

int store2[500] = {'\0',};

printf("%d\n", countreturn(sizeof(store)/sizeof(int),store));
printf("%d\n", countreturn(sizeof(store2)/sizeof(int),store2));
return 0;
}

最佳答案

问题是您首先递增 i 的值,然后打印存储在第 i 个索引处的值,这就是您的代码打印垃圾值的原因。

#include<stdio.h>
int countreturn(size_t sz, int *arr){
int i=0, count = 0;
while(arr[i]!='\0'&&i<sz){
printf("%d ",arr[i]); //print first then
++i; // increment value if i
++count;
}
printf("\n");
return count;
}

int main(){
int store[5] = {[0 ... 4] = 1 };
printf("-----------------\n");
for(int i = 0; i <5; ++i){
printf("%d ", store[i]);
}
printf("\n");
printf("-----------------\n");

int store2[500] = {'\0',};

printf("%d\n", countreturn(sizeof(store)/sizeof(int),store));
printf("%d\n", countreturn(sizeof(store2)/sizeof(int),store2));
return 0;
}

关于c - 整数数组中元素的不同打印输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51234310/

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