1
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *a= malloc(sizeof(int)*10);
    scanf("%d %d",a,a+1);
    if(*a<*(a+1))
    {
        *a=*(a+1);
        }
    printf("%d",*a);
    return 0;
}

Can I use the same array pointer to input 2 numbers and find largest number among them, as shown in the above code?

Willeke
  • 14,578
  • 4
  • 19
  • 47
Combospirit
  • 313
  • 1
  • 2
  • 11

2 Answers2

0

Yes, it will work, although it might be perceived as more readable to use bracket notation for array elements. You also only need to malloc space for 2 elements.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *a = malloc(sizeof(int) * 2);
    scanf("%d %d", &a[0], &a[1]);
    if(a[0] < a[1])
    {
        a[0] = a[1];
    }
    printf("%d", a[0]);
    return 0;
}

Read more about pointers and how they work

LGP
  • 4,135
  • 1
  • 22
  • 34
0

Yes, you can. Because when you say *a you are pointing to the 0th location of the array and getting the value there and when you say *(a+1) you are pointing to 1st location of the array. Same analogy for &a and &(a+1).

Iresh Dissanayaka
  • 483
  • 1
  • 4
  • 18