ProjectPaatt
ProjectPaatt

Reputation: 15

typedef of character array and use in functions

I want a type of cstring with a fixed maximum length, lets say 5. I would also like to be able to use the standard cstring functions if possible. However with this, i get alot of problems with function parameters. I'm not really familiar with typedef yet but im not sure if this is the wrong approach or maybe im just missing something. C++ (mingw-w64)

typedef char Name[5];
std::ostream& operator<<(std::ostream& os, Name& car)
{
    os << car;
    return os;
}

void Change(Name str)
{
    str[2] = '0';
}
Name ChangeRtn(Name str)
{
    str[2] = '1';
    return str;
}
void ChangeCat(Name * strp)
{
    strcat(strp,"3");
}
int main ()
{
    Name test = "abcd";
    Change(test);
    std::cout << test  << std::endl;

    Name test2 = ChangeRtn(test);
    std::cout << test2 << std::endl;

    Name * test3;
    //*test3 = "12"; //incompatible types... make a operator= func
    strcpy (*test3,"12"); //a temp replacement of operater=?
    ChangeCat(test3);
    std::cout << test3 << std::endl;

    return 0;
}

returns with error...

typedef.cpp:15:24: error: 'ChangeRtn' declared as function returning an array
 Name ChangeRtn(Name str)
                        ^
typedef.cpp: In function 'void ChangeCat(char (*)[5])':
typedef.cpp:22:17: error: cannot convert 'char (*)[5]' to 'char*' for argument '1' to 'char* strcat(char*, const char*)'
  strcat(strp,"3");
                 ^
typedef.cpp: In function 'int main()':
typedef.cpp:30:29: error: 'ChangeRtn' was not declared in this scope
  Name test2 = ChangeRtn(test);
                             ^

Upvotes: 0

Views: 459

Answers (1)

Edward Strange
Edward Strange

Reputation: 40859

First, you need to pick your language. Either C or C++.

Next...yeah, you can't return arrays from functions. You can do this as workaround:

struct ArrReturn { char arr[5]; };

This type can then be returned. Don't ask me why that and not array directly.

I'm answering from the perspective of C++, not C.

Upvotes: 1

Related Questions