Assalam U Alaikum Guys!
can somebody help me how to convert a string to Char array? like if m having a string=("hello"); and i want to convert it to arr[5]={'h','e','l','l','o'};
is that possible.. or can somebody help me?
Assalam U Alaikum Guys!
can somebody help me how to convert a string to Char array? like if m having a string=("hello"); and i want to convert it to arr[5]={'h','e','l','l','o'};
is that possible.. or can somebody help me?
— and pointed in the right direction. If you need a writable copy (not just a pointer to a literal), copy the bytes into a buffer whose size includes space for the terminating NUL. Below are common, safe patterns and the pitfalls to avoid.
For a fixed buffer on the stack, use a bounded copy that always NUL-terminates, for example with snprintf:
char src[] = "some text";
char buf[32];
snprintf(buf, sizeof buf, "%s", src); snprintf guarantees a NUL byte when sizeof buf > 0 (snprintf(3)). Avoid naive strncpy use without forcing a terminator — it may leave the destination unterminated (strncpy(3)).
For a heap-allocated copy, allocate length+1 and copy the bytes (including the NUL):
size_t n = strlen(src) + 1;
char *copy = malloc(n);
if (copy) memcpy(copy, src, n); That pattern uses strlen and memcpy (strlen(3), memcpy(3)). On POSIX systems strdup does this in one call (strdup(3)).
Checklist and cautions
sizeof to get buffer size only when the object is an array, not when you have a char *.strncpy: it can leave no NUL or fill with padding bytes.snprintf, memcpy + malloc, or strdup for clear, safe semantics.These patterns cover stack and heap copies and address the common off-by-one and termination bugs that come up when converting or copying C strings.
Jump to Post— zeroliken 79Isn't declaring a string in c already a null terminated character array?
Isn't declaring a string in c already a null terminated character array?
Yes, a 'string' already is a character array -- by definition.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.