I have to fill a 6x5 array with numbers: 52, 62, 72 etc till array is full. But I don't have an idea how to do it. Thank you for the help.
I tried this:
int main() {
int a[6][5];
int start = 52;
for (int i = 0; i < 6; i++)
for (int j = 0; j < 5; j++) {
a[i][j] = start;
start++;
}
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 5; j++)
printf("%d ", a[i][j]);
printf("\n");
}
return 0;
}
If you wish to increment by 10 horizontally and by 1 vertically, you can modify your code this way:
#include <stdio.h>
int main() {
int a[6][5];
int start = 52, col_incr = 10, row_incr = 1;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 5; j++) {
a[i][j] = start + i * row_incr + j * col_incr;
}
}
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 5; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}
Output:
52 62 72 82 92
53 63 73 83 93
54 64 74 84 94
55 65 75 85 95
56 66 76 86 96
57 67 77 87 97
Your code would appear to work just fine. It produces:
52 53 54 55 56
57 58 59 60 61
62 63 64 65 66
67 68 69 70 71
72 73 74 75 76
77 78 79 80 81
If you expect to see:
52 62 72 ...
You just need to increment by 10 when initializing your matrix, instead of incrementing by 1 using the ++ operator.
You can do everything inside two nested for loops:
#include <stdio.h>
int main() {
int a[6][5];
int start = 52;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 5; j++) {
a[i][j] = start;
start += 10;
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}
Note: start += 10 equals to start = start + 10
This will result:
52 62 72 82 92
102 112 122 132 142
152 162 172 182 192
202 212 222 232 242
252 262 272 282 292
302 312 322 332 342
Related
I'm currently a CS50x student.
I've been toying around with the search and sorting algorithms. Trying to understand them in code. Now, on the topic of bubble sort: I created what I think is a bubble sort algorithm. But I couldn't quite fit in the idea of the swap count that needs to be set to non-zero value. My algorithm (below) does sort all numbers. Where would I fit in the swap idea though? If anyone could be so kind to explain I'd really appreciate it.
#import <stdio.h>
#import <cs50.h>
int main(void)
{
// Creating an unsorted array
int count = 10;
int array[count];
for (int z = 0; z < count; z++)
scanf("%i", &array[z]);
// Bubble Sort
int buffer;
for (int b = 0; b < count; b++)
{
int a = 0;
while (a < count)
{
if (array[a] > array[a+1])
{
buffer = array[a];
array[a] = array[a+1];
array[a+1] = buffer;
}
a++;
}
}
printf("Sorted: ");
for (int b = 0; b < count; b++)
printf("%i ", array[b]);
printf("\n");
}
The directive is #include, not #import. The idea of counting swaps is to break the outer loop if nothing is out of sequence (because there were no swaps needed in the inner loop). This code implements that:
#include <stdio.h>
int main(void)
{
// Creating an unsorted array
int count = 10;
int array[count];
for (int z = 0; z < count; z++)
scanf("%i", &array[z]);
putchar('\n');
printf("%8s:", "Unsorted");
for (int b = 0; b < count; b++)
printf(" %i", array[b]);
printf("\n");
// Bubble Sort
for (int b = 0; b < count; b++)
{
int a = 0;
int num_swaps = 0;
while (a < count - 1)
{
if (array[a] > array[a+1])
{
int buffer = array[a];
array[a] = array[a+1];
array[a+1] = buffer;
num_swaps++;
}
a++;
}
if (num_swaps == 0)
break;
}
printf("%8s:", "Sorted");
for (int b = 0; b < count; b++)
printf(" %i", array[b]);
printf("\n");
return 0;
}
Sample runs (source bs97.c compiled to bs97; home-brew random number generator random — the options used generate 10 numbers between 10 and 99 inclusive):
$ random -n 10 10 99 | bs97
Unsorted: 68 47 85 39 52 54 31 81 19 59
Sorted: 19 31 39 47 52 54 59 68 81 85
$ random -n 10 10 99 | bs97
Unsorted: 75 85 36 11 35 87 59 63 26 36
Sorted: 11 26 35 36 36 59 63 75 85 87
$ random -n 10 10 99 | bs97
Unsorted: 90 27 64 90 76 79 52 46 98 99
Sorted: 27 46 52 64 76 79 90 90 98 99
$ random -n 10 10 99 | bs97
Unsorted: 53 60 87 89 38 68 73 10 69 84
Sorted: 10 38 53 60 68 69 73 84 87 89
$
Note that the code avoids trailing blanks in the output.
You could also define int num_swaps = 1; outside the sorting for loop and test it in the main loop condition:
for (int b = 0; b < count - 1 && num_swaps > 0; b++)
{
num_swaps = 0;
and remove the if (num_swaps == 0) break; from the end of the loop. The inner loop could be a for loop too. And the first cycle of the outer loop moves the largest value to the end of the array, so you can shorten the inner cycle so it has less work to do. The printing code should be factored into a function, too.
#include <stdio.h>
static void dump_array(const char *tag, int size, int data[size])
{
printf("%8s (%d):", tag, size);
for (int i = 0; i < size; i++)
printf(" %i", data[i]);
printf("\n");
}
int main(void)
{
// Creating an unsorted array
int count = 10;
int array[count];
for (int z = 0; z < count; z++)
{
if (scanf("%i", &array[z]) != 1)
{
fprintf(stderr, "Failed to read number %d\n", z + 1);
return 1;
}
}
putchar('\n');
dump_array("Unsorted", count, array);
// Bubble Sort
int num_swaps = 1;
for (int b = 0; b < count - 1 && num_swaps > 0; b++)
{
num_swaps = 0;
for (int a = 0; a < count - b - 1; a++)
{
if (array[a] > array[a + 1])
{
int buffer = array[a];
array[a] = array[a + 1];
array[a + 1] = buffer;
num_swaps++;
}
}
}
dump_array("Sorted", count, array);
return 0;
}
Sample output:
$ random -n 10 10 99 | bs97
Unsorted (10): 31 82 81 40 12 17 70 44 90 12
Sorted (10): 12 12 17 31 40 44 70 81 82 90
$
Problem:
1. Sorting the worst cases shows only the half of the result in all of the sorting methods.
Goal:
1. To sort the best case, average, and worst case using the bubble sort, insertion sort, and selection sort.
Tried fixes:
1. Change the values of the arrays.
2. Checked the sorting itself.
3. Make the case values to show that it is correct.
import java.util.Arrays;
public class Random {
public static void main(String[] args) {
int[] bestCase = ascRan();
int[] average = ran();
int[] worstCase = desRan();
System.out.println("Best Case: \t\t" + Arrays.toString(bestCase));
System.out.println("Average: \t\t" + Arrays.toString(average));
System.out.println("Worst Case: \t" + Arrays.toString(worstCase));
System.out.println("\nCurrent Time(ms): " + System.currentTimeMillis());
System.out.println("Current Time(ns): " + System.nanoTime());
System.out.println();
//Best Cases
System.out.println("Bubble (Best Case)");
int[]bSortBest = bubbleSort(bestCase);
print(bSortBest);
System.out.println("Insert (Best Case)");
int[]iSortBest = insertionSort(bestCase);
print(iSortBest);
System.out.println("Select (Best Case)");
int[]sSortBest = selectionSort(bestCase);
print(sSortBest);
//Average
System.out.println("Bubble (Average)");
int[]bSortAverage = bubbleSort(average);
print(bSortAverage);
System.out.println("Insert (Average)");
int[]iSortAverage = insertionSort(average);
print(iSortAverage);
System.out.println("Select (Average)");
int[]sSortAverage = selectionSort(average);
print(sSortAverage);
//Worst Cases
System.out.println("Bubble (Worst Case)");
int[]bSortWorst = bubbleSort(worstCase);
print(bSortWorst);
System.out.println("Insert (Worst Case)");
int[]iSortWorst = insertionSort(worstCase);
print(iSortWorst);
System.out.println("Select (Worst Case)");
int[]sSortWorst = selectionSort(worstCase);
print(sSortWorst);
}
//Random 0-99
public static int[] ran() {
int[] a = new int[101];
for (int i = 0; i <= a.length -1; i++) {
a[i] = (int) (Math.random() * 100);
}
return a;
}
//0-99
public static int[] ascRan() {
int[] b = new int[100];
int min;
int max = 99;
for(min = 0; min <= max; min++){
b[min] = min;
}
return b;
}
//99-0
public static int[] desRan() {
int[] c = new int[100];
int min;
int max = 99;
for(min = 0; min <= max; min++){
c[min] = max;
max--;
}
return c;
}
public static int[]bubbleSort(int[] arr){
int temp;
for(int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > (arr[j + 1])) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
public static int[]insertionSort(int[] arr){
for (int i = 1; i < arr.length; i++){
int key = arr[i];
int j= i-1;
while (j >= 0 && arr[j] > key){
arr[j+1] = arr[j];
j--;
}
arr[j+1]= key;
}
return arr;
}
public static int[]selectionSort(int[] arr) {
for(int i = 0; i < arr.length-1; i++) {
int minimum = i;
for(int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minimum]) {
minimum = j;
}
int temp = arr[minimum];
arr[minimum] = arr[i];
arr[i] = temp;
}
}
return arr;
}
public static void print(int arr[]) {
int n = arr.length;
for(int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("\nCurrent Time(ms): " + System.currentTimeMillis());
System.out.println("Current Time(ns): " + System.nanoTime());
System.out.println();
}
}
Average Case for bubble sort
0 1 1 2 2 4 5 5 6 7 8 10 14 15 16 18 21 21 22 22 23 27 28 30 31 33 34 35 36 36 37 40 40 41 42 42 44 45 46 46 47 49 55 57 57 57 58 58 59 59 60 60 61 62 62 64 65 65 67 67 68 69 69 71 71 72 74 74 76 77 77 77 78 79 79 80 80 81 83 84 84 85 85 86 86 87 87 88 90 91 93 94 96 96 96 97 98 98 99 99 97
Current Time(ms): 1565701640559
Current Time(ns): 91934126771600
Worst Case for bubble sort
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 0
Current Time(ms): 1565701640580
Current Time(ns): 91934147301100
Worst Case for insertion sort
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
Current Time(ms): 1565701640587
Current Time(ns): 91934154307600
Worst Case for selection sort
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
Current Time(ms): 1565701640589
Current Time(ns): 91934156292200
1 has an invalid value at the end of the sort
2,3,4 does not show numbers 1-49
package edu.slu.prog1;
import java.util.Arrays;
public class Random {
public static void main(String[] args) {
int[] bestCase = ascRan();
int[] average = ran();
int[] worstCase = desRan();
System.out.println("Best Case: \t\t" + Arrays.toString(bestCase));
System.out.println("Average: \t\t" + Arrays.toString(average));
System.out.println("Worst Case: \t" + Arrays.toString(worstCase));
System.out.println("\nCurrent Time(ms): " + System.currentTimeMillis());
System.out.println("Current Time(ns): " + System.nanoTime());
System.out.println();
//Best Cases
System.out.println("Bubble (Best Case)");
int[]bSortBest = bubbleSort(bestCase);
print(bSortBest);
System.out.println("Insert (Best Case)");
int[]iSortBest = insertionSort(bestCase);
print(iSortBest);
System.out.println("Select (Best Case)");
int[]sSortBest = selectionSort(bestCase);
print(sSortBest);
//Average
System.out.println("Bubble (Average)");
int[]bSortAverage = bubbleSort(average);
print(bSortAverage);
System.out.println("Insert (Average)");
int[]iSortAverage = insertionSort(average);
print(iSortAverage);
System.out.println("Select (Average)");
int[]sSortAverage = selectionSort(average);
print(sSortAverage);
//Worst Cases
System.out.println("Bubble (Worst Case)");
int[]bSortWorst = bubbleSort(worstCase);
print(bSortWorst);
System.out.println("Insert (Worst Case)");
int[]iSortWorst = insertionSort(worstCase);
print(iSortWorst);
System.out.println("Select (Worst Case)");
int[]sSortWorst = selectionSort(worstCase);
print(sSortWorst);
}
//Random 0-99
public static int[] ran() {
int[] a = new int[100];
for (int i = 0; i <= a.length -1; i++) {
a[i] = (int) (Math.random() * 100);
}
return a;
}
//0-99
public static int[] ascRan() {
int[] b = new int[100];
int min;
int max = 99;
for(min = 0; min <= max; min++){
b[min] = min;
}
return b;
}
//99-0
public static int[] desRan() {
int[] c = new int[100];
int min;
int max = 99;
int des = max;
for(min = 0; min <= max; min++){
c[min] = des;
des--;
}
return c;
}
public static int[]bubbleSort(int[] arr){
int temp;
for(int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > (arr[j + 1])) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
public static int[]insertionSort(int[] arr){
for (int i = 1; i < arr.length; i++){
int key = arr[i];
int j= i-1;
while (j >= 0 && arr[j] > key){
arr[j+1] = arr[j];
j--;
}
arr[j+1]= key;
}
return arr;
}
public static int[]selectionSort(int[] arr) {
for(int i = 0; i < arr.length-1; i++) {
int minimum = i;
for(int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minimum]) {
minimum = j;
}
int temp = arr[minimum];
arr[minimum] = arr[i];
arr[i] = temp;
}
}
return arr;
}
public static void print(int arr[]) {
for (int i = 0, arrLength = arr.length; i < arrLength; i++) {
int anArr = arr[i];
System.out.print(anArr + " ");
}
System.out.println("\nCurrent Time(ms): " + System.currentTimeMillis());
System.out.println("Current Time(ns): " + System.nanoTime());
System.out.println();
}
}
I know how to transpose a matrix, But how to transpose a matrix with odd row Reversed form.
Example 3*3 Matrix
1 2 3
4 5 6
7 8 9
Output
1 6 7
2 5 8
3 4 9
Here is a solution that breaks the problem into smaller subproblems. The function reverse_row() is a function that reverses an array in place, and the function transpose_array() transposes an array in place.
The first function, reverse_row() is called in a loop on the rows of the 2d array with odd indices, then the transpose_array() function is called on the resulting array. Note that the test if (i % 2) {} is used to determine if an array index is odd or even, since i % 2 evaluates to 0 only when i is even; you could also avoid this test and simply increment i by two at each iteration (starting from 1), as suggested by #Lưu Vĩnh Phúc in the comments:
for (size_t i = 1; i < MATRIX_SZ; i += 2) {
reverse_row(MATRIX_SZ, array[i]);
}
Also note that to transpose a square matrix in place, you do not need to iterate over all of the elements, but only the elements above or below the diagonal, swapping with the appropriate element. In this case, I have chosen to iterate over the elements below the diagonal, swapping with the corresponding element above the diagonal. Of course, the elements on the diagonal remain unchanged so are not iterated over at all.
Here is the code, using a 4X4 array as input. This code works for square matrices, and could be adapted to work for rectangular matrices. This would require care in choosing the size of the array used to represent the matrix, or dynamic allocation.
#include <stdio.h>
#define MATRIX_SZ 4
void print_array(size_t n, int arr[n][n]);
void reverse_row(size_t n, int arr[n]);
void transpose_array(size_t n, int arr[n][n]);
int main(void)
{
int array[MATRIX_SZ][MATRIX_SZ] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
puts("Before transformation:");
print_array(MATRIX_SZ, array);
putchar('\n');
for (size_t i = 0; i < MATRIX_SZ; i++) {
if (i % 2) {
reverse_row(MATRIX_SZ, array[i]);
}
}
transpose_array(MATRIX_SZ, array);
puts("After transformation:");
print_array(MATRIX_SZ, array);
putchar('\n');
return 0;
}
void print_array(size_t n, int arr[n][n])
{
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < n; j++) {
printf("%5d", arr[i][j]);
}
putchar('\n');
}
}
void reverse_row(size_t n, int arr[n])
{
size_t mid = n / 2;
for (size_t i = 0; i < mid; i++) {
size_t swap_dx = n - 1 - i;
int temp = arr[i];
arr[i] = arr[swap_dx];
arr[swap_dx] = temp;
}
}
void transpose_array(size_t n, int arr[n][n])
{
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < i; j++) {
int temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
}
And here is the program output:
Before transformation:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
After transformation:
1 8 9 16
2 7 10 15
3 6 11 14
4 5 12 13
If I have understood the assignment correctly then the program can look the following way.
#include <stdio.h>
#define MAX_VALUE 100
int main(void)
{
while ( 1 )
{
printf( "Enter the size of an array (0 - Exit): " );
size_t n;
if ( scanf( "%zu", &n ) != 1 || n == 0 ) break;
putchar('\n');
n %= MAX_VALUE;
int a[n][n];
for ( size_t i = 0; i < n; i++ )
{
for ( size_t j = 0; j < n; j++ )
{
a[i][j] = n * i + j;
}
}
for (size_t i = 0; i < n; i++)
{
for (size_t j = 0; j < n; j++)
{
printf("%3d ", a[i][j]);
}
putchar('\n');
}
putchar('\n');
for (size_t i = 0; i < n; i++)
{
for (size_t j = i; j < n; j++)
{
if (j % 2 == 1 && i < n / 2)
{
int tmp = a[j][i];
a[j][i] = a[j][n - i - 1];
a[j][n - i - 1] = tmp;
}
if (i != j)
{
int tmp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = tmp;
}
}
}
for (size_t i = 0; i < n; i++)
{
for (size_t j = 0; j < n; j++)
{
printf("%3d ", a[i][j]);
}
putchar('\n');
}
putchar('\n');
}
return 0;
}
Its output might look like
Enter the size of an array (0 - Exit): 10
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 75 76 77 78 79
80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99
0 19 20 39 40 59 60 79 80 99
1 18 21 38 41 58 61 78 81 98
2 12 22 37 42 57 62 77 82 97
3 13 23 36 43 56 63 76 83 96
4 14 24 34 44 55 64 75 84 95
5 15 25 35 45 54 65 74 85 94
6 16 26 33 46 53 66 73 86 93
7 17 27 32 47 52 67 72 87 92
8 11 28 31 48 51 68 71 88 91
9 10 29 30 49 50 69 70 89 90
Enter the size of an array (0 - Exit): 3
0 1 2
3 4 5
6 7 8
0 5 6
1 4 7
2 3 8
Enter the size of an array (0 - Exit): 0
The compiler should support Variable Length Arrays. Otherwise you can rewrite the program for an array with a fixed size.
I'm compiling my neural network in c99 on MAC OS X Yosemite.
gdb wasn't giving me a lot of information so I used a lot of printf to define where is my problem.
Here is what gdb is giving me:
entering into error output 0
0.000000
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x0000000000000000 in ?? ()
and here is my code:
127 for (int k = 0; k < 94; k++)
128 {
129 printf("\nentering into error output %d\n", k);
130 printf("\n%lf\n", results[k]);
131 printf("\n%lf\n", outputNeuron[k].output(&outputNeuron[k]));
132 printf("\n%lf\n", sigmoid.derivative(outputNeuron[k].output(&outputNeuron[k])));
133
134 outputNeuron[k].error =
135 sigmoid.derivative(outputNeuron[k].output(&outputNeuron[k])) *
136 (results[k] - outputNeuron[k].output(&outputNeuron[k]));
137
138 printf("\n adjustWeights output %d\n", k);
139 outputNeuron[k].adjustWeights(&outputNeuron[k]);
140
141 printf("\nerror output %d ok\n", k);
142 }
If you need anything more, just ask cause I think you are my last hope
edit:
77 TNeuron outputNeuron[94];
78 if (is_empty(file))
79 for (int k = 0; k < 94; k++)
80 {
81 outputNeuron[k] = TNeuron_create();
82 outputNeuron[k].randomizeWeights(&outputNeuron[k]);
83 }
file is empty for now
and here is TNeuron_create():
37 TNeuron TNeuron_create()
38 {
39 struct TNeuron This;
40 TNeuron_Init(&This);
41 return This;
42 }
43
44 void TNeuron_Init(struct TNeuron *This)
45 {
46 This->output = TNeuron_output;
47
48 This->randomizeWeights = TNeuron_randomizeWeights;
49
50 This->adjustWeights = TNeuron_adjustWeights;
51
52 for (int i = 0; i < 20; i++)
53 for (int j = 0; j < 20; j++)
54 {
55 This->inputs[i][j] = 0;
56 This->weights[i][j] = 0;
57 }
58
59 This->error = 0;
60
61 This->biasWeight = 0;
62 }
edit 2:
5 double TNeuron_output(struct TNeuron *This)
6 {
7 TSigmoid sigmoid = TSigmoid_create();
8
9 double op = 0;
10 for (int i = 0; i < 20; i++)
11 for (int j = 0; j < 20; j++)
12 op += This->weights[i][j] * This->inputs[i][j];
13
14 return sigmoid.output(op + This->biasWeight);
15 }
I have 2 arrays as follows -
int **data;
int ***count;
After running some analysis, I want make the following assignment-
count[i][j][k] = data[i][j];
However, I keep getting Segmentation fault which I think is related to some pointer assignment issues - Can anyone suggest how I can make this assignment?
Typical values of -
data[i][j] = 0/1/2.
Definition of ZALLOC:
#define ZALLOC(item,n,type) if ((item = (type *)calloc((n),sizeof(type))) == NULL) fatalx("Unable to allocate %d unit(s) for item\n",n)
// memory assignment
int **data;
int nrow, ncol;
ZALLOC(data, ncol, int *);
for (index = 0; index < ncol; index++)
{
ZALLOC(data[index], nrow, int);
}
int g=0, index1=0, index2=2;
data[index1][index2] = g;
int ***count;
int dim1 = 100, dim2 = 1, dim3=2;
ZALLOC(count, dim1, int **);
for (i = 0; i < dim1; i++)
{
ZALLOC(count[i], dim2, int *);
for (j = 0; j < dim2; j++)
{
ZALLOC(count[i][j], dim3, int);
}
}
// Initialize
for (i = 0; i < dim1; i++)
{
for (j = 0; j < dim2; j++)
{
for (k = 0; k < dim3; k++)
{
count[i][j][k] = 0;
}
}
}
// Assignment
count[0][1][2] = data[1][2];
Your organization of the allocations is a bit odd. If you have 3 dimensions (lets call them levels, rows, and columns), you would normally allocate space to hold the levels, and then for each level you would allocate the space for the rows within the level, and then finally you would allocate the space for the columns within the row.
Your code seems to start in the middle (rows); then does some work at levels; and finally at the columns.
This code is a complete rewrite of yours, but it works without crashing. I've not yet validated it with valgrind; I need to upgrade the version on this machine.
#include <stdio.h>
#include <stdlib.h>
#define ZALLOC(item, n, type) if ((item = (type *)calloc((n), sizeof(type))) == NULL) \
fatalx("Unable to allocate %d unit(s) for item\n", n)
static void fatalx(const char *str, size_t n)
{
fprintf(stderr, "%s: %zu\n", str, n);
exit(1);
}
static int ***alloc_3d(int levels, int rows, int cols)
{
int count = 0;
int ***array_3d;
ZALLOC(array_3d, levels, int **);
for (int i = 0; i < levels; i++)
{
int **data;
ZALLOC(data, rows, int *);
array_3d[i] = data;
for (int j = 0; j < rows; j++)
{
int *entries;
ZALLOC(entries, cols, int);
array_3d[i][j] = entries;
for (int k = 0; k < cols; k++)
{
array_3d[i][j][k] = count++;
}
}
}
return array_3d;
}
static void print_3d(int ***a3d, int levels, int rows, int cols)
{
for (int i = 0; i < levels; i++)
{
printf("%d:\n", i);
for (int j = 0; j < rows; j++)
{
printf(" %d: ", j);
for (int k = 0; k < cols; k++)
printf(" %3d", a3d[i][j][k]);
putchar('\n');
}
}
}
static void free_3d(int ***a3d, int levels, int rows)
{
for (int i = 0; i < levels; i++)
{
for (int j = 0; j < rows; j++)
free(a3d[i][j]);
free(a3d[i]);
}
free(a3d);
}
int main(void)
{
int d1 = 3;
int d2 = 5;
int d3 = 7;
int ***a3d = alloc_3d(d1, d2, d3);
print_3d(a3d, d1, d2, d3);
free_3d(a3d, d1, d2);
return(0);
}
Output:
0:
0: 0 1 2 3 4 5 6
1: 7 8 9 10 11 12 13
2: 14 15 16 17 18 19 20
3: 21 22 23 24 25 26 27
4: 28 29 30 31 32 33 34
1:
0: 35 36 37 38 39 40 41
1: 42 43 44 45 46 47 48
2: 49 50 51 52 53 54 55
3: 56 57 58 59 60 61 62
4: 63 64 65 66 67 68 69
2:
0: 70 71 72 73 74 75 76
1: 77 78 79 80 81 82 83
2: 84 85 86 87 88 89 90
3: 91 92 93 94 95 96 97
4: 98 99 100 101 102 103 104