C Convert char to char *

I have a char that is specified from fgets and I would like to know how I can convert it to char* .

I am sure that this was published earlier, but I could not find the one that was doing what I wanted to do. Any answer is welcome.

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"); } 
+7
source share
2 answers

Well, firstly, line is a char array, so it can be manipulated in much the same way as char * (see comp.lang.c Frequently Asked Questions for important differences), so you don't need to worry about that.

However, if you want an answer to a general question ...

The & operator is what you need:

 char c; char *pChar = &c; 

However, keep in mind that pChar is a pointer to char and will only be valid when c is in scope. This means that you cannot return pChar from a function and expect it to work; this will point to some part of the heap, and you cannot expect it to remain valid.

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

 char c; char *pChar = malloc(sizeof(char)); /* check pChar is not null */ *pChar = c; 
+16
source

Using the & operator will give you a pointer to a character, as Dankrum mentioned, but there is a problem with the area that prevents the pointer from returning, just like it mentioned.

One thing I should add is that I assume that the reason you want char* is to use it as a string in printf or something like that. You cannot use it that way because the string will not be NULL terminated. To convert a char to a string, you will need to do something like

 char c = 'a'; char *ptr = malloc(2*sizeof(char)); ptr[0] = c; ptr[1] = '\0'; 

Remember to release ptr later!

+4
source

All Articles