I've written a program that copies one array into another using array indexing and pointers. The problem I'm trying to solve is when I go to print the original array and the new array for the pointer method I get the same thing(i.e the copied array) when what I really want is the original array printed and then the new copied array. (much clearer below)
CODE
/*
Program to copy the contents of a one-dimensional character array
into another one-dimensional character array using
2 different methods(Pointers and Array Indexing)
*/
#include <stdio.h>
// Declaring both functions
void copyArrayIndexWay(char * const newArray1, const char * const originalArray1);
void copyPointerWay(char *newArray2, const char *originalArray2);
// Little explanation - I declared both arrays here instead of in my main so that my variable size can get the size of
// either array which is used in the for loops for both functions. Hence why I had to delcare it all here if I
// wanted both functions to be able to access the size variable
char array1[] = "deeznuts";
char array2[] = "gotem";
// Declaring variables i and size here which will allow both functions to call them
int size = sizeof(array1), i = 0;
int main(){
// copy 1 into 2
copyArrayIndexWay(array2, array1);
copyPointerWay(array2, array1);
}
// Functin to copy contents using array indexing
void copyArrayIndexWay(char * const newArray, const char * const originalArray){
printf("--Copying Using Array Indexing--\n");
printf("Original Array: %s\n", newArray);
for (i=0; i<size; i++){
newArray[i] = originalArray[i];
}
printf("New Array: %s\n\n\n", newArray);
}
// Function to copy contents using pointers
void copyPointerWay(char *newArray2, const char *originalArray2){
// declare pointers and assign both arrays to a pointer each
const char *orig_arrayPtr;
orig_arrayPtr = originalArray2; // array1
char *new_arrayPtr;
new_arrayPtr = newArray2; // array2
printf("--Copying Using Pointers--\n");
printf("Original Array: %s\n", new_arrayPtr);
for (i=0; i<size; i++){
new_arrayPtr[i] = orig_arrayPtr[i];
}
printf("New Array: %s\n", new_arrayPtr);
}
OUTPUT
--Copying Using Array Indexing--
Original Array: gotem
New Array: deeznuts
--Copying Using Pointers--
Original Array: deeznuts
New Array: deeznuts
The copying using pointers should print the same original array as the array indexing method but for some reason it prints the new array instead. Any advice or explanation on why this is happening would be much appreciated, thanks :)