顺序结构存储的串删除子串,该如何解决
顺序结构存储的串删除子串
#include "stdafx.h"
#include "iostream.h"
#define maxsize 6
typedef struct
{
char ch[maxsize];
int len;
}seqstring;
seqstring *WEEPSTR(seqstring *S,int i,int j)
{
int k,l;
if(i+j>S->len) printf("越界\n");
else
{
for(k=0;k<j;k++)
for(l=i;l<i+j-k;l++)
S->ch[i]=S->ch[i+1];
}
return (S);
}
int main()
{
int m,n,i;
seqstring *S;
seqstring *WEEPSTR(seqstring *S, int i,int j);
puts("please put in a string with the length of 6:");
for(i=0;i<6;i++)
S->ch[i]=getchar();
printf("start from:");
scanf("%d",&m);
printf("the length you want to weep:");
scanf("%d",&n);
WEEPSTR(S, m,n );
puts("the new string is: ");
puts(S->ch);
return 0;
}
有一个警告,运行以后出现内存不能写入,请各位路过的大神帮忙看一下~~万谢~~~~~
------解决方案--------------------
楼主,S没分配空间:
S = (seqstring *) malloc (sizeof(seqstring));
------解决方案--------------------
参考:
#include "stdafx.h"
#include "iostream.h"
#define maxsize 6
typedef struct
{
char ch[maxsize];
int len;
}seqstring;
seqstring *WEEPSTR(seqstring *S,int i,int j)
{
int k,l;
if(i+j>S->len) printf("越界\n");
else
{
for(k=0;k<j;k++)
for(l=i;l<i+j-k;l++)
S->ch[i]=S->ch[i+1];
}
return (S);
}
int main()
{
int m,n,i;
seqstring *S;
seqstring *WEEPSTR(seqstring *S, int i,int j);
puts("please put in a string with the length of 6:");
for(i=0;i<6;i++)
S->ch[i]=getchar();
printf("start from:");
scanf("%d",&m);
printf("the length you want to weep:");
scanf("%d",&n);
WEEPSTR(S, m,n );
puts("the new string is: ");
puts(S->ch);
return 0;
}
有一个警告,运行以后出现内存不能写入,请各位路过的大神帮忙看一下~~万谢~~~~~
------解决方案--------------------
楼主,S没分配空间:
S = (seqstring *) malloc (sizeof(seqstring));
------解决方案--------------------
参考:
- C/C++ code
#include <stdio.h> #include <stdlib.h> #define maxsize 6 typedef struct { char ch[maxsize]; int len; }seqstring; seqstring *WEEPSTR(seqstring *S,int i,int j) { int k,l; if(i+j>S->len) printf("越界\n"); else { /* for(k=0;k<j;k++) for(l=i;l<i+j-k;l++) S->ch[i]=S->ch[i+1]; */ for(k=i+j; k<S->len;++k) { S->ch[i++] = S->ch[k]; } S->ch[i]='\0'; } return (S); } int main() { int m,n,i; seqstring *S; seqstring *WEEPSTR(seqstring *S, int i,int j); S = (seqstring *) malloc (sizeof(seqstring)); //分配空间 puts("please put in a string with the length of 6:"); S->len = 6; // 对长度赋值 /* for(i=0;i<6;i++) S->ch[i]=getchar(); */ scanf("%s", S->ch); //用scanf()不要管回车 printf("start from:"); scanf("%d",&m); printf("the length you want to weep:"); scanf("%d",&n); WEEPSTR(S, m,n ); puts("the new string is: "); puts(S->ch); return 0; }