在C中声明一个字符串/单词变量
我对C很新,只是想知道如何声明一个单词变量。
例如,虽然
int variable;
能够只保存一个整数值,我希望能够声明一个可以保存单词或字符串的变量,例如
string name = "Joe";
要么
string name = "My name is Joe";
但是,这只会让我的程序崩溃,而我认为这是因为string
不存在而且与内存有关。
这是我的整个代码:
#include int main () { printf("What is your name?\n"); **string** name; scanf("%s", &name); printf("Hello, %s", name); getch(); return 0; }
char name[30]; /* pre-allocated memory of stack */
然后在。或中扫描该值
char *name = malloc(sizeof(char) * 30); /* run-time allocation on heap */
我只是在这里使用30,假设输入字符串适合30个字符,你可以增加或减少它,这符合你的愿望。
声明您的数组如下:
char name[20]; //^^Here you can choose what you want!
另外我会读取字符串如下:
scanf(" %s", &name); //^See the space here! The space is there so if a '\n' is still in the buffer it doesn't get read in for the name!
顺便说一句:也许你想看看这里: http : //www.cplusplus.com/doc/tutorial/
这将存储最大值。 50个字符长的字符串
char word [50+1];
但是如果要在运行时定义大小,请使用:
char *word = (char*)malloc(sizeof(char)*length);
您可以使用该数组来存储该值。 声明数组。
喜欢这个char name[20];
scanf("%s", name);
你有两个选择。
- 静态分配的
char
数组。
例。
char cArray[16] = "Hello"; //will have 16 elements, initialized 5 with hello
要么
char cArray[ ] = "Hello"; //number of char element is 6, considering terminating null.
- 指向具有动态分配内存的
char
变量的指针。
例:
char * cPtr = NULL; cPtr = malloc(16); //again, 16 char elements
注意: char
数组,何时用作字符串 ,必须以null结尾。