Reputation: 804
Compiler tell me "incompatibles type in assignments of char* to char[32]" this is my code:
char* generalOperations[2]={"Off","On"};
void test(){
char value[32];
switch(swapVariable){
case 0:
value=generalOperations[0]; //<==Error HERE!
break;
}
}
[Solved]:
strcpy(value,generalOperations[0]);
Upvotes: 1
Views: 493
Reputation: 121961
You can't assign arrays. You can either change the type of value
to a char*
or copy the content of generalOptions[0]
into value
. If you are going to copy the content, then you need to ensure that value
has enough space to hold the content of the element in generalOperations
.
Modifying a string literal is undefined behaviour, by changing the type to const char*
the compiler can detect any attempt to modify one of the entries in generalOperations
instead of experiencing odd behaviour at runtime:
const char* generalOperations [2]={"Off","On"};
const char* value;
Note you don't have to specify the number of elements in the array if you are initialising it:
const char* generalOperations [] = {"Off","On"};
Or, if this really is C++ you can make value
a std::string
instead and just assign to it which will copy the generalOperations
element.
As C++ appears to really be the language and C++11 features are permitted instead of using a switch
you could create a std::map
that associates the int
values with the std::string
:
#include <iostream>
#include <string>
#include <map>
const std::map<int, std::string> generalOperations{ {17, "Off"},
{29, "On" } };
int main()
{
auto e = generalOperations.find(17);
if (e != generalOperations.end())
{
// Do something with e->second.
std::cout << e->second << "\n";
}
return 0;
}
Demo: http://ideone.com/rvFxH.
Upvotes: 3
Reputation: 646
Use std::string
instead of char*
and std::array<T, N>
instead of T[N]
. Both are type safe (as opposed to memcpy
), both are in modern C++ style and both are directly assignable using the assignment operator.
#include <array>
#include <string>
std::array<std::string, 2> generalOperations{"Off", "On"};
void test() {
std::string value;
switch(swapVariable) {
case 0: value = generalOperations[0]; break;
}
}
Upvotes: 8
Reputation: 448
Your assignment is wrong, since you cannot assign a char * to char array instead of using this assignment you can use strcpy().
Upvotes: -1
Reputation: 8027
#include <string.h>
...
strcpy(value, generalOptions[0]);
You cannot assign arrays in C/C++. There are functions do to that for you. If your char array represents a C style string (i.e. a null terminated sequence of characters), then there are more specialist functions for that as well. strcpy
is one of those functions.
Upvotes: 0