我的代码:
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");
}
如何使用字符或字符串填充此数组?例如text =&#34; someting&#34;,对于数组3x5将是:
S o m e t
h i n g ?
? ? ? ? ?
我试过:TAB2 [0] [0] =&#39; s&#39; *&amp; TAB2 [0] [0] =&#39; s&#39;对于一个char,这确实有效...
可能我使用指针(?)。有人帮我吗?
答案 0 :(得分:2)
动态分配数组错误。
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
重要链接:
答案 1 :(得分:2)
数组的分配似乎不正确;它应该如下。
char **TAB2 = new char*[m];
for (int i = 0; i < m; i++)
TAB2[i] = new char[n];