因为你的传参出现了问题,你调用Kongsq(Sqlist L);和 Fuzhi(Sqlist L); 这两个函数的时候应该传递指针而不是实例。
如果你直接L进去,Kongsq和Fuzhi都无法对main函数中生成的实例L进行操作。
以下是我修改后的代码;增加的打印的函数void printList(Sqlist * L)
typedef struct{
int *elem;
int length;
int listsizenow;
}Sqlist;
int Kong_sq (Sqlist * L)
{
L->elem = (int *)malloc(100 * sizeof(int *));
if(!L->elem) exit(OVERFLOW);
L->length = 0;
L->listsizenow = LIST_SIZE;
return -1;
}
void Fuzhi(Sqlist * L)
{
int i;
L->length = 0;
for(i =0;i <=2;i++)
{
scanf("%d",&L->elem[L->length]);
L->length++;
}
}
void printList(Sqlist * L)
{
int i;
for(i =0;i length;i++)
{
printf("= %d\n",L->elem[i]);
}
}
int main()
{
Sqlist L;
Kong_sq(&L);
Fuzhi(&L);
printList(&L);
free(L.elem);
}
1.Kong_sq函数中采用的是值传递,因此,虽然你在Kong_sq函数中对L申请了空间,以及初始化操作,但是在实参调用(main函数中)时候,对传入的L
起始是没有起到作用的,应该采用指针或引用(在C++中);如:
int Kong_sq(Sqlist *L)
{
..........
}
2.同理,Fuzhi函数也是(1)同样的问题。
3.
修改后的代码如下:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <numeric>
#include <assert.h>
#define LIST_SIZE 10 //Fuzhi中赋值10个,100太浪费空间
#define LIST_JIA 10
typedef struct
{
int *elem;
int length;
int listsizenow;
}Sqlist;
int Kong_sq(Sqlist *L)
{
assert(L);
L->elem = (int *)calloc(LIST_SIZE,sizeof(int));
if(!L->elem) exit(EXIT_FAILURE);
L->length = 0;
L->listsizenow = LIST_SIZE;
return 1;
}
void Fuzhi(Sqlist *L)
{
assert(L); //assert特点,运行时断言;若支持C++11,最好使用static_assert();
int i = 0;
if(!L->elem)
{
puts("No application memory!");
return;
}
while(i++ < 10)
{
scanf("%d",&L->elem[L->length++]);
}
return ;
}
void DisplaySqlist(Sqlist L)
{
assert(L.elem);
int i = 0;
//while(L.length--) 逆序打印
//{
// printf("L[%d] ",L.elem[L.length]);
//}
while(i < L.length)
{
printf("L[%d] ",L.elem[i++]);
}
return ;
}
//释放内存空间
void FreeMemory(Sqlist *L)
{
assert(L && L->elem);
free(L->elem);
L->elem = NULL;
}
int main(int argc, char *argv[])
{
Sqlist L;
Kong_sq(&L);
Fuzhi(&L);
DisplaySqlist(L);
//记得释放内存空间,否则内存泄漏
FreeMemory(&L);
return 0;
}
打印结果:
1 2 3 4 5 6 7 8 9 10
L[1] L[2] L[3] L[4] L[5] L[6] L[7] L[8] L[9] L[10]
若有帮助,还请采纳!!!谢谢。。。。
1.函数参数传递有问题有问题,如果需要初始化结构体,要么参数为引用,要么传递指针,否则值传递,是无法修改结构体变量的元素值的,这一步是无效操作,将2个函数的参数用指针传递试试看;Kong_Sq(Sqlist *pList) ;Fuzhi(Sqlist *pList);
你的&L.elem[L.length]报运行时错误了,