Mat*_*hew 9 c type-conversion char
我有一个char给出的fgets,我想知道如何将它转换为char*.
我确信之前已经发布过,但我找不到一个我想做的事情.任何答案都表示赞赏.
编辑:这是代码.
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");
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*umb 20
好吧,首先,line是一个chars 数组,因此可以像a char *(请参阅comp.lang.c常见问题解答中的重要差异)一样进行操作,因此您无需担心它.
但是,如果你想要回答一般问题......
该&操作是你所需要的:
char c;
char *pChar = &c;
Run Code Online (Sandbox Code Playgroud)
但是,请记住,pChar是指向char的指针,只有在c在范围内时才有效.这意味着你不能从函数中返回pChar并期望它能够工作; 它将指向堆的某些部分,你不能指望它保持有效.
如果要将其作为返回值传递,则需要malloc一些内存然后使用指针来写入c的值:
char c;
char *pChar = malloc(sizeof(char));
/* check pChar is not null */
*pChar = c;
Run Code Online (Sandbox Code Playgroud)
&正如Dancrumb所提到的,使用运算符会给你一个指向角色的指针,但是就像他提到的那样,存在范围阻止你返回指针的问题.
我要添加的一件事是,我想你想要的原因char*是你可以将它用作字符串printf或类似的东西.您不能以这种方式使用它,因为字符串不会被NULL终止.要将a char转换为字符串,您需要执行类似的操作
char c = 'a';
char *ptr = malloc(2*sizeof(char));
ptr[0] = c;
ptr[1] = '\0';
Run Code Online (Sandbox Code Playgroud)
别忘了ptr以后免费!