How can I print the following 2D array? - c

#include <stdio.h>
#include <stdlib.h>
int ** letters (int*arr, int nr_elem)
{
char **mat=(char**)malloc( nr_elem * sizeof(char*));
int max =0;
for (int i =0; i<nr_elem;i++)
{
if( *(arr + i) > max)
max = *(arr + i);
}
for (int i=0; i<nr_elem; i++)
{
*mat=(char*)malloc((*(arr+i))*sizeof(char));
}
for(int i=0; i<nr_elem;i++)
{
for(int j=0; j<(*(arr+i)); j++)
{
mat[i][j] = 'a'+ (*(arr+i))-1;
printf("mat[%d][%d] = %c\n", i, j, mat[i][j]);
}
}
}
int main()
{
int a[] = {3, 4, 5, 2, 3};
int n = 5;
letters(a, n);
return 0;
}
My final goal is to make the function print a matrix with 5 rows on which it will print the corresponding letter from array a, that same amount of times. For example line 1, will have letter 'c' printed 3 times, line 2 will have 'd' printed 4 times etc.
For now I just want to print the matrix (i know the rest is not completely implemented, but I want to see what i have so far). it will show me that :
m[0][0] = 'c'
m[0][1] = 'c'
m[0][2] = 'c'
m[1][0] = 'd'
m[1][1] = 'd'
m[1][2] = 'd'
m[1][3] = 'd'
but then it cracks. Why?

You have an error in the second for loop inside your letters function, where you should be allocating a char* pointer to each element of mat:
for (int i=0; i<nr_elem; i++)
{
// *mat=(char*)malloc((*(arr+i))*sizeof(char)); // *mat keeps getting overwritten!
mat[i] = malloc((*(arr+i))*sizeof(char)); // Allocates new block for each loop
}
In your code, your only ever assign the return from malloc to the first element of the mat array - each loop just overwrites the previously assigned value (i.e. *mat is the same as mat[0]).
Also, please see this post on (not) casting the return value of malloc: Do I cast the result of malloc?

Related

Does this code have anything to do with pointers?

Could somebody help me with this piece of code.
I have no idea that what it does.
#include <stdio.h>
int main()
{
int arr[5],i;
int a = 1, n = 5;
for (i=0; i<5;a+= arr[i++]);
int d = a;
printf("%d",d);
}
technically this code has pointers. That is because arrays are pointers to the values that are stored in it(arr[0-5]). Every Element of the array points to a Adress anywhere in the memory.
int main()
{
int arr[10];
unsigned int x;
for(x = 0; x < 9; x++)
{
arr[x] = x;
printf("%d ", *(arr+x));
}
return 0;
}
in this code you can see that you can use an pointer notation to navigate trough an array.
now to your second question. the code that you gave us here is first initializing a array with 5 elements, a int named 'i', a int named 'a' with the value 1, and a int named 'n' that has the value 5.
then you go into a for loop that repeats 5 times. in the for loop you give a the value of the array[i]. but because the array is not filled with numbers it comes a number that is anywhere in the memory.
next you give the variable 'd' the value of 'a'. and at least you print 'd'.
I think that you want it so that you go into a loop and it prints the elements of the array.
int main()
{
int arr[5], i, a = 1, d;
for(i = 0; i < 5; i++)
arr[i] = i;
for(i = 0; i < 5; i++)
{
a = arr[i];
d = a;
printf("%d ", d);
}
return 1;
}
i think that is what you want.
Of note, we've not put anything of interest into arr, however notice the semicolon on the end of this line:
for (i=0; i<5;a+= arr[i++]);
That's a succinct (confusing?) way of saying
for (i=0; i<5; i++)
{
a += arr[i];
}
So a is summing up whatever is in arr.

C - Double pointer array - not getting correct values

Context
I created this simple code where I store various arrays in my_arrays() function and different functions (in my example the main()) can get the hard-coded arrays via the function my_arrays().
See the code here:
#include <stdio.h>
int my_arrays(int *size, int **arrays) {
size[0] = 3;
int array_1[3] = {1, 2, 3};
arrays[0] = array_1;
size[1] = 5;
int array_2[5] = {2, 3, -5, 7, 11};
arrays[1] = array_2;
}
int main() {
int num_of_arrays = 2;
int sizes[2];
int *arrays[2];
my_arrays(sizes, arrays);
for (int i=0; i < num_of_arrays; i++) {
int *array = arrays[i]; // point to sub-array
int size = sizes[i];
printf("array[%d]: {", i);
for (int x=0; x < size; x++) {
printf(" %d", array[x]);
}
printf(" }\n", i);
}
return 0;
}
In the main() I then loop through the sub-arrays and loop through each individual number and print it out.
What I expect the code above to print out is:
array[0]: { 1 2 3 }
array[1]: { 2 3 -5 7 11 }
But when compiling and running I get this:
array[0]: { 1993067712 1617605192 -2 }
array[1]: { 3936256 8 6422188 7 6422476 }
Why?
In my_arrays, array_1 and array_2 are local arrays on the stack. They will be invalid as soon as you return from my_array. Now arrays[0] and arrays[1] hold pointers to invalid or "stale" memory. Accessing that is undefined behaviour.
(The garbage values you see shows you that your arrays have been overwritten by other uses of the stack space, probably by calls to printf.)
If you want to create arrays, you can allocate memory on the heap:
int my_arrays(int *size, int **arrays)
{
size[0] = 3;
arrays[0] = malloc(3 * sizeof(int));
arrays[0][0] = 1;
arrays[0][1] = 2;
arrays[0][2] = 3;
// ... initialize other arrays ...
return 0;
}
You should explicitly free it after you're done using it:
// at the end of main
for (int i=0; i < num_of_arrays; i++) {
free(arrays[i]);
}

My code doesn't returns an output. It returns only exit code

I wanted to reverse half of the arrays inputs with the other half.
#include <stdio.h>
#include <math.h>
void main() {
double size = 5;
int array[5] = {1, 2, 3, 4, 5};
int half_size = ceil(size / 2);
for(int i = 0; i < half_size; i++){
int a;
int rev = size - (i + 1);
array[i] = a;
array[i] = array[rev];
array[rev] = a;`enter code here`
}
printf("%d", array[5]);
}
I agree with #Eugene Sh.'s and #FredK's suggestions. The line array[5] in the line printf("%d", array[5]); is out of bound since array only have indexes from 0 to 4. Since I assume you want to print out the last element in the array, you should change it to printf("%d", array[4]);. Another thing is that your assignment expression array[i] = a; is wrong. I assume the expression is part of the swapping process from element in index i with element in index rev. If that was the case then you should change it to a = array[i]; instead. I update you code according to my suggestion and it outputs the correct result. I added the for loop to verify that the array values are reversed for testing purpose. You can delete it after you're done testing.
#include <math.h>
int main() {
double size = 5;
int array[5] = {1, 2, 3, 4, 5};
int half_size = ceil(size / 2);
for(int i = 0; i < half_size; i++){
int a;
int rev = size - (i + 1);
a = array[i];
array[i] = array[rev];
array[rev] = a;
}
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
printf("%d", array[4]);
}

RUN FAILED exit value 5 trying to swap arrays

/*Jeremy Johnson 11-18-48
*
*The purpose of this program to to swap halves of an array. So {1 2 3 4 5 6}
*becomes {4 5 6 1 2 3} using pointer notation.
*/
#include <stdio.h>
#include <string.h>
int array[] = {1, 2, 3, 4, 5, 6}; //initialize array
void mirror(int* array, int from_index, int to_index); //prototype statment
int main() {
//define and assign pointer to array address
int *arrptr, i;
arrptr = &array[0];
//print original array
printf("Original Array: \n");
for (i = 0; i <= 5; i++) {
printf("%d", array[i]);
}
printf("\n");
//call function to swap values and mirror the array
mirror(arrptr, 0, 2);
mirror(arrptr, 3, 5);
mirror(arrptr, 0, 5);
mirror(arrptr, 1, 4);
mirror(arrptr, 2, 3);
//print final array
printf("Mirror Array: \n");
for (i = 0; i <= 5; i++) {
printf("%d", array[i]);
}
printf("\n");
return 0;
}
void mirror(int* array, int from_index, int to_index) {
//create pointer for temporary memory storage
int *temp, c[1];
temp = &c[0];
//Place to_index in temporary memory
*(temp) = *(array + to_index-1);
//Copy from_index to to_index
*(array + to_index-1) = *(array + from_index-1);
//Copy temporary value back into from_index
*(array + from_index-1) = *(temp);
return;
}
/* This code works for the function however I am not allowed to use array
notation.
c[1]=array[to_index];
array[to_index]=array[from_index];
array[from_index]=c[1]; */
I am trying to swap each half of the array; I have done so by switching the indices of the arrays by calling the mirror function 5 times and swapping the appropriate values. I was able to do so using the commented code at the bottom in place of the current function code, but now I receive and exit value 5, and I'm not sure why. (I receive no other errors within the code)
// perhaps swap the array by:
void mirror( int*, int* );
int main()
{
...
int *pSecondHalf = array[(sizeof(array)/sizeof(int))>>1];
// note: above line will not work for odd size array so:
if( array[(sizeof(array)/sizeof(int)] & 0x01 )
{
pSecondHalf++; // middle term in odd size array will not move
}
int *pFirstHalf = array;
const int *pLastHalf = array+((sizeof(array)/sizeof(int))>>1);
// note: following 'for' loop will execute one extra time
// for odd size array, but nothing will be changed
for( ; pFirstHalf < pLastHalf; pFirstHalf++, pSecondHalf++ )
{
mirror( pFirstHalf, pSecondHalf );
}
...
return(0);
}
// and in mirror()
void mirror( int *pVal1, int* pVal2)
{
int temp = *pVal1;
*pVal1 = *pVal2;
*pVal2 = temp;
}
The problem was in the mirror function. I did not move each element of the array to the temporary array using a for loop (aka counting loop). I added two loops to the function and it runs fine now.
/*Jeremy Johnson 11-18-48
*
*The purpose of this program to to swap halves of an array. So {1 2 3 4 5 6}
*becomes {4 5 6 1 2 3} using pointer notation.
*/
#include <stdio.h>
#include <string.h>
int array[] = {1, 2, 3, 4, 5, 6}; //initialize array
void mirror(int* array, int from_index, int to_index); //prototype statement
int main() {
//define and assign pointer to array address
int *arrptr, i;
arrptr = &array[0];
//print original array
printf("Original Array: \n");
for (i = 0; i <= 5; i++) {
printf("%d", array[i]);
}
printf("\n");
//call function to swap values and mirror the array
mirror(arrptr, 0, 2);
mirror(arrptr, 3, 5);
mirror(arrptr, 0, 5);
//print final array
printf("Mirror Array: \n");
for (i = 0; i <= 5; i++) {
printf("%d", array[i]);
}
printf("\n");
return 0;
}
void mirror(int* array, int from_index, int to_index) {
//create pointer for temporary memory storage
int *temp, c[6], j;
temp = &c[0];
//Place array elements in temporary memory
for (j = 0; j < 6; j++) {
*(temp + j) = *(array + j);
}
//Place mirrored halves in array respectively
for (j = 0; j <= (to_index - from_index); j++) {
*(array + from_index + j) = *(temp + to_index - j);
}
return;
}

Iterating 2D array with pointer expressions in C

I'm practicing pointers and want to substitute pointer operations in place of the arrays to traverse through the elements of the array. I have read numerous articles and cannot grasp this concept. Can someone explain?
Here I made a 2D array and iterated through it using a basic nested for-loop, but want to use pointers;
int test[3][2] = {1,4,2,5,2,8};
for (int i = 0 ; i < 3; i++) {
for (int j = 0; j < 2; j++) {
printf("%d\n", test[i][j]);
}
}
int test[3][2] = {{1,4},{2,5},{2,8}};
// Define a pointer to walk the rows of the 2D array.
int (*p1)[2] = test;
// Define a pointer to walk the columns of each row of the 2D array.
int *p2 = NULL;
// There are three rows in the 2D array.
// p1 has been initialized to point to the first row of the 2D array.
// Make sure the iteration stops after the third row of the 2D array.
for (; p1 != test+3; ++p1) {
// Iterate over each column of the arrays.
// p2 is initialized to *p1, which points to the first column.
// Iteration must stop after two columns. Hence, the breaking
// condition of the loop is when p2 == *p1+2
for (p2 = *p1; p2 != *p1+2; ++p2 ) {
printf("%d\n", *p2);
}
}
In some compilers you can also use a single loop, treating a multidimensional array as a one-dimensional array read in row-major order.
This is mentioned in King's C Programming: A Modern Approach (2nd ed., p268).
#include <stdio.h>
int main(void)
{
int test[3][2] = {{1,4},{2,5},{2,8}}, *p;
for(p = &test[0][0]; p <= &test[2][1]; p++)
{
printf("%d\n", *p);
}
return 0;
}
Try the following and investigate
#include <stdio.h>
int main(void)
{
int test[3][2] = { { 1,4 }, { 2,5 }, { 2,8 } };
for ( int ( *p )[2] = test ; p != test + 3; ++p )
{
for ( int *q = *p; q != *p + 2; ++q ) printf( "%d ", *q );
puts( "" );
}
return 0;
}
The putput is
1 4
2 5
2 8
The first pointer is a pointer to an object of type int[2] that is it points to the first "row" of the array and then due to increments it points to other rows.. The second pointer is a pointer to an object of type int. It points to the first element of each row in the inner loop.
Treating a 2d array as 1d array is very easy using pointer arithmetic to iterate.
void print_2d_array(int *num, size) {
int counter = 0;
while (counter++ < size) {
printf("%i ", *num);
num++;
}
printf("\n");
}
int main() {
int matrix[2][3] = {{2, 11, 33},
{9, 8, 77}};
int matrix_size = sizeof(matrix) / sizeof(int); // 24 bytes / 4 (int size) = 6 itens
print_2d_array(matrix, matrix_size);
return 0;
}
If pointer declaration is the goal of your practice, use the following initialization:
int (*pTest)[rmax][cmax] = test;
Once you do that, the syntax of using pointer indexing mirrors that of array indexing, except that you have to use the * de-referencing operator.
for (int i= 0; i < 3; i++) {
for (int j= 0; j < 2; j++) {
printf ("%d ", *(pTest[i][j]));
}
printf ("\n");
}
However, if pointer arithmetic is the goal of your practice, then the following will work too:
int *res = &test;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
printf ("%d ", *(res + i*2 + j));
}
printf ("\n");
}
OUTPUT
1 4
2 5
2 8

Resources