C 编程 ... 为什么 "return"语句在这段代码中只给出一个值?

标签 c return

我是 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/

相关文章:

C 字符串解析

c - 使用 C void 参数 "void foo(void)"还是不使用 "void foo()"更好?

c - 如何在C中的套接字上发送彩色消息?

java - 无法使用 boolean 值在 if 语句内返回

python - 为什么我的递归函数返回 None?

c - 返回结构并保存在不同 .c 文件中的结构变量中

c - 为什么变量求和返回乘法?

无法运行程序 "make": The system cannot find the file specified?

python - 如何在不使用请求上下文的情况下在 flask 中呈现模板

java - 递归方法返回并打印 String 的 Int 数