2013-02-02 48 views
-4

我现在真的很害怕我的程序。我期望strcat函数可以简单地将所需的字符串连接在一起,但显然strcat函数(未注释的时候)没有得到正确的连接,并以某种方式改变了我的变量的值。由于是,正确的结果,如果打印,例如:用C中的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); 

那么这里就是的bizzare结果我得到:

/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++; 
    } 

} 
+0

您是否考虑使用'snprintf'(或'asprintf')而不是您对'strcat'的调用?它可能更适合你的任务,并且更安全!或者,如果使用C++编码,使用'std :: string' –

+1

'strcat()'**确实会改变它的第一个参数。 – 2013-02-02 05:52:59

+0

@ H2CO3不正确。猫不会改变任何论点。 (jk) –

回答

0

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

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

目的地由第一字符覆盖“将源字符串到目的地串的副本。该终止空字符的来源,以及空字符被包含在末尾的新字符串所形成的两个连接的目标中。“

以上引用来自cplusplus。

+3

......这是一个令人耳目一新的变化,是正确的。 –