Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a value to a char array (String) in C [duplicate]

Tags:

c

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...

like image 987
Ayibogan Avatar asked Feb 10 '26 19:02

Ayibogan


1 Answers

  1. You are indeed doing a comparison here: k == "Dennis". So the compiler correctly warns you.

  2. 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);
like image 72
P.P Avatar answered Feb 12 '26 14:02

P.P