Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- int main(int argc, char *argv[])
- {
- // Allocate memory for the array like this:
- int** array;
- array = malloc(n * sizeof(*array)); /* Assuming `n` is the number of rows */
- if(!array) /* If `malloc` failed */
- {
- fputs(stderr, ""Error allocating memory; Bailing out!"");
- exit(-1);
- }
- int count = 1;
- for(int i = 0; i < n; i++)
- {
- array[i] = malloc(count * sizeof(**array));
- if(!array[i]) /* If `malloc` failed */
- {
- for(int j = 0; j < i; j++) /* free previously allocated memory */
- {
- free(array[j]);
- }
- free(array);
- fputs(stderr, ""Error allocating memory; Bailing out!"");
- exit(-1);
- }
- count++;
- }
- // Then, read data from the file into the array by using:
- FILE* fp = fopen(""file.txt"", ""r"");
- if(!fp)
- {
- for(int i = 0; i < n; i++) /* free previously allocated memory */
- {
- free(array[i]);
- }
- free(array);
- fputs(stderr, ""Error opening 'file.txt'; Bailing out!"");
- exit(-1);
- }
- int max = 1;
- for(int i = 0; i < n; i++)
- {
- for(count = 0; count < max; count++)
- {
- fscanf(fp, ""%d"", &array[i][count]);
- }
- max++;
- }
- // Then print the results:
- max = 1;
- for(int i = 0; i < n; i++)
- {
- for(count = 0; count < max; count++)
- {
- printf(""array[%d][%d] = %d"", i, count, array[i][count]);
- }
- max++;
- }
- // And finally, free the allocated memory:
- for(int i = 0; i < n; i++)
- {
- free(array[i]);
- }
- free(array);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement