在C中声明一个字符串/单词变量

时间:2014-12-18 13:41:49

标签: c variables

我对C很新,只是想知道如何声明一个单词变量。

例如,而

int variable;

只能保存一个整数值,我希望能够声明一个可以保存单词或字符串的变量,例如。

string name = "Joe";

string name = "My name is Joe";

然而,这只会让我的程序崩溃,我认为这是因为string不存在而且与内存有关。

这是我的全部代码:

#include <stdio.h>

int main () {
    printf("What is your name?\n");
    **string** name;

    scanf("%s", &name);

    printf("Hello, %s", name);

    getch();
    return 0;
    }

5 个答案:

答案 0 :(得分:2)

char name[30]; /* pre-allocated memory of stack */

然后扫描该值。 或

char *name = malloc(sizeof(char) * 30); /* run-time allocation on heap */

我只是在这里使用30,假设输入字符串适合30个字符,你可以增加或减少它,这符合你的愿望。

答案 1 :(得分:2)

声明你的数组如下:

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/

答案 2 :(得分:1)

您可以使用该数组存储该值。声明数组。

喜欢这个char name[20];

scanf("%s", name);

答案 3 :(得分:1)

这将存储最大值。 50个字符长的字符串

char word [50+1];

但是如果你想在运行时定义大小,请使用:

char *word = (char*)malloc(sizeof(char)*length);

答案 4 :(得分:0)

你有两种选择。

  1. 静态分配char数组。
  2. 实施例。

    char cArray[16] = "Hello";  //will have 16 elements, initialized 5 with hello
    

    char cArray[ ] = "Hello";   //number of char element is 6, considering terminating null.
    
    1. 指向具有动态分配内存的char变量的指针。
    2. 示例:

      char * cPtr = NULL;
      cPtr  = malloc(16);    //again, 16 char elements
      

      注意:char数组,何时用作字符串,必须以空值终止。

相关问题