1.线性表初始化 代码存在问题 vc++6.0
2.代码
#include <stdio.h>
#include <stdlib.h>
#define Listsize 20
typedef int ElemType;
typedef struct {
ElemType * elem;
int length;
int listsize;
}Sqlist,*Sq;
Sq InitSq(){
Sq L;
L->elem=(ElemType *) malloc(sizeof(ElemType )*Listsize);
L->length=0;
L->listsize=Listsize;
int i=0;
for(i =0; i<12 ;++i)
{
L->elem[i]=5*i;
L->length++;
}
return L;
}
int main(){
Sq l=InitSq();
for(j=0;j<Listsize;j++)
printf(l->elem[j]);
return 0;
}
3.错误:
error C2143: syntax error : missing ';' before 'type'
D:\demo\cdemo\1.c(21) : error C2065: 'i' : undeclared identifier
D:\demo\cdemo\1.c(38) : error C2143: syntax error : missing ';' before 'type'
D:\demo\cdemo\1.c(39) : error C2065: 'j' : undeclared identifier
D:\demo\cdemo\1.c(40) : warning C4047: 'function' : 'const char *' differs in levels of indirection from 'int '
D:\demo\cdemo\1.c(40) : warning C4024: 'printf' : different types for formal and actual parameter 1
实在不知道是什么原因了 麻烦方便的话 能够解答一下 谢谢
指针类型要做动态分配,修改了代码,你试试
#include <stdio.h>
#include <stdlib.h>
#define Listsize 20
typedef int ElemType;
typedef struct {
ElemType * elem;
int length;
int listsize;
}Sqlist, *Sq;
Sq InitSq(){
int i = 0;
Sq L = (Sq)malloc(sizeof(Sqlist));
L->elem = (ElemType *)malloc(sizeof(ElemType)*Listsize);
L->length = 0;
L->listsize = Listsize;
for (i = 0; i < 12; ++i)
{
L->elem[i] = 5 * i;
L->length++;
}
return L;
}
int main(){
int j;
Sq l = InitSq();
for (j = 0; j < l->length; j++)
printf("%d ",l->elem[j]);
free(l);
return 0;
}
没定义j,就定义他;printf语句格式错了,就改正。
返回未初始化的指针L存在风险。
首先在主函数,也就是main函数中没有定义j变类
应该是
int j=0;
然后输出格式错误
应该是
printf("%d",&l->elem[j])
至于两个警告,反正不会影响程序运行,
但是你这个初始化着实难受