I cannot figure out what I'm doing wrong in the following code:

char* charArray[3];
strcpy(charArray[0],"wn");
strcpy(charArray[1],"chair");
strcpy(charArray[2],"-over");

Thanks a lot for the help!

Recommended Answers

All 3 Replies

char* charArray[3];
strcpy(charArray[0],"wn");
strcpy(charArray[1],"chair");
strcpy(charArray[2],"-over");

You allocate memory for the pointers to the strings, but not for the characters themselves. Try replacing replacing the first line with this:

char charArray[3][20];

Make sure none of your strings have more than 19 characters though!

I don't have any syntax error before this code, but yet after I wrote the definition line for the pointer array, I got the following one:

syntax error : missing ';' before 'type'

If the code that I posted is commented out, there are no compilation errors. What can possibly be wrong, especially now after I added the malloc code before each strcpy command. And the malloc allocates memory for each word separately into a new element of the array.

I don't have any syntax error before this code, but yet after I wrote the definition line for the pointer array, I got the following one:

syntax error : missing ';' before 'type'

If the code that I posted is commented out, there are no compilation errors. What can possibly be wrong, especially now after I added the malloc code before each strcpy command. And the malloc allocates memory for each word separately into a new element of the array.

The code you posted should compile fine, provided you have #included the cstring library and have handled any namespace problems (i.e. you're using namespace std and haven't overridden it or whatever.

It won't RUN correctly if you haven't added malloc statements or whatever between lines 1 and 2, but I can't think of anything that would give you a compile error, but it'll compile fine.

So the problem is with code you haven't posted. Make sure strcpy is defined (again add the "#include <cstring>" and "using namespace std" lines at the top (may not need the namespace but it can't hurt). If you're using malloc, you need to #include cstdlib.

Can't comment beyond that as I'd need to see the code before this and the full error message. The code you posted should compile. Look for any missing semicolons and/or extra/missing brackets.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.