Home > Mobile >  Copy char to a array with a function - C
Copy char to a array with a function - C

Time:11-08

Function.h

void copyArray(char, char);

Main.cpp

void copyArray(char word[], char temp[]) {
    for (int i = 0; i < 50; i  ) temp[i] = word[i];
}

auther.cpp

copyArray("CHAMPAGNE", char myArray[50]);

Output

C2664   'void copyArray(char,char)': cannot convert argument 1 from 'const char [10]' to 'char'

already googled the error, look for function precoded, found nothing I must not use string

CodePudding user response:

First: The declaration and definition don't match since the declaration specifies that the function takes two chars while the definition specifies that the function takes two char*:

void copyArray(char, char); // declaration

void copyArray(char word[], char temp[]) { // definition
    for (int i = 0; i < 50; i  ) temp[i] = word[i];
}

You need to make the declaration the same as the definition:

void copyArray(char[], char[]); // or void copyArray(char*, char*);

... but, in order to copy from string literals, you need to make the first argument take a const char* since string literals consists of const chars.

void copyArray(const char word[], char temp[]);

There are however not 50 chars in "CHAMPAGNE" so trying to copy that many will make your function access "CHAMPAGNE" out of bounds (with undefined behavior as a result). You shouldn't copy beyond the \0 terminator:

void copyArray(const char* word, char* temp) {
    do {
        *temp   = *word;
    } while(*word   != '\0'); // stop when \0 has been copied
}

But make sure that temp has enough room for the larget string you try to copy into it.

If you want to copy CHAMPAGNE into myArray, you need to declare myArray first and supply it as an argument to the function:

char myArray[50];
copyArray("CHAMPAGNE", myArray);

Demo

  • Related