Reputation: 11936
I want a cross between the two declarations below:
char string[6];
char * string;
I need a pointer with a fixed size and I don't want to use malloc
for something this simple.
All this char array needs to do is be assigned a value and have it retrieved by a function as seen below. (But in a loop hence the separate declaration) What is the best way to do this?
string = "words";
printf("%s",string);
Upvotes: 3
Views: 18809
Reputation: 612954
Since you have now stated that you can't use @nightcracker's solution, I think you need to use strncpy()
to assign to the string.
char string[6];
/* .... loop code */
strncpy(string, "words", 6);
printf("%s", string);
I guess that in a real program you wouldn't be using a string literal, hence the need for strncpy()
.
Upvotes: 3
Reputation: 117681
Define a constant array of which the size gets counted by the initializer:
const char string[] = "words";
If you just want a pointer to a fixed size amount of memory that is small, just use it like this:
const int STR_LEN = 10;
char str[STR_LEN];
... loop, etc
strncpy(string, "1234567890", STR_LEN);
... etc
Upvotes: 4
Reputation: 27460
Why not to use this:
const char * string;
...
string = "words";
printf("%s",string);
(or your question is not clear)
Upvotes: 1