不知道该怎么做。试过类似下面的内容。想要更多代码优化。
每件事都应该只有一个功能,
指导我如何打开文件,
如何在每一行中找到字符,
增加柜台。
void simpleFileIn(void) {
string line;
ifstream myfile("example.txt");
if (myfile.is_open()) {
while (getline(myfile, line)) {
//found(line);
size_t size = strlen(line);
cout << line << '\n';
}
myfile.close();
}
else
cout << "Unable to open file";
}
函数simpleFileIn()应该工作,打开文件然后在工作完成后关闭 找出字符a并计算整数。 想关闭/删除这个问题,因为我禁止请求更多帮助。情况日渐恶化
答案 0 :(得分:3)
您需要在循环中分配行:
int** pptr = new int* [rows]; // <<== rows, not cols
for(int i=0;i<rows;i++){
pptr[i] = new int[cols]; // <<== Add this line
for(int j=0;j<cols;j++){
cout<<"Enter value at "<<i<<j<<endl;
cin>>pptr[i][j];
cout<<"Value is "<<pptr[i][j]<<endl;
}
}
在删除指向它们的指针数组之前,还需要删除单个行。使用带有方括号的delete[]
运算符:
for(int i=0;i<rows;i++){
delete[] pptr[i];
}
delete[] pptr;
您不需要将NULL
分配给已删除的指针,除非您计划稍后将指针重新用于其他内容。
答案 1 :(得分:2)
你正在分配指针数组错误。
首先,你必须为row
指针分配足够的空间
int** pptr = new int* [rows];
对于每个指针,col
整数
for (int i = 0; i < cols; i++)
{
pptr[i] = new int [cols];
}
要删除数组,请使用delete[]
代替delete
。
删除每一行
for (int i = 0; i < rows; i++)
{
delete [] pptr[i];
}
然后删除指针数组
delete [] pptr;
由于您不会再次使用它们,因此无需为已删除的指针指定NULL
。同样在c++中,您应该使用nullptr
代替NULL
。
<强> Here is the correct using of array of pointers. 强>
你的错误
int* ptr = new int [rows];
int** pptr = new int* [cols];
*pptr=ptr;
delete
代替delete[]
答案 2 :(得分:1)
所以分配似乎有些混乱。从你的代码
int* ptr = new int [rows];
int** pptr = new int* [cols];
*pptr=ptr;
您现在已经创建了1维数组。然后,您取消引用pptr
并为其分配ptr
这与
pptr[0] = ptr;
所以你只是初始化第一列。您想将此代码更改为
int** pptr = new int* [cols];
for (int i = 0; i < cols; ++i) {
pptr[i] = new int [rows];
}
这将正确分配内存
答案 3 :(得分:1)
您可以为2D数组创建各种构造函数,以便进行单行簿记:
#include <iostream>
template <typename T>
T** new_( std::size_t rows, std::size_t columns )
{
auto dsize = rows * sizeof(T*);
auto rsize = columns * sizeof(T);
auto tsize = rows * rsize;
unsigned char* data = new unsigned char[ dsize + tsize ];
T** result = (T**)data;
T* table = (T*)(data + dsize);
while (rows--)
result[ rows ] = table + rows * columns;
return result;
}
int main()
{
int m; std::cout << "m? "; std::cin >> m;
int n; std::cout << "n? "; std::cin >> n;
// Create the new matrix
int** a = new_<int>( m, n );
// Do stuff with a[ r ][ c ] here.
// It looks and behaves JUST LIKE a normal 2D C array
// in all respects EXCEPT one: &a != &(a[0][0]).
// Use the latter when passing to a flat function!
// Delete it
delete [] a;
}
享受这种奇怪。