我想在C中創建一個程序,它使用指針計算兩個int數組的總和。 這裏是我想要做的一個例子:在C中使用指針的兩個數組的總和
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}
問題是我的輸出是不同的,它表明:
Output : c = {2,4,6,8}
任何想法,我做了什麼錯誤以及如何糾正呢? 這是我的代碼:
#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]);
}
}
不要標記C++,否則,你將不得不使用'std :: vector'。 – Jarod42
您還需要將'int * a []'更改爲'int a []'。 – Shibli
另一方面,你應該得到'c = {2,4,6,8,}',而不是'c = {2,4,6,8}' – anishsane