-1
#include<stdio.h>

int main(void) {
    int arr[7];
    int i;
    int copy[7];
    int j;
    int *ptr_copy;
    int *ptr_arr;
    ptr_arr=&arr[0];
    ptr_copy=&copy[0];
    printf("Enter 7 Element In the Array");
    for(i=0;i<7;i++)
        scanf("%d",&ptr_arr[i]);

    printf("\n");

    for(i=7,j=0;i>=0;i--,j++)
        ptr_copy[j]=ptr_arr[i];

    for(i=0;i<7;i++)
        ptr_copy[i]=ptr_copy[i]*-1;
    printf("%d",ptr_copy[i]);
}

In the last loop I thought if I multiply the loop by -1 all the numbers' signs will change, is that correct? And in the last loop I'm not sure if it's correct. Could you help me and tell me where is the mistake?

PiotrWolkowski
  • 8,408
  • 6
  • 48
  • 68
DreamBig
  • 19
  • 1
  • 4

2 Answers2

3

You have undefined behaviour in this code . As you access index out of bound here -

 for(i=7,j=0;i>=0;i--,j++)
 ptr_copy[j]=ptr_arr[i];

ptr_array[7] isn't there . Array is till index 6. ptr_arr[7] contains garbage or whatever.

Change this loop to this (start from i=6)-

for(i=6,j=0;i>=0;i--,j++)
ptr_copy[j]=ptr_arr[i];

Also need a {} here -

for(i=0;i<7;i++){
  ptr_copy[i]=ptr_copy[i]*-1;
  printf("%d",ptr_copy[i]);
}
ameyCU
  • 16,489
  • 2
  • 26
  • 41
2

The problem is that you didn't put { } around the body of the last loop. So the printf is not part of the loop, it's run when the loop is done. And when the loop is done the value of i is 7, which is outside the bounds of the array.

This became obvious once I used my editor's indent command to reformat the code.

It should be:

for(i=0;i<7;i++) {
    ptr_copy[i]=ptr_copy[i]*-1;
    printf("%d",ptr_copy[i]);
}

I recommend you always put braces around the bodies of your if, while, for, etc. even if they only have one line. See Why is it considered a bad practice to omit curly braces?

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612