Home > Enterprise >  Convert integer array into string
Convert integer array into string

Time:10-12

I have an integer array:

int s3[] = {97, 115, 100, 102, 103, 49, 50, 51, 37, 36, 33};

and I need its string value like "asdfg123%$!"

something like this:

printf ("%s", s4);   // and output should be => asdfg123%$!

CodePudding user response:

Copy the array item by item in a loop and store each value in a char. Then null terminate that char array so that it becomes a string. Or alternatively don't declare s3 as int to begin with.

CodePudding user response:

You want something like this:

#include <stdio.h>
#include <string.h>

int main() {
  int s3[] = { 97, 115, 100, 102, 103, 49, 50, 51, 37, 36, 33 };
  // make sure s3 does not contain values above 127 (or 255 depending on
  // your platform).

  // temporary storage for the null terminated string
  char temp[100];   // must make sure s3 has no more than 99 elements

  // copy the values in s3 to temp as chars
  int i;
  for (i = 0; i < sizeof(s3)/sizeof(int) ; i  )
  {
    temp[i] = s3[i];
  }

  // null terminate 
  temp[i] = 0;   

  // now we can print it with `printf` and `%s` because
  // now `temp` is a null terminated string.
  printf("%s\n", temp);
}

sizeof(s3) is the size of the s3 array in bytes, sizeof(int) is the size of an int, therefore sizeof(s3)/sizeof(int) is the number of elements in the s3 array.


Advanced knowledge (slighly above beginner level):

  • Actually you should even write sizeof(s3)/sizeof(*s3) which is cleaner because we don't need to repeat the int type.

  • Instead of having a fixed size char temp[100]; you could allocate the memory dynamically using malloc with the size sizeof(s3)/sizeof(*s3) 1 ( 1 for the null terminator).

  •  Tags:  
  • cgcc
  • Related