그래서 두 개의 개별 배열에 저장된 각 요소의 값을 간단히 추가하고 세 번째 배열에 저장해야하는 함수를 작성했습니다.포인터 산술을 사용하여 두 배열의 내용을 추가하고 빈 배열에 저장
문제점이 무엇인지 이해하지 못합니다. 각 포인터에서 참조하는 위치에 저장된 int 값을 더하고 제 3의 빈 배열에 저장합니다.
내 코드는 정상적으로 컴파일되지만 세 번째 배열의 내용을 인쇄 할 때 루프를 실행하면 각 색인에 두 개의 이전 배열 요소의 합계가 포함되어야합니다. 뭐라 구요?
편집 : 내 while 루프가 산술 연산을 수행하도록 수정되었으며 모든 것이 잘 작동합니다. 내 작업 코드는 아래와 같습니다. 다른 사람들을 돕기를 바랍니다. 이 함수에 전달 될 때
#include<iostream>
#include<stdlib.h>
using namespace std;
void arrayAdd(int firstArray[], int secondArray[], int targetArray[], int size){
int *firstPtr = firstArray;
int *secondPtr = secondArray;
int *tragetPtr = targetArray;
while (firstPtr <= &firstArray[size - 1]){
//add the first two array elements
*tragetPtr = (*firstPtr + *secondPtr);
// point to the next location
*firstPtr++;
*secondPtr++;
*tragetPtr++;
}
}
int main() {
int totalElements;
const size_t ARRAY_SIZE = 50;
int firstIntegerArray[ARRAY_SIZE];
int secondIntegerArray[ARRAY_SIZE];
int thirdIntegerArray[ARRAY_SIZE];
cout << "Please enter the total number of elements for your array: ";
cin >> totalElements;
for(int i = 0; i < totalElements; i++){
cout << "Please enter a value for the first array at index " << i << ": ";
cin >> firstIntegerArray[i];
}
for(int i = 0; i < totalElements; i++){
cout << "Please enter a value for the second array at index " << i << ": ";
cin >> secondIntegerArray[i];
}
//run our arrayAdd function
arrayAdd(firstIntegerArray, secondIntegerArray, thirdIntegerArray, totalElements);
cout << "The conents of your two arrays added together is; " << endl;
for(int i = 0; i < totalElements; i++){
cout << thirdIntegerArray[i] << ", ";
}
return 0;
}
arrayAdd의 sizeof (firstArray)는 사용자가 생각하는 것과 다릅니다. 대신 함수 매개 변수로 몇 개의 요소가 있는지 전달하십시오. – mark