回 帖 发 新 帖 刷新版面

主题:严版数据结构 第76页StrAssign的问题

我在将严版数据结构 第76页StrAssign的伪码转换为程序的时候遇到一个问题,具体见下面程序的注释部分,功能是:生成一个其值等于串常量s的串t。


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

#define ERROR 0
#define OK 1
#define INFEASIBLE -1
#define NULL 0
#define OVERFLOW -2
#define MAXSTRLEN 30

typedef int Status;

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

void StrAssign(StringType &t,char *s){
    int i=0;
    char *p,*q;
    p=s;
    if(t.length>0)    free(t.ch);    [color=800000]/*书上用的是if(t.ch),但我这样用的时候程序出错,书上这样对么?*/[/color]    
         while(*p!='\0')    {++i;p++;}
    if(i)    t.length=i;
    else {t.ch=NULL;t.length=0;}
    t.ch=(char *)malloc(i*sizeof(char));
    q=t.ch;p=s;
    for(i=0;i<t.length;i++)    *(q++)=*(p++);
}

void main(){
    StringType t;
    StrAssign(t,"I am a student");
    printf("%d %s\n",t.length,t.ch);
}

回复列表 (共2个回复)

沙发

有必要对t 先进行初始化么?例如象链表那样加上
Status InitString(StringType &t){
    t.ch=NULL;
    t.length=0;
    ruturn OK;
}

板凳

void StrAssign(StringType *t,char *s){
    int i=0;
    char *p,*q;
    p=s;
    if(t->length>0)    free(t->ch);    
         while(*p!='\0')    {++i;p++;}
    if(i)    t->length=i;
    else {t->ch=NULL;t->length=0;}
    t->ch=(char *)malloc(i*sizeof(char));
    q=t->ch;p=s;
    for(i=0;i<t->length;i++)    *(q++)=*(p++);
}

我来回复

您尚未登录,请登录后再回复。点此登录或注册