C语言指针题目

时间:2008-05-09 10:19:25   来源:论坛整理  作者:  编辑:chinaitzhe
C/C code





Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/



#include<string.h>

#include<stdio.h>

fun(char *w,int n)

{

    char t,*s1,*s2;

    s1=w;

    s2=w n-1;

    while(s1<s2)

    {

        t=*s1  ;

        *s1=*s2--;  //程序运行时在这里卡住了

        *s2=t;      

    }

}

main()

{

    char *p,t,*s1,*s2;

    int n;

    p="1234567";

    fun(p,strlen(p));

    puts(p);

}



问题是“22.exe 中的 0x00413622 处未处理的异常: 0xC0000005: 写入位置0x004156a9 时发生访问冲突”是什么原因,请高手指点。通过笔头计算,得出的结果是1711717

网友回复:
C/C code





Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/





#include<string.h>

#include<stdio.h>

void fun(char *w,int n)

{

    char t,*s1,*s2;

    s1=w;

    s2=w n-1;

    while(s1<s2)

    {

        t=*s1  ;

        *s1=*s2--; 

        *s2=t;      

    }

}

int main()

{

    char p[]="1234567",t,*s1,*s2;

    int n;



    fun(p,strlen(p));

    puts(p);

    return 0;

}




网友回复:char *p= "123";这样p指向了常量数据区(只读),对其进行修改会造成错误
char p[]= "123";这样p[]被分配在栈中,可以进行任意修改

网友回复:#include <string.h>
#include <stdio.h>
void fun(char *w, int n)
{
char t, *s1, *s2;
s1 = w;
s2 = w n-1;
while(s1 < s2)
{
t = *s1;
*s1 = *s2; //程序运行时在这里卡住了
*s2 = t;
s1 ; // 这样实现数据转置
s2--; //
}
}
void main()
{
char p[] = "1234567";
fun(p, strlen(p));
puts(p);
}
char *p = "1234567"; 指针p指向的是数据常量区,数据不能被修改。
你可以用char p[] = "1234567"; 这样p指向堆栈区,可以修改数据。
关键字:语言,指针,题目,

文章评论

共有 0 位网友发表了评论 此处只显示部分留言 点击查看完整评论页面