I tried to assign a String a value in C, but for me it doesn't work... This is, what I tried to do:
#include <stdio.h>
#include <string.h>
int main()
{
char k[25];
k == "Dennis"
printf("My Name is %s", k);
}
Sample Output would be: My Name is Dennis
However, I receive the a warning: warning: comparison of distinct pointer types lacks a cast k == "Dennis";
I tried to find a solution on this website, but could not find one, where it was the same error with assigning a value to a char array (a string) in C
Also tried initializing my char as
char *k[25];
still didn't work...
You are indeed doing a comparison here: k == "Dennis". So the compiler correctly warns you.
You probably meant k = "Dennis"; (fixed the missing semi-colon there). But that won't work either. Because in C arrays are not modifiable lvalues.
So you can either initialize the array:
char k[25] = "Dennis";
or, use strcpy to copy:
strcpy(k, "Dennis");
If you actually have no need for an array, you can simply use a pointer that points to the string literal. The following is valid:
char *k;
k = "Dennis";
printf("My Name is %s", k);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With