Home > Software engineering >  cast a char into a char* in C
cast a char into a char* in C

Time:10-12

I have a char array s[11]="0123456789"; and I want to be able to take each digit s[i](using a for loop) and cast it somehow to a char*(I need a char* specifically because I need to use strncat on some other string)

I've been trying to do this for the past 4 hours and I couldn't get anything done.

CodePudding user response:

Unless you're willing to temporarily modify s, or copy the character somewhere else... You're going to have a hard time.

Modify s temporarily.

int main() {
  char s[11] = "0123456789";
  for (int i = 0; i < strlen(s); i  ) {
    // Modify s in place.
    const char tmp = s[i 1];
    s[i 1] = '\0';
    char *substr = &s[i];
    // Do something with substr.
    printf("%s\n", substr);
    // Fix s
    s[i 1] = tmp;
  }
}

Or copy s[i] to a new string.

int main() {
  char s[11] = "0123456789";
  for (int i = 0; i < strlen(s); i  ) {
    // Create a temporary string
    char substr[2];
    substr[0] = s[i];
    substr[1] = '\0';
    // Do something with substr.
    printf("%s\n", substr);
  }
}

Or maybe just don't use strncat?

Assuming you're actually using strncat or similar... Those functions are pretty trivial, especially if you are appending only a single character. You might just create your own version.

void append_character(char *buffer, int buffer_size, char new_character) {
  int length = strlen(buffer);
  if (length   2 < buffer_size) {
    buffer[length] = new_character;
    buffer[length 1]  = '\0';
  } else {
    // No space for an additional character, drop it like strncat would.
  }
}

Or you could do it as a simple wrapper around strncat:

void append_character(char *buffer, int buffer_size, char new_character) {
  char new_string[2] = { new_character, '\0' };
  strncat(buffer, buffer_size, new_string);
}

CodePudding user response:

What you are requesting does not make any sense. A char is a small number. A pointer is the address of some memory. Converting a char to a pointer won't give you a valid pointer, but a pointer that will crash as soon as it is used.

For strncat, you need an array of characters containing a C string. You could create a string by writing char array[2]; (now you have an array with space for two characters), then array[0] = whateverchar; array[1] = 0; and now you have a C string with space for exactly one char and one trailing zero byte.

CodePudding user response:

Yet another idea:

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

int main(void)
{
    char src[11]="0123456789";
    char dest[50]="abc";

    char* p = src;
    int i = 0;
    int len = strlen(src);
    
    for (i = 0; i < len; i  )
    {
        p  ;
        strncat(dest,p,1);
    }
    
    printf("src:  %s\n", src);
    printf("dest: %s\n", dest);

    return 0;
}

Compiled with gcc under Ubuntu:

$ gcc hello_str.c -o hello_str

Output:

$ ./hello_str 
src:  0123456789
dest: abc123456789
  • Related