C Convert char into char*

c, char, type-conversion

Solution

Well, first of all, `line` is an array of `char`s and so can be manipulated in much the same way as a `char *` (See comp.lang.c FAQs for important differences), so you don't need to worry about it.

However, in case you want an answer to the general question...

The `&` operator is what you need:

char c;
char *pChar = &c;

However, bear in mind that pChar is a pointer to the char and will only be valid while c is in scope. That means that you can't return pChar from a function and expect it to work; it will be pointing to some part of the heap and you can't expect that to stay valid.

If you want to pass it as a return value, you will need to malloc some memory and then use the pointer to write the value of c:

char c;
char *pChar = malloc(sizeof(char));

/* check pChar is not null */

*pChar = c;

Problem

I have a `char` that is given from `fgets`, and I would like to know how I can convert it into a `char*`. I am sure this has been posted before, but I couldn't find one that was doing quite what I wanted to do. Any answer is appreciated. EDIT: Here is the code. ``` char *filename = "file.txt"; FILE *file = fopen(filename, "r"); if(file != NULL) { char line[260]; char *fl; while(fgets(line, sizeof line, file) != NULL) { // here I combine some strings with the 'line' variable. str_replace(line, "\"", "\"\""); // A custom function, but it only takes char*'s. } printf(fl); printf("\n"); } else { printf(" -- *ERROR* Couldn't open file.\n"); } ```

Original source