2012-11-12 65 views
0
#include <stdio.h>  

int main() 
{ 
    char s[] = "churchgate: no church no gate"; 
    char t[25]; 
    char *ss, *tt; 
    ss = s; 
    while (*ss != '\0') 
    *tt++ = *ss++; 
    printf("%s\n", t); 
    return 0; 
} 

这段代码有什么问题?当我尝试运行它时,它显示了一些垃圾值。显示错误的字符串代码?

+2

后检查t

  • 没有0终止通过未初始化的指针写入是未定义的行为。 –

  • +0

    添加'static_assert(sizeof(s)<= 25,“坏坏坏”);' – Lundin

    +1

    @Lundin,我会建议'char t [sizeof(s)];'而不是。特别是,考虑到它是'c'标记的。 –

    回答

    3

    您从未将tt指向任何东西。你需要把它指向t

    tt=t; 
    
    +0

    哦谢谢了。这些指针让我困惑。 –

    3
    1. 你忘了inialize ttt
    2. 你的阵列太小。
    3. 你忘了null终止你的数组。
    +0

    谁在乎2,给1? :) –

    +0

    @ MichaelKrelin-hacker是的,我试图做到尽善尽美;) – ouah

    +0

    是的,你已经做得相当彻底,因此我的upvote。 –

    0

    几个问题:

    1) “TT” 从未初始化,

    2) “S []” 可能是只读(取决于编译器/平台)! !

    建议:

    #include <stdio.h> 
    
    #define MAX_STRING 80 
    
    int 
    main() 
    { 
        char s[MAX_STRING] = "churchgate: no church no gate"; 
        char t[MAX_STRING]; 
        char *ss = s, *tt = t; 
        while (*ss) 
        *tt++ = *ss++; 
        *tt = '\0'; 
        printf("%s\n", t); 
        return 0; 
    } 
    
    +0

    2只有在指针初始化的情况下? –

    +2

    's'只读? 's'不是一个字符串文字。 – ouah

    1

    芹苴它可以很有趣,在内存的任意位置进行试验,如果你想有一个定义的行为接入的目标,必须定义。

    在对其执行操作之前,tt必须指向内存空间中的某个定义区域。

    *tt++ = *ss++; 
    

    s是30字节。 t,如果那是你想用于tt的那个是25.

    +0

    嗯。我数了30? –

    +0

    @ MichaelKrelin-hacker;你是非常正确的,我在那里计算字符有点困难。谢谢:) –

    +0

    这是因为我没有将它粘贴到控制台'echo -n .... | wc -c'(并添加了一个用于终止符);-) –

    0

    几种可能性,例如,摹:

    #include <stdio.h>  
    
    int main() 
    { 
        char s[] = "churchgate: no church no gate"; 
        char t[25]; 
        char *ss, *tt; 
        for (ss=s, tt=t; *ss != '\0' && tt-t < sizeof(t)-1; ss++, tt++) 
        *tt = *ss; 
        } 
        *tt = '\0'; 
    
        // or just use strncpy. 
        // strncpy doesn't copy the \0 if the size is reached, 
        // so account for that. 
        strncpy(t, s, sizeof(t)-1); 
        t[sizeof(t)-1] = '\0'; 
    
        printf("%s\n", t); 
        return 0; 
    } 
    

    你知道从其他答案你的主要问题:

    1. tt初始化
    2. 没有界限复制