Curnelious
Curnelious

Reputation: 1

strcpy on a string pointer gives errors

I have read a lot about the subject and I am confused .

What used to work in a C file ,not working on a cpp file :

 char  *builtinFunctions[20];

Then I get error on the strcpy function here :

void Intepreter::setBuiltIns(char *builtins)
{
   strcpy(builtinFunctions, builtins); // no matching function call to strcpy
}

I probably don't understand the basics here, but why in C++ this will not work ( do i need to use = instead ? )

strcpy(char *, const char*) = thats the structure

if I change the builtinFunctions from being a pointer it works.

EDIT: The reason for being a const before this edit is that I read here : Why is conversion from string constant to 'char*' valid in C but invalid in C++

that char *builtinFunctions[20]; will produce warning when :

builtinFunctions[0]="me";

and it did. I could fix it by removing the const .

Upvotes: 0

Views: 535

Answers (1)

Igor S.K.
Igor S.K.

Reputation: 1039

This is an array of pointers to char.

char  *builtinFunctions[20];

So you call

strcpy(builtinFunctions, builtins);

gets treated as strcpy(char **, char*), not as strcpy(char *dest, const char *src). So you get a mismatch for first parameter type.

EDIT:

So let's suppose builtinFunctions is "an array of words" you wish to populate, with void Intepreter::setBuiltIns(char *builtins) meant to do just that with it's first parameter being a pointer to a new incoming word. (And you're doing this in a C-style manner. Well, up to you.)

Some things to consider.

  1. If you declare an array type arrName[N]; then the array's name being used all alone without index is treated as a variable of type type *arrName. If you type is initially char *, then builtinFunctions by itself is of type char**. That's why your strcpy fails, but strcpy(builtinFunctions[someIndex], builtins); works.

  2. Before invoking strcpy you should consider, if you have a destination space allocated. builtinFunctions[someIndex] is of type char *. Where does it point to? Is it a valid pointer to an allocated space, or a gateway to hell of undefined behaviour strcpy will happily take you to?

Upvotes: 3

Related Questions