Printing 2D Array using pointers in C - c

#include "stdio.h"
void main(){
int a[2][2]={1, 2, 3, 4};
int a[2][2]={1, 2, 3, 4};
display(a, 2, 2);
show(a, 2, 2);}
}
display(int *k, int r, int c){
int i, j, *z;
for(i = 0; i < r; i++){
z = k + i;
printf("Display\n");
for(j = 0; j < c; j++){
printf("%d", *(z + j));
}
}
}
show(int *q, int ro, int co){
int i, j;
for(i = 0; i < ro; i++){
printf("\n");
for(j = 0; j < co; j++){
printf("%d", *(q + i*co + j));
}
}
}
Output:
Display
12
23
Show
12
34
Why Display() is not showing 1223 while show() gives 1234? Both uses the same logic to display the 2d array. Can any one help please?

In display you are using two counters, i for rows and j for columns. Since the array is laid out sequentially in memory you need to increase i by the size of a column, i.e. c, each time you want to move from one row to the next. So, you should add i*c to k, not i.
The complete function:
display(int *k,int r,int c){
int i,j,*z;
for(i=0;i<r;i++){
z=k+i*c;
printf("Display\n");
for(j=0;j<c;j++){
printf("%d",*(z+j));
}
}
}

To access 2D array using pointers:
#define R 2
#define C 2
...
int A[R][C]={1, 2, 3, 4};
for(i=0;i<R;i++)
for(j=0;j<C;j++)
printf("%d ",*(*(A+i)+j));
...

Related

2D array, sort rows by sum

There is 2D array with pointers from user, filled with random numbers, program count sum of every row. I need to sort array by sum of every row and print it. For example if we have array:1 2 2 (sum=5)2 9 9 (sum=20)2 1 6 (sum=9)
output should be:1 2 2 (sum=5)2 1 6 (sum=9)2 9 9 (sum=20). Thanks for help.
int main () {
int i, j, row, column, **array,sum;
time_t seconds;
time (&seconds);
srand ((unsigned int)seconds );
printf ("Write number of rows:");
scanf ("%d", &row);
printf ("Write number of columns:");
scanf ("%d", &column);
array=(int**) malloc (row * sizeof(int *));
if (array!=NULL){
for (i=0; i<row;i++)
array[i]= (int*) malloc (column *sizeof(int));
}
for (i=0; i<row;i++)
for (j=0; j<column;j++)
array[i][j]=(rand()%100);
for (i=0; i<row;i++){
for (j=0; j<column;j++)
printf("%d ",array[i][j] );
printf ("\n");
}
for(i=0;i<row;i++){ //find sum of each row
sum=0;
for(j=0;j<column;j++){
sum=sum+array[i][j];
}
printf("%d \n",sum);
}
return 0;
}
sample of option 1
#include <stdio.h>
#include <stdlib.h>
int COLUMNS;
int sum(int len, int *array){
int i, sum = 0;
for(i=0; i<len; ++i)
sum += *array++;
return sum;
}
int cmp(const void *a, const void *b){
int sum1 = sum(COLUMNS, *(int**)a);
int sum2 = sum(COLUMNS, *(int**)b);
return (sum1 > sum2) - (sum1 < sum2);
}
int main(void){
int i, j, row, column, **array;
row = 3; column = 3;
array = (int**) malloc (row * sizeof(*array));//cast of (int**) is redundant.
array[0] = (int []){1, 2, 2};
array[1] = (int []){2, 9, 9};
array[2] = (int []){2, 1, 6};
COLUMNS = column;//size of columns pass to compare function by global variable.
qsort(array, row, sizeof(*array), cmp);
for (i=0; i<row;i++){
for (j=0; j<column;j++)
printf("%d ",array[i][j] );
printf ("\n");
}
free(array);
return 0;
}
sample of option 2
#include <stdio.h>
#include <stdlib.h>
int sum(int len, int *array){
int i, sum = 0;
for(i=0; i<len; ++i)
sum += *array++;
return sum;
}
typedef struct pair {
int *p;//or index
int sum;
} Pair;
int cmp(const void *a, const void *b){
Pair const *x = a;
Pair const *y = b;
return (x->sum > y->sum) - (x->sum < y->sum);
}
int main(void){
int i, j, row, column, **array;
row = 3; column = 3;
array = (int**) malloc (row * sizeof(*array));//cast of (int**) is redundant.
array[0] = (int []){1, 2, 2};
array[1] = (int []){2, 9, 9};
array[2] = (int []){2, 1, 6};
Pair *temp = malloc(row * sizeof(*temp));
for(i = 0; i < row; ++i){
temp[i].p = array[i];
temp[i].sum = sum(column, array[i]);
}
qsort(temp, row, sizeof(*temp), cmp);
for (i=0; i<row;i++){
for (j=0; j<column;j++)
printf("%d ", temp[i].p[j] );
printf ("\n");
}
free(temp);
free(array);
return 0;
}

passing 2d array in c using pointer to pointer by typecasting

How to pass a 2D array as a parameter in C?
I was searching to pass a 2d array to a function in c and I came across the above site. I understood the first and second way of passing 2d array, but I got
confused in the 3rd method, specifically, how is it even working that way?`
3) Using an array of pointers or double pointer
In this method also, we must typecast the 2D array when passing to function.
#include <stdio.h>
// Same as "void print(int **arr, int m, int n)"
void print(int *arr[], int m, int n)
{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
printf("%d ", *((arr+i*n) + j));
}
int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int m = 3;
int n = 3;
print((int **)arr, m, n);
return 0;
}
Output:
1 2 3 4 5 6 7 8 9
`
The above code works fine on codeblocks.
When calling print() from main(), we pass arr as argument by typecasting it to pointer to pointer , but in the function print() it dereferences only once to print the values. printf("%d ", *((arr+i*n) + j));
Shouldn't it be *((*arr+i*n) + j));, I tried compiling this statement , it compiles but doesn't execute.
2) Using a single pointer
In this method, we must typecast the 2D array when passing to function.
#include <stdio.h>
void print(int *arr, int m, int n)
{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
printf("%d ", *((arr+i*n) + j));
}
int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int m = 3, n = 3;
print((int *)arr, m, n);
return 0;
}
Output:
1 2 3 4 5 6 7 8 9
`
The 2nd method and the 3rd method only differ in the type of argument passed in the print() function while rest of the code is same. So what is actually the difference between the working of the functions?
easiest way to pass 2D array,
function
void PrintArray(unsigned char mat[][4]){
int i, j;
printf("\n");
for(i = 0;i<4;i++){
for(j = 0;j<4;j++)
printf("%3x",mat[i][j]);
printf("\n");
}
printf("\n");
}
main
int main(){
int i,j;
//static int c=175;
unsigned char state[4][4], key[4][4], expandedKey[176];
printf("enter the value to be decrypted");
for(i=0;i<4;i++)
for(j=0;j<4;j++)
scanf("%x",(unsigned int *)&state[j][i]);
PrintArray(state);
return 0;
}

breadth-first search in C language

I have two integer lists say list_a and list_b.
I have a function say func(), and func(list_a) would produce n lists say:
list_a_1 list_a_2 list_a_3 list_a_4 ........... list_a_n
I have to run func() on all lists as produced above until I find one of those lists = list_b.
So below could be the possible representation of how the list grows:
list_a
============================================================================
list_a_1 list_a_2 list_a_3 list_a_4 ........... list_a_n LEVEL 1
============================================================================
list_a_1_1.... list_a_1_n list_a_2_1... list_a_2_n..... LEVEL 2
============================================================================
Suppose say we find list_a_1_n == list_b, then stop the function and return the LEVEL, which in our case is 2 (Level2).
I am not being able to do it :(
How to do it in C?
Please note, this is not a homework question.
I am trying to find Cyclic Kendal Tau distance between two inputs as I think I found a solution in terms of algorithm for this question. I want to check whether my algorithm is correct.
below is the code in Python:
import collections
def Transpose(alist):
leveloutput = []
n = len(alist)
for i in range(n):
x=alist[:]
x[i],x[(i+1)%n] = x[(i+1)%n],x[i]
leveloutput.append(x)
return leveloutput
def Cyc_Ken_Tau(start, goal):
queue = collections.deque([(start, 0)])
while True:
element, level = queue.popleft()
if element == goal:
return level
for new_list in Transpose(element):
queue.append((new_list, level + 1))
if __name__ == '__main__':
print "***********************************************************"
u = [2, 3, 4, 1]
v = [1, 2, 4, 3]
print "***********************************************************"
m = Cyc_Ken_Tau(u,v)
print "Cyclic Kendal Tau:",m
Also the partial code in C is as follows:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print_array(int **a, int num_elements);
int **transpose(int n, int arr[n]);
int main(){
int a[] = {2, 3, 4, 1};
int **c;
int n = sizeof(a)/sizeof(*a);
int i;
printf("original\n");
print_array2(a,4);
printf("\n*****************************\n");
c= transpose(n, a);
print_array(c, n);
//deallocate
for(i=0;i<n;++i)
free(c[i]);
free(c);
return 0;
}
int **transpose(int n, int arr[n]){
int l = n;
int **b = malloc(l * sizeof(*b));//sizeof(*b) : sizeof(int *)
int i, j, k;
for (i = 0; i < l; i++) {
j = (i + 1) % l;
int *copy = malloc(l * sizeof(*copy));//sizeof(int)
for (k = 0; k < l; k++)
copy[k] = arr[k];
int t = copy[i];
copy[i] = copy[j];
copy[j] = t;
//printf("{%d, %d, %d, %d}\n", copy[0], copy[1], copy[2], copy[3]);
b[i] = copy;
}
return b;
}
void print_array(int **a, int num_elements){
int i, j;
for(i=0; i<num_elements; i++){
for(j=0; j<num_elements; j++)
printf("%d ", a[i][j]);
printf("\n");
}
}
void print_array2(int a[], int num_elements)
{
int i;
for(i=0; i<num_elements; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
But I am struggling with the Cyc_Ken_Tau function in C. Any help will be much much appreciated.

Printing contents of matrix by using pointer

Here is my assignment:
arrPrintMatrix(int *matrix, int m, int n): prints the content of the
matrix[m][n] to the screen in table format.
And here is my code:
#include <stdio.h>
#include <malloc.h>
int main() {
void arrPrintMatrix(int *matrix, int m, int n);
int matrix[2][3] = {{5, 10 , 15}, {0, 2, 4}};
int *ptr;
ptr = &matrix[0][0];
arrPrintMatrix(ptr, 2, 3);
return 0;
}
void arrPrintMatrix(int *matrix, int m, int n) {
int i, j;
for (i = 0; i < m; i++) {
printf("\n");
for (j = 0; j < n; j++) {
printf("%d\t", matrix[i] + j);
}
}
}
But when I run this code, I get 5 6 and 7 as first row, 10 11 and 12 as second row. So something wrong with matrix[i] + j. How should I fix this?
By the way, I'm so confused about arrays of pointers, malloc, pointers to functions, so generally I'm confused about pointers. I would be glad if you suggest some web pages or videos about that.
Change the line
printf("%d\t", matrix[i] + j);
to
printf("%d\t", matrix[i*n+j]);
Update
Layout of memory of 2D arrays is nicely explained in this article.
mChange:
matrix[i] + j
To:
matrix[(i*n)+j]

Multiplying two 3x3 matrices in C

I am trying to multiply two 3x3 matrices. The first 2 numbers in the first
and second row are the only correct answer. What am I doing
wrong? Is the stuff I need declared in mult_matrices?
#include <stdio.h>
void mult_matrices(int a[][3], int b[][3], int result[][3]);
void print_matrix(int a[][3]);
int main()
{
int p[3][3] = {{1, 2, 3},{4, 5, 6}, {7, 8, 9}};
int q[3][3] = {{10, 11, 12}, {13, 14, 15}, {16, 17, 18}};
int r[3][3];
mult_matrices(p, q, r);
print_matrix(r);
}
void mult_matrices(int a[][3], int b[][3], int result[][3])
{
int i, j, k;
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
for(k = 0; k < 3; k++)
{
result[i][j] += a[i][k] * b[k][j];
}
}
}
}
void print_matrix(int a[][3])
{
int i, j;
for (i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
printf("%d\t", a[i][j]);
}
printf("\n");
}
}
Make sure you initialize r to all zeros before you use it.
int r[3][3] = { 0 };
Looks like you're not initializing your result matrix.
i.e. Change:
int r[3][3];
to
int r[3][3] ={{0,0,0},{0,0,0},{0,0,0}};
One thing that I notice that you don't do is initialize you're r[3][3] array. I am not sure if this is the root of you're problem but it very well could be. Essentially what the values of r are set to is whatever was "left over" in memory in that location. Sometimes they will all be 0 but most likely they will not be. So it could be the issue you are having, but even if it isn't it is good to always get in a habit of initializing all of you're variables.
int main(){
int A[3][3],B[3][3],C[3][3],i,j;
printf("Please Enter 9 Numbers for First Matrix")
for(i=0;i<=2;i++){
for(j=0;j<=2;j++){
scanf("%d",A[i][j]);
}
}
printf("Please Enter 9 Numbers for Second Matrix")
for(i=0;i<=2;i++){
for(j=0;j<=2;j++){
scanf("%d",B[i][j]);
}
}
for(i=0;i<=2;i++){
for(j=0;j<=2;j++){
C[i][j]=A[i][j]+B[i][j]
printf("%d "C[i][j]);
}
printf("\n");
}
}

Resources