我正在尝试用 C 编写一个函数,该函数将打印一个字符串作为参数。这在 C 中甚至可能吗?
我的头文件中有类似的内容,但字符串不是有效标识符。我知道 C 中没有字符串,但是 string.h 类有什么用?
#include <string.h>
#ifndef _NEWMAIN_H
#define _NEWMAIN_H
#ifdef __cplusplus
extern "C" {
#endif
void print (string message){ //this is where i need help
printf("%s", message);
}
#ifdef __cplusplus
}
#endif
#endif /* _NEWMAIN_H */
最佳答案
在 C 中,没有原生的 string
类型。
C 将字符串作为以 null 结尾的 char
数组处理。
例如:
char* string = "this is a string";
string.h
存在以对类型为 char*
的 C 字符串执行字符串操作函数。
使用 printf
打印字符串时, 将传入一个 char*
变量:
char* string_to_print = "Hello";
printf("%s", string_to_print);
有关 C 中字符串的更多信息,Wikipedia page on C strings将是一个好的开始。
关于C编程。如何制作打印字符串的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1414052/