2012-11-18 74 views
3

可能重复:
What is the difference between char s[] and char *s in C?
Why does this program give segmentation fault?总线错误10

这里是代码:

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

void reverse(char *c){ 
    int len = strlen(c); 
    char tmp; 
    int i; 
    for(i = 0; i < len; i++){ 
     tmp = c[len-1-i]; 
     c[len-1-i] = c[i]; 
     c[i] = tmp; 
    } 
} 

int main(){ 
    char *s = "antonio"; 
    //printf("%zd\n", strlen(s)); 
    reverse(s); 
    printf("%s\n", s); 
    return 0; 
} 

的问题是反向(字符* c),它采取了一个字符串广告相反,但我不明白它在哪里g错了。

+2

你试图修改字符串文字。这是未定义的行为,通常会崩溃。 –

+2

你没有使用你的编译器警告和/或注意它们。再次编译代码,并启用所有警告,并确保您了解编译器告诉您的所有内容。自动化工具可以在您需要寻求帮助之前为您提供很长的路要走! –

+0

@KerrekSB我没有收到任何警告,我会看到如何启用我的编译器的所有警告。 – AR89

回答

5

有两种错误的位置:

1)

您正试图改变一个字符串,从而导致未定义的行为,表现为你的情况总线错误。

变化

char *s = "antonio"; 

char s[] = "antonio"; 

2)

而且您运行的是整个字符串长度的循环计数器:

for(i = 0; i < len; i++) 

这种方式,你会找回原点inal字符串。你想要的只是将一半的字符与另一半交换:

for(i = 0; i < len/2; i++) 
+0

http://stackoverflow.com/a/3735133/635608 – Mat

+0

@Mat:谢谢,正在寻找一个。 – codaddict

+0

@codaddict有什么区别:char * s =“antonio”; char s [] =“antonio”; char s * = malloc(size);?我知道函数(char a [])变成了函数(char * a),在这种情况下会发生什么? – AR89