Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I initialize string after declaration?

Tags:

c

Can I initialize string after declaration?

char *s;
s = "test";

instead of

char *s = "test"; 
like image 942
user1301568 Avatar asked Jul 23 '12 14:07

user1301568


2 Answers

You can, but keep in mind that with that statements you are storing in s a pointer to a read-only string allocated elsewhere. Any attempt to modify it will result in undefined behavior (i.e., on some compilers it may work, but often will just crash). That's why usually you use a const char * for that thing.

like image 181
Matteo Italia Avatar answered Oct 03 '22 17:10

Matteo Italia


Yes, you can.

#include <stdio.h>

int 
main(void)
{
    // `s' is a pointer to `const char' because `s' may point to a string which
    // is in read-only memory.
    char const *s;
    s = "hello";
    puts(s);
    return 0;
}

NB: It doesn't work with arrays.

#include <stdio.h>

int 
main(void)
{
    char s[32];
    s = "hello"; // Syntax error.
    puts(s);
    return 0;
}
like image 39
md5 Avatar answered Oct 03 '22 17:10

md5