gpt4 book ai didi

c - 使用没有指针的函数的 C 程序不起作用

转载 作者:行者123 更新时间:2023-11-30 21:18:12 26 4
gpt4 key购买 nike

我写了一段代码,但它无法运行。不过编译器并没有错误。我被困住了,你能给我一个提示吗?我错在哪里?我 95% 确定它与 checktable 函数有关。附:我知道如何使用指针来实现这一点,但我尝试了解如何在没有指针的情况下实现它。

谢谢!

#include <stdio.h>  
#include "genlib.h"

void fillarray (int a[50])
{
int i;
for(i=0;i<50;i++)
a[i]=rand()%10;
}

void printarray (int a[50])
{
int i;
for(i=0;i<50;i++)
printf(" %d ", a[i]);
}

int number()
{
int num;
printf("Give the number!");
num=GetInteger();
return num;
}

void checktable (int a[50], int b[50], int ar,int count)
{
int i;
count=0;
for(i=0;i<50;i++)
if (a[i]==ar)
{

b[count]=i;
count++;
}

}
main()
{
int i,a[50], b[50], N,count;
fillarray(a);
printarray(a);
N=number();
checktable(a,b,N,count);
printf("the number is used %d times", count);
printf("in places:");
for(i=0;i<count;i++)
printf("%d ",b[i]);

getch();
}

最佳答案

方法一:“指针”方式:

在您的代码中进行更改

void checktable (int a[50], int b[50], int ar,int count)

void checktable (int a[50], int b[50], int ar,int *count)

并将其命名为 checktable(a,b,N,&count);

<小时/>

方法2:“返回”方式:

否则,checktable()中更新的count将不会反射(reflect)在main()中。

但是,或者(不使用指针),IMO,通过 return 语句简单地返回出现次数总是更容易。在这种情况下,代码将如下所示

int checktable (int a[50], int b[50], int ar)
{
int i;
int count=0;
for(i=0;i<50;i++)
if (a[i]==ar)
{

b[count]=i;
count++;
}
return count;
}

调用将是

 count = checktable(a,b,N);

注意:初始化变量始终是一个好习惯。

关于c - 使用没有指针的函数的 C 程序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27102277/

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