gpt4 book ai didi

c - 在函数中使用#define

转载 作者:行者123 更新时间:2023-11-30 20:06:30 25 4
gpt4 key购买 nike

如何才能在函数中使用#define 变量?我需要创建一个程序来使用此代码调用函数。基本上我底部的函数可以改变,但我的主函数不能从这种格式改变,所以无论我编写我的函数,我都必须通过函数传递变量 a 和变量 SIZE 。但目前看来 SIZE 实际上并没有被识别为 int 变量。

#include <stdio.h>

#define SIZE 9

int i, position, tmp;

void readArray(int a[]);
void printArray(int a[]);
void sortArray(int a[]);

int main(void)
{
int a[SIZE];

readArray(a);

printArray(a);

sortArray(a);

printf("After sorting:\n");

printArray(a);

return 0;
}


//Functions//
void readArray(int a[]){
printf("Please enter %d integers: ", SIZE);
for (i=0; i<SIZE; i++) {
scanf("%d", &a[i]);
}
}

void printArray(int a[]){
for (i=0;i<SIZE;i++) {
printf("a[%d] = %3d\n", i, a[i]);
}
}

void sortArray(int a[]){
for (i=0; i<SIZE; i++) {
// In each iteration, the i-th largest number becomes the i-th array element.
// Find the largest number in the unsorted portion of the array and
// swap it with the number in the i-th place.

for (position=i; position<SIZE; position++) {
if (a[i] < a[position]) {
tmp = a[i];
a[i] = a[position];
a[position] = tmp;
}
}
}
}

最佳答案

写作

 #define SIZE 9

将告诉预处理器将每次出现的 SIZE 替换为 9。意思是,下面一行 -

void sortArray(int a[], int SIZE)

将替换为 -

void sortArray(int a[], int 9)

我想您知道这是非法的。您应该删除第二个函数参数。

关于c - 在函数中使用#define,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23394135/

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