Reputation: 7
#define NUM_EL 10
int randomArray1[NUM_EL];
int randomArray2[NUM_EL];
int sumArray[NUM_EL];
//Function Protocol
int IntializeArrayWithPointers(int, int, int);
void DisplayArrayDataWithPointers(int);
int AddTwoArraysWithPointers(int,int,int);
int main()
{
*randomArray1=IntializeArrayWithPointers(randomArray1, 0, 1);
*randomArray2=IntializeArrayWithPointers(randomArray2, 10, 11);
*sumArray=AddTwoArraysWithPointers(randomArray1,randomArray2,sumArray);
DisplayArrayDataWithPointers(randomArray1);
DisplayArrayDataWithPointers(randomArray2);
DisplayArrayDataWithPointers(sumArray);
}
int IntializeArrayWithPointers(int pointer1[], int a, int b)
{
int i;
int* pa;
pa= pointer1;
for(i = 0; i < NUM_EL; i++)
{
pa[i] = rand()%(b-a+1)+a;
}
}
void DisplayArrayDataWithPointers(int* p)
{
int i;
for(i = 0; i < NUM_EL; i++)
{
printf("arrayEL[%d] = %d at %p \n",i,p[i],&p[i]);
}
printf("\n");
}
int AddTwoArraysWithPointers(int a[],int b[],int c[])
{
int i;
int *pa;
int *pb;
int *pc;
pa = a;
pb = b;
pc = c;
for(i=0;i<NUM_EL;i++)
{
*(pc +i)=*(pa +i)+*(pb +i);
}
}
The first element, when printing the array, always shows up as the value of NUM_EL
. That happens even when I set it for rand
s between 0 and 1. The rest are random like they are supposed to be. The code works perfect except for the 1st element of each array including the sum array.
Upvotes: 0
Views: 80
Reputation: 503
*randomArray1=IntializeArrayWithPointers(randomArray1, 0, 1);
This statement sets return value of function to first element of randomArray1.that why it's getting modified.
Remove the assignment and declare IntializeArrayWithPointers() with return type as void.
Upvotes: 0
Reputation: 110128
When you call the function, you do it like this:
*randomArray1=IntializeArrayWithPointers(randomArray1, 0, 1);
This will assign the return value of the function to the first element of randomArray1
. Since you don't want this, you should remove the assignment.
In fact, the function doesn't even return a value so the behavior is undefined. You should declare the function as returning void
.
Another issue is that the types in your function declarations don't match the types in the function definitions - always make sure they match, and pay attention to compiler warnings which would alert you to this.
Upvotes: 4