-4

我现在对我的程序感到非常沮丧。我希望 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++;
    }

}
4

1 回答 1

0

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

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

"将源字符串的副本附加到目标字符串。目标中的终止字符被源的第一个字符覆盖,并且空字符包含在由两者连接形成的新字符串的末尾。”

以上引用来自cplusplus。

于 2013-02-02T05:54:32.667 回答