Reputation: 67
I am trying to create a program in C that calculates the sum of two int arrays using pointers. Here is an example of what I want to do:
int a[] = {1,2,3,4}
int b[] = {1,2,3,4,5,6}
int c[] = sumArrays(a,b,4,6)
Output : c = {2,4,6,8,5,6}
The problem is my output is different, it shows:
Output : c = {2,4,6,8}
Any idea what did I do wrong and how to correct it ? Here is my code :
#include <stdio.h>
#include <stdlib.h>
int* sumArrays(int *arr1, int *arr2, int dim1,int dim2)
{
int *ret = NULL;
if(dim1<dim2) ret = (int*) malloc(dim2*sizeof(int));
else ret = (int*) malloc(dim1*sizeof(int));
if(ret)
{
if(dim1<dim2) {
int i = 0;
for (i = 0;i < dim1;i++) {
ret[i] = arr1[i] + arr2[i];
}
for (i = dim1; i < dim2;i++) {
ret[i]=arr2[i];
}
} else {
int i = 0;
for (i = 0;i < dim2;i++) {
ret[i] = arr1[i] + arr2[i];
}
for (i = dim2; i < dim1;i++) {
ret[i]=arr1[i];
}
}
}
return ret;
}
int main()
{
int *a[] = {1,2,3,4};
int *b[] = {1,2,3,4,5,6};
int *c = sumArrays(a,b,4,6);
printf("c = ");
int i;
for (i = 0; i < sizeof(c); i++) {
printf("%d,",c[i]);
}
}
Upvotes: 1
Views: 7105
Reputation: 20891
You have problem about using pointers.
int *a[] = {1,2,3,4}; // a is an array of pointers to integers.
int *b[] = {1,2,3,4,5,6}; // b is an array of pointers to integers.
By doing this, you are declaring array of pointers to integers
. So, it most likely causes compiler warning or error depending on your compile settings like, initialization makes pointer from integer without a cast. When you are passing the actual arguments to formal parameters, it causes same warning as well. Your main should be like this,
int main()
{
int a[] = {1,2,3,4};
int b[] = {1,2,3,4,5,6};
int sizeA = sizeof(a) / sizeof(*a);
int sizeB = sizeof(b) / sizeof(*b);
int *c = sumArrays(a,b,sizeA,sizeB);
printf("c = ");
int i;
for (i = 0; i < (sizeA < sizeB ? sizeB : sizeA); i++) {
printf("%d,",c[i]);
}
}
Upvotes: 1
Reputation: 8534
Sizeof c will always return 4 for 32-bit system and 8 for 64-bit, because c is a pointer to int.
So to print the result array you should write:
for (i = 0; i < 6; i++) {
Upvotes: 5