我是 C 编码新手。我正在尝试编写一个程序,在数组的第一个位置添加一个值。如下图append
函数必须返回多个值。
当我使用printf("%d ", array[c])
时在这个函数中声明,没有问题,我得到了我想要的值。
但是,当我使用return s;
时在此函数中的语句中,它只给出一个值,尽管它必须给出与 printf("%d ", array[c])
相同的值。声明。
当我使用 printf("%d ", array[c])
运行此代码时,输出为:
25, 5, 8, 555, 99
当我使用 return s
运行此代码时,输出为;
25
为什么两个陈述之间有不同?我不需要在屏幕上打印这些值。我需要使用return
陈述。请帮助我......
#include <stdio.h>
int append(int array[]){
int position, c, s, len=4, value=25;
position=1;
for (c = len - 1; c >= position-1; c--){
array[c+1] = array[c];
}
array[position-1] = value;
for (c = 0; c <= len; c++){
//return array[c]; // <-- why this give only one value???
printf("%d ", array[c]); //<-- this print the all value !!!
}
}
int main(){
int kar[]= {5, 8, 555, 99};
printf("%d", append(kar));
return 0;
}
最佳答案
您将array
传递给函数,这实际上是传递一个指向数组第一个元素的指针。这意味着对函数中数组的更改也会出现在调用函数中,因为它是同一个数组。
您不需要返回任何东西。只需打印 main
中数组的内容即可。
此外,大小为 4 的数组的索引从 0 到 3。现在您正在写入超出数组末尾的内容。您需要更改您的功能来防止这种情况发生。您不能只写到数组末尾以使其变大。大小是固定的。
void append(int array[]){
int position, c, s, len=4, value=25;
position=1;
for (c = len - 2; c >= position-1; c--){
array[c+1] = array[c];
}
array[position-1] = value;
}
int main() {
int kar[]= {5, 8, 555, 99};
append(kar);
int c;
for (c = 0; c < 4; c++){
printf("%d ", kar[c]);
}
return 0;
}
关于C 编程 ... 为什么 "return"语句在这段代码中只给出一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53071182/