在 C 中声明一个字符串/单词变量 [英] Declare a string/word variable in C

查看:24
本文介绍了在 C 中声明一个字符串/单词变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 C 相当陌生,只是想知道如何声明一个单词变量.

I'm fairly new to C, and was just wondering how to declare a word variable.

例如,虽然

int variable;

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

is able to hold only an interger value, I would like to be able to declare a variable that can hold a word, or string, e.g.

string name = "Joe";

string name = "My name is Joe";

然而,这只会使我的程序崩溃,我假设这是因为 string 不存在并且与内存相关的事情有关.

However, this just crashes my program, and I'm assuming it is because string doesn't exist and something to do with memory-ish things.

这是我的全部代码:

#include <stdio.h>

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 个字符,您可以增加或减少它,这取决于您的意愿.

I am just using 30 here assuming the input string fits in 30 char's you can increase or decrease it , it is up to your wish.

这篇关于在 C 中声明一个字符串/单词变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆