如何将字符添加到二维数组?
How to add chars to 2D array?
我的代码:
FILE * file;
file = fopen("c://catalog//file.txt", "r");
int m,n; //size of 2d array (m x n)
fscanf(file, "%d", &m);
fscanf(file, "%d", &n);
fclose(file);
printf("Size: %d x %d\n", m, n);
// create 2d array
char **TAB2 = new char*[m];
for (int i = 0; i < m; i++)
char *TAB2 = new char[n];
// display 2d array
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++)
{
printf("%c ", &TAB2[i][j]);
}
printf("\n");
}
如何用字符或字符串填充这个数组?例如文本 = "someting",对于数组 3x5 将是:
S o m e t
h i n g ?
? ? ? ? ?
我试过了:TAB2[0][0] = 's'; *&TAB2[0][0] = 's';对于一个字符,这不起作用...
可能是我用不好指针(?)。有人帮帮我吗?
动态分配数组错误
char **TAB2 = new char*[m];
for (int i = 0; i < m; ++i)
TAB2[i] = new char[n];
检查这个 link 寻求帮助。
你可以试试这个:
#include<iostream>
using namespace std;
int main() {
const int m = 3, n = 5;
char **TAB2 = new char*[m];
for (int i = 0; i < m; ++i)
TAB2[i] = new char[n];
char c;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
std::cin >> c;
TAB2[i][j] = c;
}
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
std::cout << TAB2[i][j];
}
std::cout << "\n";
}
// NEVER FORGET TO FREE YOUR DYNAMIC MEMORY
for(int i = 0; i < m; ++i)
delete [] TAB2[i];
delete [] TAB2;
return 0;
}
输出:
jorje
georg
klouv
jorje
georg
klouv
重要链接:
- How do I declare a 2d array in C++ using new?
- How do I use arrays in C++?
数组的分配似乎不正确;应该是这样的。
char **TAB2 = new char*[m];
for (int i = 0; i < m; i++)
TAB2[i] = new char[n];
我的代码:
FILE * file;
file = fopen("c://catalog//file.txt", "r");
int m,n; //size of 2d array (m x n)
fscanf(file, "%d", &m);
fscanf(file, "%d", &n);
fclose(file);
printf("Size: %d x %d\n", m, n);
// create 2d array
char **TAB2 = new char*[m];
for (int i = 0; i < m; i++)
char *TAB2 = new char[n];
// display 2d array
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++)
{
printf("%c ", &TAB2[i][j]);
}
printf("\n");
}
如何用字符或字符串填充这个数组?例如文本 = "someting",对于数组 3x5 将是:
S o m e t
h i n g ?
? ? ? ? ?
我试过了:TAB2[0][0] = 's'; *&TAB2[0][0] = 's';对于一个字符,这不起作用...
可能是我用不好指针(?)。有人帮帮我吗?
动态分配数组错误
char **TAB2 = new char*[m];
for (int i = 0; i < m; ++i)
TAB2[i] = new char[n];
检查这个 link 寻求帮助。
你可以试试这个:
#include<iostream>
using namespace std;
int main() {
const int m = 3, n = 5;
char **TAB2 = new char*[m];
for (int i = 0; i < m; ++i)
TAB2[i] = new char[n];
char c;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
std::cin >> c;
TAB2[i][j] = c;
}
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
std::cout << TAB2[i][j];
}
std::cout << "\n";
}
// NEVER FORGET TO FREE YOUR DYNAMIC MEMORY
for(int i = 0; i < m; ++i)
delete [] TAB2[i];
delete [] TAB2;
return 0;
}
输出:
jorje
georg
klouv
jorje
georg
klouv
重要链接:
- How do I declare a 2d array in C++ using new?
- How do I use arrays in C++?
数组的分配似乎不正确;应该是这样的。
char **TAB2 = new char*[m];
for (int i = 0; i < m; i++)
TAB2[i] = new char[n];