簡體   English   中英

交流程序的異常行為?

[英]Unexpected behaviour of a c program?

這段代碼沒有提供預期的輸出,顯然我無法理解程序的行為。請幫助我理解此程序。任何幫助將不勝感激。 您可以在此處查看程序https://code.hackerearth.com/31d954z?key=fce7bc8e07fc10a3d7a693e45a5af94a的輸出。

1.在最后一條評論中,我找不到為什么數組的元素未更新的原因。

2.在func主體上打印'a'時,會產生一些意外的輸出。

例如,如果我通過j = 2且a [0] = 1

  After j = j+1 , which results in j = 3; a=a+j should result in a = 4 but instead it result in a = 13. 
#include <stdio.h>

void func(int j,int *a)
{
 j=j+1;
 printf("%d\t%d\n",a,j);     //prints j updated value and a
 a=a+j;
 printf("a = %d\n ",a);      //prints value of a
}


void main()
{
 int a[5] ={1,2,3,4,5},i,j=2;
 for (i =0;i<5;i++ )
 func(j, a[i]);
 for (i =0;i<5;i++ )   
 printf("%d\t",a[i]);    //Prints the array as 1 2 3 4 5
}

運行此代碼時,輸​​出為:

1 3 // Here a = 1 and j = 3 a = 13 //but after addition a = 13 2 3 a = 14 3 3 a = 15 4 3 a = 16 5 3 a = 17 1 2 3 4 5 //array elements not updated

我想了解代碼行為。

您的代碼會產生Undefined Behavior ,因此您應該停止正在做的事情並對其進行調試


當您想索引數組時,您可以像這樣:

a[i]

在那里i是索引和a你的陣列。 因此,如果要訪問第一個元素,則需要執行a[0] ,當您要索引第三個元素時,則需要執行a[2] ,依此類推。


但是,您可能想要做的只是傳遞第i個元素,添加並打印它。

因此,您應該啟用編譯器警告:

prog.c: In function 'func':
prog.c:6:11: warning: format '%d' expects argument of type 'int', but argument 2 has type 'int *' [-Wformat=]
  printf("%d\t%d\n",a,j);     //prints j updated value and a
          ~^
          %ls
prog.c:8:15: warning: format '%d' expects argument of type 'int', but argument 2 has type 'int *' [-Wformat=]
  printf("a = %d\n ",a);      //prints value of a
              ~^
              %ls
prog.c: At top level:
prog.c:12:6: warning: return type of 'main' is not 'int' [-Wmain]
 void main()
      ^~~~
prog.c: In function 'main':
prog.c:16:10: warning: passing argument 2 of 'func' makes pointer from integer without a cast [-Wint-conversion]
  func(j, a[i]);
          ^
prog.c:3:6: note: expected 'int *' but argument is of type 'int'
 void func(int j,int *a)
      ^~~~

然后相應地修改您的代碼,例如:

#include <stdio.h>

void func(int j,int a)
{
 j=j+1;
 printf("%d\t%d\n",a,j);   
 a=a+j;
 printf("a = %d\n ",a);
}


int main(void)
{
 int a[5] ={1,2,3,4,5},i,j=2;
 for (i =0;i<5;i++ )
 func(j, a[i]);
 for (i =0;i<5;i++ )   
 printf("%d\t",a[i]);
}

輸出:

1   3
a = 4
 2  3
a = 5
 3  3
a = 6
 4  3
a = 7
 5  3
a = 8
 1  2   3   4   5

那是因為您正在為需要指針的函數賦值。

void func(int j,int *a) // a is a pointer

這就是你通過的:

func(j, a[i]); // a[i] is a value

您應該傳遞一個您想要更改的值的地址。 這樣,如果在func上更改了值,則主體也將具有更改后的值。 如果按值傳遞,func將在堆棧上更改該值(因為函數參數進入堆棧),而main將具有舊的未更改值。 要將引用傳遞給要更改的值,請使用以下命令:

func(j, a + i); //a is address to start of array

當然,在函數中,您應該增加值,而不是地址:

*a += j; // Instead of a = a + j where 'a' is pointer according your function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM