【问题标题】:Struggling with strcat function in CC中的strcat函数苦苦挣扎
【发布时间】:2013-02-02 05:46:59
【问题描述】:

我现在对我的程序感到非常沮丧。我希望 strcat 函数会简单地将所需的字符串连接在一起,但显然 strcat 函数(未注释时)没有正确连接,并且以某种方式改变了我的变量的值。照原样,如果打印出正确的结果,例如:

/usr/local/sbin
/usr/local/sbin
/usr/local/bin
/usr/local/bin
/usr/sbin
/usr/sbin
... (etc)

但是当这两行没有注释时

//strcat(file_loc, slash);
//strcat(file_loc, temp);

然后这是我得到的奇怪结果:

/usr/local/sbin
/usr/local/sbin/ls
ls
ls/ls
/usr/sbin
/usr/sbin/ls
... (etc)

这是我正在处理的功能。非常感谢您的帮助。

void step_four (void) {
    int n=0;
    int has_slash=0;
    const char * slash="/";
    char * aa;
    char bb[64];
    int cc=0;
    int len;
    char * file_loc = malloc(100);
    char * temp= malloc(100);
    char * temp2 = malloc(100);
    //char [] f="FOO";


    printf("XXXXXXXXXXXXXXXXXXXXXXXX\n");
    printf("Made it to step 4\n");
    printf("First word of command is: %s\n", words[0]);

    aa = words[0];
    len = strlen(aa);

    while (cc < len) {
        bb[cc] = *(aa + cc);
        cc++;
    }

    while(n < len) {
        if (bb[n++] == '/') {
            //printf("HELLO !!\n");
            has_slash=1;
            break;
        }
    }


    //printf("has_slash=%d\n", has_slash);

    n=0;

    while (paths[n] != NULL) {
        //printf("%s\n", paths[n]);
        file_loc = paths[n];
        //file_loc[strlen(file_loc)]='\0';
        temp = words[0];
        if (has_slash) {
            //do stuff for slash

        }
        else {  
            printf("%s\n", file_loc);
            //strcat(temp2, "a");
            //strcat(file_loc, slash);
            //strcat(file_loc, temp);
            //file_loc[strlen(file_loc)]='/';
            //file_loc[strlen(file_loc) + 1]='/0';
            printf("%s\n", file_loc);
        //  f = file_loc;

        }
        n++;
    }

}

【问题讨论】:

  • 您是否考虑过使用snprintf(或asprintf)而不是调用strcat?它可能更适合您的任务,并且更安全!或者,如果使用 C++ 编码,请使用 std::string
  • strcat() 确实改变了它的第一个参数。
  • @H2CO3 不正确。猫不会改变任何论点。 (jk)
  • 但它是一个 str -ange one!你没看见吗?
  • @StevenC。你的程序的其余部分在哪里? @这里的第一个问题,请阅读要做什么when you get answers

标签: c pointers char strcat


【解决方案1】:

http://www.cplusplus.com/reference/cstring/strcat/

char * strcat ( char * destination, const char * source );

"将源字符串的副本附加到 destination 字符串。destination 中的终止 null 字符被覆盖 strong> 由 source 的第一个字符组成,并且 null-character 包含在 新字符串的末尾,该字符串由 destination 中两者的连接形成。”

以上引用来自cplusplus。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多