Define char array pointer with size
Solution 1
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()
.
Solution 2
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
Solution 3
Why not to use this:
const char * string;
...
string = "words";
printf("%s",string);
(or your question is not clear)
J V
Updated on June 28, 2022Comments
-
J V almost 2 years
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);
-
J V almost 13 yearsI forgot to mention, the assigning and accessing has to be performed in a loop (Hence the prior declaration)
-
J V almost 13 yearsThat will do, I was hoping to avoid it but it seems grand.
-
Oliver Charlesworth almost 13 years+1: Agreed. This answers the question as stated. If it's not appropriate, then the question needs to be clarified.