我想用C语言编写一个程序,该程序可以读取3个数字并打印出较大的数字,而只使用一个指针而不使用更多变量。 有人可以给我提供代码吗?我无法实现这一目标。 我认为的唯一方法是使用这样的指针:* p [3],但我确实知道这是否是我们要执行的操作。 我还考虑过使用malloc,但是我不确定如何使用
我们得到的原型是:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int*p;
...
}
答案 0 :(得分:0)
我想用C语言编写一个程序,该程序可以读取3个数字并仅使用一个指针,而不再使用变量来打印较大的数字。
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *p;
p = malloc(sizeof *p); // assume it worked
if (scanf("%d", p) != 1) /* error */; // read 1st number
printf("%d\n", *p); // print 1st number
if (scanf("%d", p) != 1) /* error */; // read 2nd number
printf("%d\n", *p); // print 2nd number
if (scanf("%d", p) != 1) /* error */; // read 3rd number
printf("%d\n", *p); // print 3rd number
free(p);
}
上面的程序,执行所需的操作。此外,它还会打印中间和较小的数字!
使用3个指针的数组进行更新
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *p[3];
p[0] = malloc(sizeof *p[0]); // assume it worked
p[1] = malloc(sizeof *p[0]); // assume it worked
p[2] = malloc(sizeof *p[0]); // assume it worked
if (scanf("%d", p[0]) != 1) /* error */; // read 1st number
if (scanf("%d", p[1]) != 1) /* error */; // read 2nd number
if (scanf("%d", p[2]) != 1) /* error */; // read 3rd number
if ((*p[0] >= *p[1]) && (*p[0] >= *p[2])) printf("%d\n", *p[0]);
if ((*p[1] > *p[0]) && (*p[1] >= *p[2])) printf("%d\n", *p[1]);
if ((*p[2] > *p[0]) && (*p[2] > *p[1])) printf("%d\n", *p[2]);
free(p[2]);
free(p[1]);
free(p[0]);
}