PDA

View Full Version : Multiplying array elements by 3. C program on Xcode




Mugambo
Jul 25, 2012, 09:57 PM
On the last return line, I get the error:
Thread 1: Signal SIGABRT.

I have written the C program on xcode.
This is a program to multiply an array by 3 and return new values.
Please tell me what the error is and any suggestions to make this program work.

Learning C from 2 weeks.

#include <stdio.h>

int modify(int anth[10])
{
int i;
for(i=0;i<10;i++)
{
anth[i]*=3;
}
return anth[10];
}

int main(int argc, const char * argv[])
{
int i, *anth;
int arr[10]={1,2,3,4,5,6,7,8,9,10};
anth=arr;
modify(&arr[10]);
for(i=0;i<=9;i++)
{
printf("%d.", arr[i]);
}
return 0;
}



lee1210
Jul 25, 2012, 10:27 PM
After the initial declaration of arr, you no longer need the [10]. You do need [] in the declaration of modify. Right now, instead of passing the address of the 0th element of arr to modify, you're passing the address of the (non-existant/overflow) 10th element to modify. If you just pass arr you should be fine. Also, there's no real reason to return an int from modify, you're not using it. Right now when you call modify it is mutilating memory situated right after arr, which will cause all sorts of trouble. Try to make these changes and see how it goes.

-Lee

Mugambo
Jul 25, 2012, 10:36 PM
Thanks Lee!
1) I removed 10(overflow) within [] from modify() while defining the function.

2) while calling function modify. Used modify(arr) instead of modify(&arr[10])

And it worked perfect!

While returning values however, we need the [10]. Is it because we're indicating size of array being returned?

gnasher729
Jul 26, 2012, 02:02 AM
Thanks Lee!
1) I removed 10(overflow) within [] from modify() while defining the function.

2) while calling function modify. Used modify(arr) instead of modify(&arr[10])

And it worked perfect!

While returning values however, we need the [10]. Is it because we're indicating size of array being returned?

The array element arr [10] doesn't exist. If you try to return something that doesn't exist, you are just asking for trouble. There is no reason for your function to return anything.