【问题标题】:C - Problems with strcat [duplicate]C - strcat的问题[重复]
【发布时间】:2014-05-24 04:22:36
【问题描述】:

我正在尝试获取用户 argv 并在屏幕上打印结果。这是我的以下代码:

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

int main (int argc, char *argv[])
{
    if (argc >= 1)
    {
        char *command = "gcc ";
        strcat(command, argv[1]);
        printf("%s", command);
        return 0;
    }
}

它可以编译,但每次我执行它时都会说“Windows 停止工作”。基本上,如果用户这样做:

myprogram.exe test

输出可能是

gcc test

我的错误在哪里?

【问题讨论】:

    标签: c strcat


    【解决方案1】:

    您需要 strcat 的目标参数足够大以容纳所有内容,即

    char command[50];
    strcpy(command, "gcc ");
    strcat(command, argv[1]);
    

    【讨论】:

    • 它适用于 5001 而不是 50。谢谢
    • 请记住动态分配的其他答案 - 您最终可能会得到一些适合 5001 的数组的输入 :)
    • 这会导致未定义的行为; strcat 附加到现有字符串,但 command 未初始化。您应该以strcpy 开头,或者至少将command[0] 初始化为0
    【解决方案2】:

    在使用 strcat 之前,您需要为 char 指针分配内存。因为 char *command = "gcc" 将只是指向一个内存位置。在写入该位置之前,您必须使用 malloc 分配内存或将其更改为数组。

    【讨论】:

      【解决方案3】:
      char *command
      

      只声明一个数组而不指向任何空格。使用前需要为指针分配空间,也可以使用字符数组。

      char command[100]="string";
      

       char *command = (char*) malloc (size);
      

      然后你就可以像以前一样使用 strcat 了。

      【讨论】:

      • char *command; 声明一个指针,而不是一个数组。此外,OP 的代码实际上确实指向了一些空间。并且不要强制转换 malloc。
      • 为什么不应该强制转换 malloc?
      • see here。演员表有零好的效果和非零的坏效果。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-11
      • 2011-07-08
      • 1970-01-01
      • 2013-05-11
      • 2013-09-07
      相关资源
      最近更新 更多