当前位置: 代码迷 >> C语言 >> 不看不知道
  详细解决方案

不看不知道

热度:216   发布时间:2006-04-16 19:58:00.0
不看不知道

#include < stdio.h >
#include <stdlib.h>
#include <string.h>
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;


typedef struct{
char * ch;
int length;
}HString;


Status StrAssign(HString &T,char *chars){
int i ,j;
char * p = T.ch,c;
j = strlen(chars);
for(i = 0,c = chars[i]; c;++i,++c);//surpise c = chars[i] char c c++
if(!i){T.ch = NULL; T.length = 0;}
else{
if(!(T.ch = (char *)malloc(j*sizeof(char))))//将i改为J更好
exit(OVERFLOW);
T.ch = chars;//surpise T.ch[0.1.2.3......] = chars[0.1.2.3......]
T.length = j;//T.length = i i是指针长度随机的
}
return OK;
}


void main(){
HString T;
char s[100];
printf("please input a string\n");
gets(s);
StrAssign(T,s);
puts(T.ch);
printf("the length is %d\n",T.length);
//if( T.length ) free( T.ch );//为何出错指点一下
}


----------------解决方案--------------------------------------------------------
应该不能free,可能没这个权限吧!要全部把T删掉才可以.
----------------解决方案--------------------------------------------------------

#include <stdio.h >//多加了一个空格
#include <stdlib.h>
#include <string.h>
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;


typedef struct{
char * ch;
int length;
}HString;

//在这里∨ 把&去掉
Status StrAssign(HString &T,char *chars){
int i ,j;
char * p = T.ch,c;
j = strlen(chars);
for(i = 0,c = chars[i]; c;++i,++c);//surpise c = chars[i] char c c++
if(!i){T.ch = NULL; T.length = 0;}
else{
if(!(T.ch = (char *)malloc(j*sizeof(char))))//将i改为J更好
exit(OVERFLOW);
T.ch = chars;//surpise T.ch[0.1.2.3......] = chars[0.1.2.3......]
T.length = j;//T.length = i i是指针长度随机的
}
return OK;
}


void main(){
HString T;
char s[100];
printf("please input a string\n");
gets(s);
StrAssign(T,s);
puts(T.ch);
printf("the length is %d\n",T.length);
if( T.length ) free( T.ch );
}


----------------解决方案--------------------------------------------------------
  相关解决方案