Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Why does my program break in my reverseCopy function saying that it needs a hand

ID: 674431 • Letter: W

Question

Why does my program break in my reverseCopy function saying that it needs a handled exception to run safely?

#include <stdio.h>
#define MAX 10

void reverseCopy(int *array1[MAX], int *array2[MAX]);

int main(void)
{
   int array1[MAX] = { 1,2,3,4,5,6,7,8,9,10 };
   int array2[MAX] = { 0 };

   reverseCopy(&array1, &array2);
   printf("%d", &array2);
}

void reverseCopy(int *array1[MAX], int *array2[MAX])//swaps the numbers from the first array with the numbers from the 2nd array
{
   size_t i;
   int j;

   for (j = 0;j < MAX;j++) {
       for (i = 9; i >= 0;i--)
       {
           *(array2 + j) = *(array1 + i);//program breaks here and says unhandled exception. I'm not quite sure why
       }
   }
}

Explanation / Answer

I checked your code and It is not giving exception you mentioned but It is giving segmentation Fault which means errors related to Memory management and which is coming because you use pointers wrongly in your code. like

   printf("%d", &array2); // is will not print your array insead it will print address of first element.

and other thing there is error in your logic

for (j = 0;j < MAX;j++) {
       for (i = 9; i >= 0;i--)
       {
           *(array2 + j) = *(array1 + i);//program breaks here and says unhandled exception. I'm not quite sure why
       } // It will assign element at index 0 to array2 everytime.
   }

and other errors are you are passing address of arrays and I wish to mention that array name itself defines address of first element of array. So I have wrote simple code for you below.

#include <stdio.h>
#define MAX 10

void reverseCopy(int array1[MAX], int array2[MAX]);

int main(void)
{
   int j;
    int array1[MAX] = { 1,2,3,4,5,6,7,8,9,10 };
    int array2[MAX] = { 0 };

    reverseCopy(array1, array2);
    for (j = 0;j< MAX;j++) {
      
            printf("%d",array2[j]);
      
    }
}
void reverseCopy(int array1[MAX], int array2[MAX])
{
   int i =9;
    int j;

    for (j = 0;j < MAX;j++) {
      
            (array2[j]) = (array1[i]);
            i--;
      
    }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote