Untitled

 avatar
unknown
plain_text
2 years ago
1.9 kB
5
Indexable
 

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main(void)
{
int m, n, q;
printf("Enter dimensions m, n, q: ");
scanf("%d %d %d", &m, &n, &q);

//allocate memory for tensor
int *tensor = malloc(m*n*q*sizeof(int));

//seed random number generator
srand(time(NULL));

//initialize elements of tensor to random integers in range [0,10]
for(int i=0; i<m*n*q; i++)
{
*(tensor+i) = rand() % 11;
}

//add random integers in range [-5, 5] to all tensor elements
for(int i=0; i<m*n*q; i++)
{
*(tensor+i) += (rand() % 11) - 5;
}

//print tensor
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
for(int k=0; k<q; k++)
{
printf("%d ", *(tensor + i*n*q + j*q + k));
}
printf("\n");
}
printf("\n");
}

//deallocate memory for tensor
free(tensor);
}

 --------------------------------------------------------------------------

Explanationfor step 1
This code dynamically allocates memory for a 3-dimensional tensor using a single malloc call. The dimensions of the tensor are input by the user. The elements of the tensor are initialized to random integers in the range [0, 10] and then random integers in the range [-5, 5] are added to all elements. The tensor is printed to the screen. Finally, the memory for the tensor is deallocated using free.
Step 2/2




The code uses a single malloc call to allocate memory for the tensor. This is possible because the size of the tensor is known in advance. The size is determined by the dimensions input by the user. The code uses a single for loop to initialize the elements of the tensor to random integers in the range [0, 10]. Another for loop is used to add random integers in the range [-5, 5] to all elements of the tensor. The tensor is printed to the screen using a triple nested for loop. Finally, the code uses free to deallocate the memory used by the tensor.
Final answer


Output:
Enter dimensions m, n, q: 2 2 2
-2 1
2 2

0 3
2 5
Editor is loading...