c - How To Assign char* to an Array variable -


i have started code in c , having quite lot of fun it. ran little problem have tried solutions think of no success. how can assign char* variable array?

example

int main() {     char* sentence = "hello world";      //sentence gets altered...      char words[] = sentence;      //code logic here...      return 0; } 

this of course gives me error. answer appreciated.

turn compiler warnings on , trust says. array initializer must string literal or initializer list. such needs explicit size or initializer. if had explicitly initialized still wouldn't have been assignable in way wrote.

 words = sentence; 

please consult this post quotation c standard.

as of:

how assign char* array variable ?

you can populating "array variable" content of string literal pointed char *, have give explicit length before can copying. don't forget #include <string.h>

char* sentence = "hello world"; char words[32];                //explicit length strcpy (words, sentence); printf ("%s\n", words); 

or in way:

char* sentence = "hello world"; char words[32]; size_t len = strlen(sentence) + 1; strncpy (words, sentence, (len < 32 ? len : 31)); if (len >= 32) words[31] = '\0'; printf ("%s\n", words); 

btw, main() should return int.


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -