【问题标题】:How to assign new string values in C [duplicate]如何在C中分配新的字符串值[重复]
【发布时间】:2017-04-14 04:34:31
【问题描述】:

我的简单计算器正在尝试显示用户选择的操作。我知道在 C 中,字符串必须声明为一维字符数组。

int a, b;
int oper; //operation number
char operName[15];

printf("\nEnter two numbers: ");
scanf("%d%d", &a, &b);
printf("\nYou entered: %d and %d", a, b);

printf("\nChoose operation:"
        "\n1 = +"
        "\n2 = -"
        "\n3 = x"
        "\n4 = /");
scanf("%d", &oper);

代码编译并运行。但是在执行 switch 块时,它会停止工作。我正在使用 switch 选择适当的操作名称,并将其分配给 operName(这样我就可以在执行实际操作之前显示选择的操作)。

switch(oper){
    case 1:
        operName == "Addition";
        break;  
    .
    .
    .
    default:
        operName == "Invalid input";
}

printf("\n\nYou chose: %s", oper);

我在某处读到需要使用指针来防止内存泄漏,但我是新手,所以也许有更简单的方法。

【问题讨论】:

  • 如果您尝试将该字符串文字分配给 operName ,请使用 strcpy()、strncpy()、strlcpy() 或 memcpy()
  • 语句"...我需要使用指针来防止内存泄漏..." 本身没有意义;指针不是防止内存泄漏的某种神奇机制,它们只是内存地址。内存泄漏是由于动态分配内存而未能解除分配造成的;您没有使用动态内存分配(在提供的代码中),因此内存泄漏不是问题。除了动态内存分配需要指针,从这个意义上说,指针可能导致泄漏,而不是阻止它们——但只能通过不正确的使用; 正确的代码可以防止(或者说避免)内存泄漏。
  • @Clifford 哦,我没有很好地使用这个概念。我会继续学习以了解更多信息:)

标签: c arrays string switch-statement calculator


【解决方案1】:

== 不用于分配。 C 是一种非常低级的语言,您不能像为整数或字符那样为 C 中的字符串赋值。

为此,您必须使用标准库string.h

例如:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char source[1000], destination[1000];

    /* Do something with the strings */

    strcpy(destination, source);
    return 0;
}

了解更多关于string.hhere

【讨论】:

  • 感谢它的工作!字符操作名称[15]; /* ... */ strcpy(operName, "ADD");
  • 不客气;我可以帮上忙。
猜你喜欢
  • 2012-04-03
  • 2019-07-18
  • 2017-08-03
  • 2011-12-15
  • 1970-01-01
  • 2021-01-21
  • 1970-01-01
  • 1970-01-01
  • 2013-04-25
相关资源
最近更新 更多