#include <iostream>
#include <conio.h>
//数据
int size = 1;//最多存多少个整数
int len = 0;//已经存储的整数个数
int* p = (int*)malloc(size*sizeof(int));
//存储一个整数
void Add(int a)
{
p[len] = a;
len++;
//扩容
if (len == size)
{
int* np = (int*)malloc(size*2*sizeof(int));
for (int i = 0;i < len; ++i)
np[i] = p[i];
free(p);
p = np;
size *= 2;
}
}
//打印
void Print()
{
for (int i = 0;i < len; ++i)
std::cout<<p[i]<<" ";
}
void main()
{
while (1)
{
system("cls");
std::cout<<"1)添加整数\n2)打印\n3)退出\n请选择:";
int a = _getch();
if (a == '1')
{
int b;
std::cout<<"请输入一个整数:";
std::cin>>b;
Add(b);
}
else if (a == '2')
{
Print();
system("pause");
}
else if (a == '3')
{
free(p);
break;
}
}
system("pause");
}
-----------------------------------
#include <iostream>
#include <conio.h>
int len = 0;//长度
int count = 0;//字符串的个数
char* p = (char*)malloc(1);
//存储一个字符串
void Add(char* a)
{
int nlen = strlen(a) + 1;
char* np = (char*)malloc(len + nlen);
//拷贝原来的数据
if (len)
memcpy(np, p, len);
free(p);
p = np;
//memcpy(np + len, a, nlen);或者
strcpy(np + len, a);
len += nlen;
count++;
}
//打印
void Print()
{
char* q = p;
for (int i = 0;i < count; ++i)
{
std::cout<< q <<std::endl;
q += strlen(q) + 1;
}
}
void main()
{
while (1)
{
system("cls");
std::cout<<"1)添加字符串\n2)打印\n3)退出\n请选择:";
int a = _getch();
if (a == '1')
{
char s[128];
std::cout<<"请输入字符串:";
std::cin>>s;
Add(s);
}
else if (a == '2')
{
Print();
system("pause");
}
else if (a == '3')
{
free(p);
break;
}
}
system("pause");
}
abc
def
123456
789
abc\0def\0123456\0789\0
q
添加不同类型的数据
1)int
2)double
3)char
4)字符串
5)打印
100 200 4.4 54.5 abcdefg 400
1 100 1 200 2 4.4 2 54.5 4 abcdefg 1 400
#include <iostream>
#include <conio.h>
int len = 0;//总字节数
int count = 0;//存了多少个变量
char* p = (char*)malloc(1);
void Add(void* mem, int size)
{
char* np = (char*)malloc(len + size);
if (len)
memcpy(np, p, len);
memcpy(np + len, mem, size);
free(p);
p = np;
len += size;
}
void Print()
{
char* q = p;
for (int i = 0;i < count; ++i)
{
int type = *(int*)q;
q += 4;
if (type == 1)//int
{
std::cout<< *(int*)q ;
q += 4;
}
else if (type == 2)//double
{
std::cout<< *(double*)q;
q += 8;
}
else if (type == 3)
{
std::cout<< *(char*)q;
q += 1;
}
else if (type == 4)
{
std::cout<< q;
q += strlen(q) + 1;
}
std::cout<<" ";
}
}
void main()
{
while (1)
{
system("cls");
std::cout<<"1)添加int\n2)double\n3)char\n4)字符串\n5打印\n6)退出\n请选择:";
int a = _getch();
if (a == '1')
{
int a;
std::cout<<"请输入一个int:";
std::cin>>a;
int type = 1;
Add(&type, 4);//先存类型
Add(&a, 4);//再存数据
count++;
}
else if (a == '2')
{
double a;
std::cout<<"请输入一个double:";
std::cin>>a;
int type = 2;
Add(&type, 4);
Add(&a, 8);
count++;
}
else if (a == '3')
{
char a;
std::cout<<"请输入一个char:";
std::cin>>a;
int type = 3;
Add(&type, 4);//
Add(&a, 1);
count++;
}
else if (a == '4')
{
char a[128];
std::cout<<"请输入一个字符串:";
std::cin>>a;
int type = 4;
Add(&type, 4);
Add(a, strlen(a) + 1);
count++;
}
else if (a == '5')
{
Print();
system("pause");
}
else if (a == '6')
{
free(p);
break;
}
}
system("pause");
}
数据储存
最新推荐文章于 2022-12-30 09:54:25 发布