gpt4 book ai didi

c - c 程序的意外行为?

转载 作者:太空宇宙 更新时间:2023-11-04 06:55:35 24 4
gpt4 key购买 nike

此代码没有按预期提供输出,显然我无法理解程序行为。请帮助我理解这一点。任何帮助将不胜感激。您可以看到程序的输出 https://code.hackerearth.com/31d954z?key=fce7bc8e07fc10a3d7a693e45a5af94a在这里。

1.In the last comment, I can't find why the elements of array are not updated.

2.In the body of func on printing 'a' it gives some unexpected output.

For e.g., if i pass j = 2 and 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

最佳答案

I want to understand the code 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

关于c - c 程序的意外行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45400396/

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