查错:下面的程序编译没问题,为什么运行会出错呢

查错:下面的程序编译没问题,为什么运行会出错呢

最近在看吉林大学的C程序设计的课件,有一章讲到这个函数动手写了一下。

题目:
编写一个Insert函数实现在字符串s中的第i个位置插入字符串s1;
在VC++2005中编译这段程序没有任何的Error和warning但是运行就会错误,不知道为什么阿,请高手指点一二。

#include "stdafx.h"

#include <iostream>
using namespace std;

void Insert(char *s, char *s1, int i)
{
 char *p,*q;
 p = s + strlen(s); // p 指向s的末尾+1
 q = p + strlen(s1); //q 指向新构造的字符串的\0 
 *q = '\0';

 // 
 for(p--,q--;p>=s+i-1;)
 {
  *(p--) = *(q--);
 }

 //
 for(p=s+i-1;*s1;)
 {
  *(p++) = *(s1++);
 }
}


int _tmain(int argc, _TCHAR* argv[])
{

 char *s = "Student";
 char *s1 = "Teacher";

 Insert(s,s1,3);

// 期待的输出是StuTeacherdent;
 cout<<s;


 return 0;
}


// 还有我如果把insert函数改成下面的应该也是可以的吧

void Insert2(char *s, char *s1, int i)
{
 char *p,*q;
 p = s + strlen(s); // p 指向s的末尾+1
 q = p + strlen(s1); //q 指向新构造的字符串的\0 
 *q = '\0';

 // 
 for(p--,q--;p>=s+i-1;)
 {
  *p-- = *q--;
 }

 //
 for(p=s+i-1;*s1;)
 {
  *p++ = *s1++;
 }
}

你可能感兴趣的:(查错:下面的程序编译没问题,为什么运行会出错呢)