Question

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.

Was it helpful?

Solution

There are two ways to do this. As written, maxArray is 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 the strcpy standard library function.

char maxArray[50];

strcpy(findMax(aArray, bArray), maxArray);

The other way is to change the declaration of maxArray to be a char *, a pointer. Pointers can be assigned to directly without having to loop or invoke a function.

char *maxArray;

maxArray = findMax(aArray, bArray);

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 from aArray and bArray. 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, maxArray becomes an indirect reference to either aArray or bArray. It's not a copy of one of those arrays, it points to one of them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top