由于未知原因,我需要知道如何将标准替换为char a[10];(string a;是的,我在 CS50 中看到过)。那么,如何创建自己的变量类型命名string?
4 回答
放大@Lundin 在他的回答中所说的话:
One of the things that makes C hard to learn -- especially for students coming from other languages -- is that C does not have a first-class "string" type. Important as they are, strings in C are cobbled together out of arrays of char, and often accessed via char * pointers. The cobbling together is performed by a loose collaboration between the compiler, the programmer, and library functions like strcpy and printf.
Although I said that "strings are cobbled together out of arrays of char, and often accessed via char * pointers", this does not mean that C's string type is char [], and it also does not mean that C's string type is char *.
If you imagine that C has a first-class string type, handled for you automatically by the language just like char, int, and double, you will be badly confused and frustrated. And if you try to give yourself a typedef called string, this will not insulate you from that confusion, will not ease your frustration, will not make your life easier in any way. It will only cloud the issue still further.
它就像typedef char string[10];.
但请不要这样做。在 typedef 后面隐藏数组或指针是非常糟糕的做法。代码变得更难阅读,你从中得不到任何好处。请参阅typedef 指针是个好主意吗?- 相同的论点适用于数组。
命名隐藏数组特别糟糕,string因为这是 C++ 使用的确切拼写std::string。
请注意,CS50 是一门糟糕的课程,因为它教你这样做。SO 社区已经厌倦了向这门课程的受害者“不教”坏习惯。远离有问题的互联网教程。
如果要创建某种方式的自定义字符串类型,正确且正确的方法是改用结构。
C 中的用户定义类型是结构、联合、枚举和函数。而且似乎您还可以在列表中包含数组。
例如
struct Point
{
int x;
int y;
};
或者
enum Dimension { N = 100 };
Point a[N];
在此示例中,数组类型为Point[N].
事实上,任何派生类型(包括指针)都可以被视为用户定义类型。C 标准没有定义和使用 tern 用户定义类型。
用户定义的类型是以下之一struct:union或enum。例如struct:
struct worker {
int id;
char firstName[255];
char lastName[255];
};
创建实例:
struct worker w1 = { 1234, "John", "Smith" };