ironicaldiction
ironicaldiction

Reputation: 1207

character array to string in C?

I want to turn an array of characters into ONE string.

Example:

char foo[2] = {'5', '0'}; --> char* foo = "50";

What would be the best way to go about doing this in C? The problem stems from a larger problem I'm having trying to extract a substring from command line input. For example, I want to make argv[1][0] and argv[1][1] into ONE string so that if the program was run like this...

$ ./foo 123456789

I could assign "12" to a char* variable.

Upvotes: 0

Views: 420

Answers (6)

pb2q
pb2q

Reputation: 59657

Rewrite your example since you can't initialize a char[] with multiple literal strings:

char foo[3] = { '5', '0', '\0' }; // now foo is the string "50";

Note that you need at least 3 elements in your array if foo is to hold the string "50": the additional element is for the null-terminating character, which is required in C strings. We The above is equivalent to:

char foo[3] = "50";

But you don't need this to extract the first two characters from argv[1], you can use strncpy:

char foo[3];
foo[0] = '\0';

if ((argc > 1) && (strlen(argv[1]) >= 2)
{
    // this copies the first 2 chars from argv[1] into foo
    strncpy(foo, argv[1], 2);
    foo[2] = '\0';
}

Upvotes: 3

chrisaycock
chrisaycock

Reputation: 37938

Something like:

char* foo_as_str = malloc(3);
memset(foo_as_str, 0, 3);
strncpy(foo_as_str, argv[1], 2);

Upvotes: 3

Jack
Jack

Reputation: 16724

Try by using strcat().

  char *foo[2] = {"5", "0"}; /* not the change from foo[x] to *foo[x] */ 
  size_t size = sizeof(foo) / sizeof(foo[0]);
  char *buf = calloc(sizeof(char), size + 1);
    if(buf) {
      int i;
      for(i = 0; i < size; ++i)
    strcat(buf, foo[i]);
      printf("buf = [%s]\n", buf);
    } else {
      /* NO momeory. handling error. */
    }

Output:

buf = [50]

Upvotes: 0

mathematician1975
mathematician1975

Reputation: 21351

You can use strcat although you must ensure that the destination buffer is large enough to accomodate the resultant string.

Upvotes: 1

Jon
Jon

Reputation: 437854

To make a string you will need to add a null terminating byte after the two characters. This means that the memory address following them needs to be under your control so that you can write to it without messing up anyone else. In this case, to do that you will need to allocate some additional memory for the string:

int length = 2; // # characters
char* buffer = malloc(length + 1); // +1 byte for null terminator
memcpy(buffer, foo, length); // copy digits to buffer
buffer[length] = 0; // add null terminating byte

printf("%s", buffer); // see the result

Upvotes: 1

user529758
user529758

Reputation:

Check out the man page of strcat. Mind overwriting constant strings.

If you want just put chars together to form a string, let you do that as well:

char foo[3];
foo[0] = '1';
foo[1] = '2';
foo[2] = 0;

Upvotes: 2

Related Questions