一个VC下运行错误的程序,在win-tc上可以运行成功.程序已调试成功,求详细原因
程序代码:
#define LIST_INIT_SIZE 100 #define LISTINCREMENT 10 #include <malloc.h> #include <stdio.h> /*顺序表示的线性表*/ typedef struct{ char *elem; int length; int listsize; }Sqlist; /*线性表的初始化*/ void initList_sq(Sqlist *list){ list->elem = (char *)malloc(LIST_INIT_SIZE*sizeof(char)); list->length = 0; list->listsize = LIST_INIT_SIZE; } /*遍历线性表的节点*/ void listTraverse_sq(Sqlist *list){ int i; if(list->length == 0) return; for(i=0; i<list->length;i++){ printf("%c ",*(list->elem + i*sizeof(char))); } } /*向线性表中第n个元素之前插入一个节点*/ void listInsert_sq(Sqlist *list, int n, char c){ int i; char *newbase; if(n<1||n>list->length+1) return; if(list->length>=list->listsize){ newbase = (char *)realloc(list->elem, (list->listsize+LISTINCREMENT)*sizeof(char)); if(!newbase) exit(1); list->elem = newbase; list->length += LISTINCREMENT; } if(list->length != 0) for(i=list->length-1; i>=n-1; i--) *(list->elem + (i+1)*sizeof(char)) = *(list->elem + (i)*sizeof(char)); *(list->elem + (n-1)*sizeof(char)) = c; list->length += 1; } void main(){ Sqlist *s; /*VC中此处要改为: Sqlist *s,l; s = &l; */ initList_sq(s); listInsert_sq(s,1,'a'); listInsert_sq(s,1,'b'); listInsert_sq(s,1,'c'); listInsert_sq(s,2,'d'); listInsert_sq(s,5,'l'); listTraverse_sq(s); free(s); /*vc中此处应改为:free(s->elem)*/ getch(); }见main函数中两处注释,知道是按照书本上是VC上的那个写的规范,但是tc上那个为啥不报错,也能得出正确的运行结果?
求详细分析!
[ 本帖最后由 三月的雪 于 2011-4-14 07:31 编辑 ]