0

I'm trying to create a 2D array from the data read from .txt file.
The data in 'data.txt' look like belows:

A;B;4
A;C;5
B;C;8

Assume it is symmetry.
Is there any way to create a 2D matrix [i][j] and print in d[i][j] = value?

Appreciate your comments/suggestion.

1
  • you can create char array and store value and key there. Commented May 15, 2012 at 18:19

3 Answers 3

1

2D arrays are useful when the dimensions are known at compile time. If this is the case, other answers can be useful. If not, a 2D array isn't for you.

I suggest using a simple 1D array, allocated (malloc) to have n*n entries.
Then, to access cell i/j, use array[i*n+j].

Another approach is to allocate an array of pointers to arrays. Creating it is more complicated, but you can access it as array[i][j].

0
int tda[3][3];
tda[1][2] = 'x';

You can also use malloc for a dynamically-sized array.

0

As you wrote:

#include <stdio.h>

#define N 4

int main(int argc, char **args) {
    int A[N][N], i, j;

    for (i = 0; i < N; i++)
        for (j = 0 ; j < N; j++)
            A[i][j] = i + j;

    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++)
            printf("%d ", A[i][j]);
        printf("\n");
    }
}
1
  • It just sets some values in a 4x4 matrix and then prints them. Commented May 16, 2012 at 16:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.