繁体   English   中英

这是问题“在 C 中编写程序以将数组的引用传递给 function 并打印该数组”,这不是给 output,为什么?

[英]this is the question "write a program in C to pass the reference of an array to a function & print that array" ,this is not giving the output ,why?

我的一位同行问我这个问题,因为我不太了解“C”,但我仍然是初学者,我尝试解决它,这是我使用的方法,但它没有给出预期的 output。

根据问题,它应该打印数组的输入元素,当我们将数组的引用传递给 function 时,任何人都可以查看此代码吗?

#include <stdio.h>
void print(int arr[], int n);

int main(){
    
    int n,i;
    int arr[n];

    printf("enter the size of array :");
    scanf("%d",&n);
    
    
    printf("enter elements :\n");
    for(i=0; i<n; i++){
        scanf("%d",&arr[i]);
    }
    print(&arr[i], n);
    
}

void print(int arr[], int n){
    int i;
    for(i=0; i<n; i++){
        printf("\nentered elements are : %d",arr[i]);
    }
}

这个变长数组的声明

int n,i;
int arr[n];

调用未定义的行为,因为变量n未初始化。

相反,你需要写

int n,i;

printf("enter the size of array :");

if ( scanf("%d",&n) == 1 && n > 0 )
{
    int arr[n];
    // and so on

这个电话

print(&arr[i], n);

再次导致未定义的行为,因为变量 i 的值等于数组的大小。 所以表达式&arr[i]指向数组外部。

你需要写

print( arr, n);

像这样声明和定义 function 会更正确

void print( const int arr[], int n )
{
    printf( "\nentered elements are: " );
 
    for ( int i = 0; i < n; i++ )
    {
        printf( "%d ", arr[i] );
    }
    putchar( '\n' );
}

您的程序没有给出 output,因为您没有声明数组的大小,即代替 arr[n] 写入 arr[100] 或任何其他正 integer。 否则代码没有错误。

希望这会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM