Reputation: 423
I would like to pass a string to function like this..
long_var = get_value("long_value");
short_var = get_value("short_value");
Inside the function, I did this..
double get_value(char *get_type){
if (*get_type == "short_value")
{
//calculate and return
}
else if (*get_type == "long_value")
{
//calculate and return
}
}
However, i have an error Error: main.c(334): function argument #1 of type 'flash unsigned char [11]' is incompatible with required parameter of type 'unsigned char *'
I thought that a string was just an array of char and I can call it..
Also, is there a better way to do this..
Thanks..
Upvotes: 0
Views: 1204
Reputation: 476950
String literals are of type const char[]
, which decays to const char *
in the function call, so you should make the signature of your function double get_value(const char *)
.
Second, when you dereference *get_type
, you only get one char, not the entire string! And then you're trying to compare that char to an array (which again decays to a pointer) -- that doesn't work. What you need is strcmp
(or a variant version thereof):
if (!strcmp(get_type, "short_value")) { ... }`
If you prefer, you can say strncmp(get_type, "short_value", 12)
and only compare the initial 12 characters, which is the length of "short_value" including its terminating null byte - not strictly necessary, but it's good to be aware of one's string lengths when using string manipulation functions.
Upvotes: 3
Reputation: 88378
You are going to need to include <string.h>
and change your code to say
if (!strcmp(get_type, "short_value"))
The way things are now, you are comparing a character (*get_type
) with a pointer to a character ("short_value"
).
Upvotes: 6
Reputation: 3803
You should pass constant strings as "const char*" or even "const char * const". Also, c-strings are plain arrays and using == operation on them will just compare pointers, not strings. You should use strcmp function for comparison.
Upvotes: 4