convert an array to a string in C
Code snippet on how to convert an array to a string in C
#include <stdio.h>
#include <string.h>
int main()
{
char arr[20] = "hello, world";
char str[20];
int i;
/* copy the contents of arr[] to str[] */
for(i = 0; arr[i] != '\0'; ++i) {
str[i] = arr[i];
}
str[i] = '\0';
printf("string = %s", str);
return 0;
}
This code converts an array to a string in C. First, the code creates two character arrays, one named arr[] and the other named str[]. Then, the for loop goes through the array arr[] and copies each element one by one to the array str[]. Finally, printf prints out the str[] array, which is a string. The functions strlen and strcpy can also be used to achieve the same result.