Print values of a 2D Dynamic matrix - c

i cannot find solution how to solve this.
rows number is easy one. reading from keyboard and allocation but column number is different for each row.
lets assume user entered 2 rows after that user entered 3 column for row 0 and 10 column for row 1
and i dont know how to enter values for these columns and print them. because every column has different length. unfortunately != NULL not working
int** ptr; int rows, columns;
printf("enter number of rows..\n");
scanf("%d", &rows);
ptr = (int**)calloc(rows, sizeof(int*));
for (size_t i = 0; i < rows; i++) // allocation an array of integers for every row
{
printf("enter number of columns..\n");
scanf("%d", &columns);
ptr[i] = (int*)calloc(columns, sizeof(int));
}
for (size_t i = 0; i < rows; i++){
for (size_t j = 0; ptr[i][j] != NULL; j++)
ptr[i][j] = j;
}
for (size_t i = 0; i < rows; i++){
for (size_t j = 0; ptr[i][j] != NULL; j++)
printf("%d\n", ptr[i][j]);
}

Since C arrays don't have a final delimiter, then you need to store the length in an efficient way:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main()
{
int** ptr; int rows, columns;
printf("enter number of rows..\n");
scanf("%d", &rows);
ptr = (int**)calloc(rows, sizeof(int*));
for (size_t i = 0; i < rows; i++) // allocation an array of integers for every row
{
printf("enter number of columns..\n");
scanf("%d", &columns);
ptr[i] = (int*)calloc(columns+1, sizeof(int)); // Last pos will save the size
// We need to track the columns since C arrays do not have a final delimiter
ptr[i][columns] = INT_MIN; // It could also be INT_MAX depending on our needs
}
for (size_t i = 0; i < rows; i++){
for (size_t j = 0; ptr[i][j] != INT_MIN; j++)
ptr[i][j] = j;
}
for (size_t i = 0; i < rows; i++)
{
printf("Line %li\n", i);
for (size_t j = 0; ptr[i][j] != INT_MIN; j++)
{
printf(" Column %li: ", j);
printf("%d\n", ptr[i][j]);
}
}
return 0;
}

Related

Sorting variable length Rows using Array of Pointers

hi this is my code can you help me out not printing output properly how to print output given in description , i am not getting way to sort the given output, output should be sorted from given average.
Implement fragments using array of pointers.
Rows are static and columns are dynamic. Fixed no.of rows and columns will vary for each row.
Example:
Read no.of rows from user and allocate the memory statically for rows.
Read no.of columns for each row and allocate the memory dynamically.
Let us Assume, Row = 3.
Row[0] = 4 columns, Row[1] = 3 columns and Row[2] = 5 columns.
While allocating the memory for columns you have allocate for no.of columns + 1 dynamically.
After that read the values from user and calculate the average for each row separately and store that average in that extra memory block which you added while allocating the memory.
Then sort the array based on the average.
Print the output on the screen.
Example is given below.
ENTER THE NUMBER OF ARRAY YOU WANT TO GIVE AS INPUT: 3
ENTER NO. OF COLUMNS IN ROW[0]: 3
ENTER NO. OF COLUMNS IN ROW[1]: 3
ENTER NO. OF COLUMNS IN ROW[2]: 3
ENTER 3 VALUES OF ROW[0]: 2 3 5
ENTER 3 VALUES OF ROW[1]: 2 4 7
ENTER 3 VALUES OF ROW[2]: 2 1 0
BEFORE SORTING OUTPUT IS:
2 3 5 3.33333
2 4 7 4.33333
2 1 0 1
AFTER SORTING OUTPUT IS:
2 1 0 1
2 3 5 3.33333
2 4 7 4.33333
My code so far:
#include <stdio.h>
#include <stdlib.h>
int fragments(int rows, int *array)
{
int i, j;
int pos[rows];
float *arr[rows], avg, sum;
char *temp[rows];
for (i = 0; i < rows; i++)
{
arr[i] = malloc(sizeof(float*) * array[i]+1);
pos[i] = i;
printf("Enter %d values for row[%d]: ", array[i], i);
for (j = 0; j< array[i]; j++)
{
scanf(" %f", &arr[i][j]);
}
}
printf("Before Sorting output is:\n");
for (i = 0; i < rows; i++)
{
sum = 0;
for (j = 0; j < array[i]; j++)
{
printf("%f ", arr[i][j]);
sum = sum + arr[i][j];
}
printf("%f\n", arr[i][j] = (sum / j));
}
for (i = 0; i < rows - 1; i++)
{
for (j = 0; j < rows - i - 1; j++)
{
if (arr[j][array[j]] > arr[j+1][array[j+1]])
{
temp[j][j] = arr[j][array[j]];
arr[j][array[j]] = arr[j+1][array[j+1]];
arr[j+1][array[j+1]] = temp[j][j];
}
}
}
for (i = 0; i < rows; i++)
{
for (j = 0; j < array[i] + 1; j++)
{
printf("%f ", arr[i][array[j]]);
}
printf("\n");
}
}
int main()
{
int rows, i, j;
printf("Enter no of rows: ");
scanf("%d", &rows);
int array[rows];
int pos[rows];
for (i = 0; i < rows; i++)
{
printf("Enter no of columns in row[%d]:", i);
scanf("%d", &array[i] );
}
fragments(rows, array); //`enter code here`
}
There are multiple problems in your code:
The allocation size is incorrect: arr[i] = malloc(sizeof(float*) * array[i]+1); should read:
arr[i] = malloc(sizeof(float) * (array[i] + 1));
the swapping code should swap the array pointers and the array sizes. The current code does not make sense. Use this instead:
float *temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
int temp1 = array[j];
array[j] = array[j+1];
array[j+1] = temp1;
the final print loop is incorrect: instead of printf("%f ", arr[i][array[j]]); you should write:
printf("%f ", arr[i][j]);
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
int fragments(int rows, int *array) {
float *arr[rows];
for (int i = 0; i < rows; i++) {
arr[i] = malloc(sizeof(float) * (array[i] + 1));
printf("Enter %d values for row[%d]: ", array[i], i);
for (int j = 0; j < array[i]; j++) {
if (scanf("%f", &arr[i][j]) != 1)
return;
}
}
printf("Before Sorting output is:\n");
for (int i = 0; i < rows; i++) {
float sum = 0;
for (j = 0; j < array[i]; j++) {
printf("%f ", arr[i][j]);
sum += arr[i][j];
}
printf("%f\n", arr[i][j] = sum / j);
}
for (int i = 0; i < rows - 1; i++) {
for (int j = 0; j < rows - i - 1; j++) {
if (arr[j][array[j]] > arr[j+1][array[j+1]]) {
float *temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
int temp1 = array[j];
array[j] = array[j+1];
array[j+1] = temp1;
}
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < array[i] + 1; j++) {
printf("%f ", arr[i][j]);
}
printf("\n");
}
for (int i = 0; i < rows; i++) {
free(arr[i]);
}
}
int main() {
int rows;
printf("Enter no of rows: ");
if (scanf("%d", &rows) != 1)
return 1;
int array[rows];
for (int i = 0; i < rows; i++) {
printf("Enter no of columns in row[%d]:", i);
if (scanf("%d", &array[i]) != 1)
return 1;
}
fragments(rows, array);
return 0;
}

Why do I keep printing out the memory address instead of array values?

So I'm trying to print out an array of 2d arrays (you can think of the whole thing as a 3d array) where the user decides the size of the outer array, as well as rows and column size of the 2d inner arrays. I've now made 2 functions, one to initialize the arrays and one to print them.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int arrays, rows, columns;
int ***tables;
printf("\nEnter the number of arrays (0 to quit): ");
scanf("%d", &arrays);
while (arrays !=0){
printf("\n Enter values for rows, columns (e.g: 2 3): ");
scanf("%d %d", &rows, &columns);
tables = (int ***) calloc (arrays, sizeof (int**));
initarrays(tables, arrays, rows, columns);
printarrays(tables, arrays, rows, columns);
printf("Enter the number of arrays (0 to quit): ");
scanf("%d", &arrays);
}
return 0;
}
void initarrays(int ***nTables, int nArrs, int row, int column){
for (int i = 0; i < nArrs; i++){
nTables[i] = (int **)malloc(row * sizeof(int *));
if (nTables[i] == NULL){
fprintf(stderr, "Out of Memory");
exit (0);
}
for (int j = 0; j < row; j++){
nTables[i][j] = (int *)malloc(column * sizeof(int));
if (nTables[i][j] == NULL){
fprintf(stderr, "Out of Memory");
exit (0);
}
}
}
// Assign values to allocate memory for each array except for last
for (int i = 0; i < nArrs; i++){
for (int j = 0; j < row; j++){
for (int k = 0; k < column; k++){
nTables[i][j][k] = 1;
}
}
}
//Assign values for last array
for (int i = nArrs; i < nArrs+1; i++){
for (int j = 0; j < row; j++){
for (int k = 0; k < column; k++){
nTables[i][j][k] = 0;
}
}
}
// free up allocated memeory
for (int i = 0; i < nArrs; i++){
for (int j = 0; j < row; j++){
free(nTables[i][j]);
}
free (nTables[i]);
}
free(nTables);
}
void printarrays(int ***nTables, int nArrs, int row, int column){
// print out the values in the arrays
for (int i = 0; i < nArrs; i++){
for (int j = 0; j < row; j++){
for (int k = 0; k < column; k++){
printf("%2i ",nTables[i][j][k]);
}
printf("\n");
}
printf("\n");
}
}
Within the outer array, I need to make sure the last 2d array is one that is full of 0s, whereas the preceding ones are full of 1s. I'm not sure if one of my pointers is incorrect, my memory allocation is off, or my iteration is wrong when initializing, but for some reason, my output is always a mix of memory addresses and array values instead of just the array values that I need them to be. I basically want to print several 2d arrays of 1s, and then one more array with 0s. Any help would be great, thanks.

initialization of arrays while operating with mallocs

Given the following piece of code, I don't understand why do we have to initialize every single row of the matrix when we have already created enough space in the stack.
#include <stdio.h>
#include <stdlib.h>
main() {
int **w;
int i, j;
int m, n;
printf("Number of rows in the matrix: ");
scanf("%d", &m);
printf("Number of columns in the matrix: ");
scanf("%d", &n);
w = (int **)malloc(m * n * sizeof(int));
for (i = 0; i < m; i++)
w[i] = (int *)malloc(n * sizeof(int));
for (i = 0; i < m; i++)
for (j = 0; j < n; j++) {
printf("Element [%d][%d]: ", i + 1, j + 1);
scanf("%d", &w[i][j]);
}
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
printf("Element [%d][%d]: %d\n", i + 1, j + 1, w[i][j]);
}
There are many issues in your code:
space is not allocated on the stack, but from the heap.
in both cases, memory allocated for the objects is uninitialized, which means it is not initialized to anything in particular and can have any value whatsoever. Relying on any particular contents is undefined behavior.
the matrix dimensions and all the matrix elements are read from standard input with scanf(). Yet you do not check for scanf() failure to convert integers from the characters read from stdin, so any invalid or missing input is going to cause undefined behavior at some point in the program.
your matrix is actually structured as an array of pointers to arrays of int, which is fine, but inconsistent with the size arguments used to allocate the first array: w = (int **)malloc(m * n * sizeof(int)); should be
w = malloc(m * sizeof(*w));
you could easily get objects pre-initialized to 0 by using calloc() instead of malloc():
for (i = 0; i < m; i++)
w[i] = calloc(n, sizeof(int));
you should also check for malloc() failure and exit with an appropriate diagnostic message.
main() is an obsolete prototype for the main function. You should either use int main(), int main(void) or int main(int argc, char *argv[])...
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
int get_int(void) {
int n;
if (scanf("%d", &n) != 1) {
printf("invalid input\n");
exit(EXIT_FAILURE);
}
return n;
}
void xalloc(size_t size) {
void *p = calloc(size, 1);
if (p == NULL) {
printf("out of memory for %zu bytes\n", size);
exit(EXIT_FAILURE);
}
return p;
}
int main() {
int **w;
int i, j;
int m, n;
printf("Number of rows in the matrix: ");
m = get_int();
printf("Number of columns in the matrix: ");
n = get_int();
w = xalloc(m * sizeof(*w));
for (i = 0; i < m; i++) {
w[i] = xalloc(n * sizeof(int));
}
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("Element [%d][%d]: ", i + 1, j + 1);
w[i][j] = get_int();
}
}
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("Element [%d][%d]: %d\n", i + 1, j + 1, w[i][j]);
}
}
for (i = 0; i < m; i++) {
free(w[i]);
}
free(w);
return 0;
}

Sum of elements in a matrix using threads in c

The problem statement goes like this: Calculate the sum of the elements in a bidimensional matrix, using a separate thread to calculate the sum of each row. The main thread adds up these sums printing the final result.
From what I have seen so far, the code runs correctly. The only issue is when I choose the number of rows to be smaller than the number of columns (e.g. rows = 2, columns = 3), because it only computes the sum for the first 2 columns, completely ignoring the third one.
This is the code I wrote in C and I would really appreciate any help understanding what I did wrong or missed. Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define M 10
#define N 10
int rows, columns, a[M][N], s[M];
// compute the sum of each row
void* f(void* p) {
int k = *((int*) p);
int i;
for (i = 0; i < columns; i++) {
s[i] += a[k][i];
}
return NULL;
}
int main() {
int i, j, *p, rc;
int sum = 0;
pthread_t th[M];
// matrix creation
printf("no. of rows = ");
scanf("%d", &rows);
printf("no. of columns = ");
scanf("%d", &columns);
for (i = 0; i < rows; i++) {
for (j = 0; j < columns; j++) {
printf("a[%d][%d] = \n", i, j);
scanf("%d", &a[i][j]);
}
}
printf("\nThe matrix is: \n");
for(i=0; i < rows; i++) {
for(j=0; j < columns; j++)
printf("%d ", a[i][j]);
printf("\n");
}
// thread creation
for (i=0; i < rows; i++) {
p = malloc(sizeof(int));
*p = i;
rc = pthread_create(&th[i], NULL, f, p);
if (rc != 0) {
printf("Thread creation failed");
exit(-1);
}
}
for (i=0; i < rows; i++) {
pthread_join(th[i], NULL);
}
// compute the final sum
for (i=0; i < rows; i++) {
sum += s[i];
}
printf("The sum is = %d\n", sum);
return 0;
}
You need
s[k] += a[k][i];
instead of
s[i] += a[k][i];
Sum of each rows should be added up in each index of each row as s is declared as s[M].

Overwrite character in an array using C

I'm creating a dynamic 2d character array in C:
Note: rows and columns are user input integers
char** items;
items = (char**)malloc(rows * sizeof(char*));
int i;
for(i = 0; i < rows; i++)
{
items[i] = (char*)malloc(columns * sizeof(char));
}
int j;
for(i = 0; i < rows; i++)
{
for(j = 0; j < columns; j++)
{
items[i][j] = 'O';
}
}
Later in my code, I attempt to overwrite a specific location in the array:
items[arbitraryRow][arbitraryColumn] = 'S';
But the result is that the characters in that row/column are now 'SO'
What am I doing wrong?
Update:
This is how I'm printing the array:
int i;
for(i = 0; i < rows; i++)
{
printf("[");
int j;
for(j = 0; j < columns; j++)
{
printf("'%s'", &items[i][j]);
if(j != columns - 1)
printf(", ");
}
printf("]");
printf("\n");
}
You're not storing strings you're storing characters so all you can read is one character so that'd be the S
My suspision is that the next character is an O so when you look at it as a string you get SO
printf("'%c'", items[i][j]);
You are storing characters and reading strings. Try reading character back from the Array.
Change your code to:
int i;
for(i = 0; i < rows; i++)
{
printf("[");
int j;
for(j = 0; j < columns; j++)
{
printf("'%c'", items[i][j]);
if(j != columns - 1)
printf(", ");
}
printf("]");
printf("\n");
}

Resources