C++數組的動態分配空間、初始化和釋放空間
參考這裏。
針對於一維數組
動態分配空間(new)
const int n = 10;
int *array = new int [n];
初始化(memset)
#include <string.h>
memset(array, 0, n*sizeof(int));
釋放空間(delete)
delete []array;
針對於二維數組
動態分配空間(new)
const int n = 10;
int **array = new int *[n];
for(int i=0;i<n;i++)
array[i] = new int [n];
初始化(memset)
初始化和動態分配一塊進行:
#include <string.h>
const int n = 10;
int **array = new int *[n];
for(int i=0;i<n;i++)
{
array[i] = new int [n];
memset(array[i], 0, n*sizeof(int));
}
釋放空間(delete)
有多少個new就有多少個delete。
for(int i=0;i<n;i++)
delete[] array[i];
delete []array;
C/C++讀寫文件
C++讀寫
參考文章《C++中cin.getline()、getline()、cin.get()區別》。
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
ifstream ifs("in.txt");
ofstream ofs("out.txt");
string temp;
while(getline(ifs, temp))
{
cout<<temp<<endl;
}
ifs.close();
ofs.close();
return 0;
}
C讀寫
#include <stdio.h>
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdin);
fclose(stdin);
fclose(stdout);
C/C++中assert斷言的使用
#include <assert.h>
assert(int expression);