Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Convert char into char*

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");
}
like image 407
Matthew Avatar asked Jun 29 '12 20:06

Matthew


2 Answers

Well, first of all, line is an array of chars 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;
like image 92
Dancrumb Avatar answered Nov 15 '22 16:11

Dancrumb


Using the & operator will give you a pointer to the character, as Dancrumb mentioned, but there is the problem of scope preventing you from returning the pointer, also as he mentioned.

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

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

Don't forget to free ptr later!

like image 23
Daniel Avatar answered Nov 15 '22 15:11

Daniel