Home > Net >  For a C program, I had to accept 5 element of an array from a user and copy them to another array us
For a C program, I had to accept 5 element of an array from a user and copy them to another array us

Time:11-23

Write a program to accept 5 integer elements of an array and copy them to another array, but all tasks must be performed using pointers.

// Here is my  program

#include <stdio.h>
#include <conio.h>

void main() {
  int arr[5], brr[5], *p, *q, i;
  p = arr;
  q = brr;
  for (i = 0; i < 5; i  ) {
    printf("Enter any 5 element=");
    scanf("%d", (p   i));
  }
  for (i = 0; i < 5; i  ) {
    brr[i] = arr[i];
  }
  for (i = 0; i < 5; i  ) {
    printf("Copied array elements are=%d", brr);
  }
  getch();
}

CodePudding user response:

Your code is correct except for the line where you're placing the output where you aren't using a pointer to the elements of brr.

Try

for(i=0;i<5;i  )
{
     printf("Copied array elements are=%d\n",*(q i));   
}

CodePudding user response:

In the following line:

printf("Copied array elements are=%d", brr);

You are telling the system to display the brr (of type int[] — synonymous to int*) with %d that expects an integer. That leads to the problem.

You want to:

printf("Copied array elements are = ");
for (i = 0; i < 5; i  )
    // Accessing the array element in a sequence.
    // NOTE: brr[i] could also be used, but pointer is used for this question.
    // brr[i] is the syntactic sugar of *(brr   i). No key differences.
    printf("%d ", *(brr   i));

printf("\n");

As a side note, you want to:

printf("Enter any 5 element = ");
for (i = 0; i < 5; i  )
    scanf("%d", (p   i));
  • Related