So this is a homework assignment, there might be come constraints that are ridiculous but please bear with me. This is just a simple function but drawn out. I need to return a character array via assignment operator but it doesn’t seem to be working at all. I’ve tried pointers, but no luck.
#include <iostream>
using namespace std;
char* findMax(char*, char*);
int main()
{
char aArray[50] = "Hello World",
bArray[50] = "dlroW olleH",
maxArray[50];
maxArray[50] = findMax(aArray, bArray);
cout << maxArray << " is the bigger of the 2 strings" << endl;
return 0;
}
char* findMax(char* strA, char* strB){
char* maxStr;
if(strcmp(strA, strB) < 1)
maxStr = strB;
else
maxStr = strA;
return maxStr;
}
if I cout the return value of findMax() it does print out the value of bArray, but geting it into maxArray via assignment operator isn’t working at all.
There are two ways to do this. As written,
maxArrayis an array of characters. Arrays can’t be directly assigned to. Instead you need to copy each character one by one. You could do that with a loop, or by calling thestrcpystandard library function.The other way is to change the declaration of
maxArrayto be achar *, a pointer. Pointers can be assigned to directly without having to loop or invoke a function.The difference between this and the first solution is subtle, but important. With
char maxArray[50]you are actually allocating a third array of 50 characters, separate fromaArrayandbArray. This array has its own storage, its own 50 bytes of memory.In the second you don’t create a third array. You merely create a pointer which can point to other arrays already in existence. After the assignment,
maxArraybecomes an indirect reference to eitheraArrayorbArray. It’s not a copy of one of those arrays, it points to one of them.