c/c++语言开发共享在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 cArray[16] = "Hello"; //will have 16 elements, initialized 5 with hello 

    要么

     char cArray[ ] = "Hello"; //number of char element is 6, considering terminating null. 

    例:

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

    注意: char数组,何时用作字符串 ,必须以null结尾。

      以上就是c/c++开发分享在C中声明一个字符串/单词变量相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/549271.html

      (0)
      上一篇 2021年1月14日
      下一篇 2021年1月14日

      精彩推荐