Reputation: 45
My code:
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");
}
How fill this array with chars or string? for example text = "someting", and for array 3x5 will be:
S o m e t
h i n g ?
? ? ? ? ?
I tried: TAB2[0][0] = 's'; *&TAB2[0][0] = 's'; for one char, and this does'nt work...
Probably I badly use pointers(?). Anyone help me?
Upvotes: 1
Views: 2065
Reputation: 73366
The dynamic allocation array is wrong.
char **TAB2 = new char*[m];
for (int i = 0; i < m; ++i)
TAB2[i] = new char[n];
Check this link for help.
You could try this:
#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;
}
Output:
jorje
georg
klouv
jorje
georg
klouv
Important links:
Upvotes: 2
Reputation: 17605
The allocation of the array seems incorrect; it should be as follows.
char **TAB2 = new char*[m];
for (int i = 0; i < m; i++)
TAB2[i] = new char[n];
Upvotes: 2