Does this code have anything to do with pointers? - c

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.

Related

Attempt to access elements of a 2d struct array failing

typedef struct{
unsigned long a;
unsigned long b;
unsigned long c;
} mini_struct;
struct ministruct** build_2Dstruct(unsigned long x, unsigned long y){
double x_squared = pow(2, x);
struct ministruct** temp = (mini_struct**)malloc(x*sizeof(mini_struct*));
for(int i = 0; i < x_squared; i++){
temp[i] = (mini_struct*)malloc(y*sizeof(mini_struct));
for(int j = 0; j < y; j++){
temp[i][j].a = 0;
etc....
}
}
return temp;
}
In the code above I am trying to create a 2D array of ministructs**, with the whole struct being made out of 2^x ministructs*, and each ministruct* has y amount of ministructs.
aka:
x = 2,
y = 2,
[[struct, struct], [struct, struct], [struct, struct], [struct, struct]]
However, for some reason when I try to access the second element or index 1 of the struct inside each struct*, it says there is an error: "expression must be pointer to complete object".
I just do not understand why the code is not allowing me to access each individual element of the elements of the array?
Thanks
You are trying to make an x by y array of structs. So:
// create array of x pointers
mini_struct **temp = malloc(x*sizeof(mini_struct*));
for (int i=0; i<x; i++) {
// to array of y structs
temp[i] = malloc(y*sizeof(mini_struct));
for (int j=0; j < y; j++) {
temp[i][j].a = 0;
... etc.
Question is incomplete so I will be making asumptions.
You seem to be wanting to allocate a 2D array of structs and initialize all members to 0. Here is a possible solution:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
typedef struct mini_struct{
unsigned long a;
unsigned long b;
unsigned long c;
} mini_struct;
struct mini_struct** build_2Dstruct(unsigned long x, unsigned long y){
double x_squared = pow(x, 2);
mini_struct **temp = (mini_struct **) malloc(x_squared * sizeof(mini_struct*));
for(int i = 0; i < x_squared; i++){
temp[i] = (mini_struct *) calloc(y, sizeof(mini_struct));
}
return temp;
}
int main () {
int x = 3;
int y = 4;
mini_struct **struct2D = build_2Dstruct(x, y);
int x_squared = pow(x,2);
for (int i = 0; i < x_squared; ++i) {
for (int j = 0; j < y; ++j) {
printf("Value of data stored at struct[%d][%d] is: %d\n", i, j, struct2D[i][j]);
}
}
for (int i = 0; i < x_squared; ++i) {
free(struct2D[i]);
}
free(struct2D);
}
As you can see, this contains the whole program, not just the snippet you showed. In this case, a main function would have been useful so that we don't have to guess what you want to do. My solution creates the 2D array with all elements initialized to 0 (you can use calloc to do that, no need for a second for loop).
Another important point is that, because the function returns a newly heap allocated 2D array, you need to free it to avoid a memory leak (end of main function).
You allocate x pointers to mini_struct:
mini_struct **temp = (mini_struct **) malloc(x_squared * sizeof(mini_struct*));
But then when you initialize them:
for(int i = 0; i < x_squared; i++){
temp[i] = (mini_struct *) calloc(y, sizeof(mini_struct));
}
You index temp based on upto x_squared.
Consider if x is 2. You would allocate temp to be an array of two pointers to mini_struct. But then your for loop would attempt to initialize four elements in temp.

Print descending array C

I have to create functions for print array, fill array witn descending numbers.
I created functions for printing array and creating descending array.But I faced with a problem.
If I use my own function printArray() it prints something unclear. Where is the problem, what i do wrong?
Please, help.
Here is the code in C. value - is value of array
Function for printing array:
void printArray (int arr[]){
int i;
printf("\n");
for(i = 0; i < value; i ++)
printf("%3d ", arr[i]);
}
Function for creating descending array:
int createDescendingArray(int a[])
{
int i;
printf("\nDescending array is created.\n");
for (i = value; i > 0; i--) {
a[i] = i;
}
printArray(a); // print of created array
}
Main function:
int main(){
int arr1[value]; //create new array
arr1[value] = createDescendingArray (arr1); //fill array with descending numbers
}
However when I don't use my print function in function createDescendingArray() and print it in Main funktion with standart method like this:
{int i;
for(i = 0; i < value; i++)
{
a[i]=i;
printf("%3d", a[i]);
}
}
It shows descending array as ascending (look at the picture)
How it works?
You have been using a variable named value in your function which prints array, without initializing it, hence the garbage value.
you should initialize it in the function or pass its start value as an argument to the function.
#include <stdio.h>
#include <stdlib.h>
void printArray(int *arr, int length)
{
int i;
printf("\n");
for (i = 0; i < length; i++)
{
printf("%3d ", arr[i]);
}
}
int *createDescendingArray(const int length)
{
if (length == 0)
return NULL;
int *a = malloc(length * sizeof(int));
;
printf("\nDescending array is created.\n");
for (int i = length-1; i >= 0; i--)
{
a[i] = i;
}
printArray(a, length); // print of created array
return a;
}
int main()
{
int *a = createDescendingArray(20);
printArray(a, 20);
return 0;
}
these changes should most probably do the trick but again, there is no initialization of value in the function that creates array as well
EDIT: stop creation of array if length is 0
EDIT2: fixed code to consider 0 as an element
EDIT3: Fixed code with suggestion from #CraigEstey in comments, tested and working
EDIT4: fixed for loop and removed cast on mallock
The function
int createDescendingArray(int a[])
{
int i;
printf("\nDescending array is created.\n");
for (i = value; i > 0; i--) {
a[i] = i;
}
printArray(a); // print of created array
}
is wrong.
According to the output in your question, it seems that you have defined value as 4 (you are not showing us the code with the definition). In that case, your code for the mentioned function is equivalent to the following:
int createDescendingArray(int a[])
{
printf("\nDescending array is created.\n");
a[4] = 4;
a[3] = 3;
a[2] = 2;
a[1] = 1;
printArray(a); // print of created array
}
I did nothing else to the code than unroll the loop.
Since the array a has a size of 4 elements, valid indices are from 0 to 3. Therefore, by writing to a[4], you are writing to the array out of bounds, causing undefined behavior.
If you had written
for (i = value - 1; i >= 0; i--)
instead of
for (i = value; i > 0; i--)
then the unrolled loop would be:
a[3] = 3;
a[2] = 2;
a[1] = 1;
a[0] = 0;
This is better, because now we have fixed the undefined behavior; you are no longer writing to the array out of bounds. However, this is still not what you want. If you want descending output, your unrolled loop must look like this instead:
a[0] = 3;
a[1] = 2;
a[2] = 1;
a[3] = 0;
This can be accomplished by changing your function to the following:
int createDescendingArray(int a[])
{
int i;
printf( "\nDescending array is created.\n" );
for ( i = 0; i < value; i++ ) {
a[i] = value - i - 1;
}
printArray(a); // print of created array
}
Here is a small test program:
#include <stdio.h>
//NOTE: It is customary for constants to be written upper-case,
//not lower-case, so the line below should normally not be used.
#define value 4
void printArray (int arr[]) {
int i;
printf( "\n" );
for( i = 0; i < value; i++ )
printf("%3d ", arr[i]);
}
int createDescendingArray(int a[])
{
int i;
printf( "\nDescending array is created.\n" );
for ( i = 0; i < value; i++ ) {
a[i] = value - i - 1;
}
printArray(a); // print of created array
}
int main( void )
{
int array[value];
createDescendingArray( array );
}
The output is:
Descending array is created.
3 2 1 0
In this test program, I took over most of your other code, but I did not take over the function main, because it was also causing undefined behavior:
int main(){
int arr1[value]; //create new array
arr1[value] = createDescendingArray (arr1); //fill array with descending numbers
}
In the line
arr1[value] = createDescendingArray (arr1);
you are assigning the return value of the function to a variable, although the function did not return a value. This causes undefined behavior. You may want to consider changing the return type to void in the function declaration, if it does not return a value.
Also, even if the function did return a value, arr1[value] would be writing to the array out of bounds, as valid indices are from 0 to value - 1.

2 Dimensional Array sorting in c

Here is a segment of my (incomplete) code
int rows(int board[][9]){
int badUnits = 0, i = 0, n = 9, j, z = 0;
int (*temp)[9];
//Sort each row of 2d array
for (z; z < n; z++){
for (i; i < n; i++){
for (j = i; j < n; j++){
if (board[z][i] > board[z][j]){
temp = board[z][i];
board[z][i] = board[z][j];
board[z][j] = temp;
}
}
}
}
printf ("%d\n", temp[1][0]);
printf ("%d\n", temp[1][1]);
return badUnits;
}
The function takes a 9*9 array.
I get a segmentation fault when the print statements are executed.
I believe my sort code is correct because it is similar to what I use for 1d arrays and I think everything else is correctly assigned.
So the culprit would be my temp variable. I have gone through and tried to assign values to it, tried to change the type, and have taken into account that the 2d array decays into a pointer but is not actually a pointer.
The conclusion I am left with is that this is a dynamic allocation issue. Can someone please lend a hand and assist me in fixing this? I have exhausted my knowledge base and am stuck.
To clarify: I decided to print the temp variable because I thought it would lend some information. The main problem was that the swap was not working, and I was still left with an unsorted array when I originally attempted to print out the board[][]. I know that board is what I am SUPPOSED to be printing.
Thank you for any help!
You assign an int value to temp
temp = board[z][i]; // Temp now is a what ever value was at
// That location in the array e.g. 42
You then treat temp as if it was the address in memory of an integer array
temp[1][1] // treat temp as a pointer and find the integer
// 10 integers further along then temp.
Also sometime temp will not have been initialised (never assigned to) in this case your going to get unexpected behaviour depending on what the last value stored where temp is now (Lets call it a random number).
Did you mean to output the values in board?
printf ("%d\n", board[1][0]);
printf ("%d\n", board[1][1]);
One thing to notice is that the variable temp will only get assigned to if a swap occurs, if the sorting algorithm was correct that is still a situation that could occur with a input corresponding to a sorted board.
But more importantly, the variable temp is used as an int during the swap. Later that integer value is interpreted as a pointer in the expressions temp[1][0] and temp[1][1], which in all likelihoods is not a valid address. You may want to change temp to be declared as:
int temp;
And figure out exactly what you would like to print. If it is whatever one of the two swapped values was (for the last swapped pair in the loop), then you would print it as:
printf("%d", temp);
Else, you would have to add logic according to what you really want to do.
Note that a single pass of this algorithm would not perform a complete sort, but I guess that's one of the reason why you said the provided code was not complete.
Something like this?
#include <stdio.h>
#include <stdlib.h>
void printArray(int** arr, int w, int h) {
for (int i = 0; i < w; ++i) {
for (int j = 0; j < h; ++j) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
void sortArray(int** arr, int w, int h) {
for (int row = 0; row < h; ++row) {
for (int col = 0; col < w; ++col) {
for (int i = 0; i < w; ++i) {
if (arr[row][i] > arr[row][col]) {
int tmp = arr[row][col];
arr[row][col] = arr[row][i];
arr[row][i] = tmp;
}
}
}
}
}
int main() {
int w = 9, h = 9;
int** arr = (int**)malloc(sizeof(int*) * w);
for (int i = 0; i < w; ++i) {
arr[i] = (int*)malloc(sizeof(int) * h);
for (int j = 0; j < h; ++j) {
arr[i][j] = rand() % 10;
}
}
printf("Unsorted:\n");
printArray(arr, w, h);
sortArray(arr, w, h);
printf("Sorted:\n");
printArray(arr, w, h);
for (int j = 0; j < h; ++j) {
free(arr[j]);
}
free(arr);
return 0;
}

int** vs int[const][const] differences

I was writing a code the other day and I found it rather strange, that int** and int[][] does not behave the same way. Can anyone point out the differences between them? Below is my sample code, which fails with a segmentation fault, if I pass constant size 2d array, while it does work fine when I pass a dinamically allocated 2d array.
I am confused mainly because ant int[] array works the same as int*.
#include<stdio.h>
#include<stdlib.h>
void sort_by_first_row(int **t, int n, int m)
{
int i, j;
for(i = m-1 ; i > 0 ; --i)
{
for(j = 0 ; j < i; ++j)
{
if(t[0][j] < t[0][j+1])
{
int k;
for(k = 0 ; k < n ;++k)
{
int swap;
swap = t[k][j];
t[k][j] = t[k][j+1];
t[k][j+1] = swap;
}
}
}
}
}
int main(void) {
int i, j;
/* Working version */
/*int **t;
t =(int**) malloc(3*sizeof(int*));
for(i = 0; i < 3; ++i)
{
t[i] = (int*) malloc(6*sizeof(int));
}*/
/*WRONG*/
int t[3][6];
t[0][0] = 121;
t[0][1] = 85;
t[0][2] = 54;
t[0][3] = 89;
t[0][4] = 879;
t[0][5] = 11;
for( i = 0; i < 6; ++i )
t[1][i] = i+1;
t[2][0] = 2;
t[2][1] = 4;
t[2][2] = 5;
t[2][3] = 3;
t[2][4] = 1;
t[2][5] = 6;
sort_by_first_row(t, 3, 6);
for(i = 0; i < 3; ++i)
{
for(j = 0; j < 6; ++j)
printf("%d ", t[i][j]);
printf("\n");
}
return 0;
}
So based on the below answers I realize, that a multidimensional array is stored continuously in a row major order. After some modification, the below code works:
#include<stdio.h>
#include<stdlib.h>
void sort_by_first_row(int *t, int n, int m)
{
int i, j;
for(i = m-1 ; i > 0 ; --i)
{
for(j = 0 ; j < i; ++j)
{
if(t[j] < t[j+1])
{
int k;
for(k = 0 ; k < n ;++k)
{
int swap;
swap = t[k*m + j];
t[k*m + j] = t[k*m + j+1];
t[k*m + j+1] = swap;
}
}
}
}
}
int main(void) {
int i, j;
/* Working version */
/*int **t;
t =(int**) malloc(3*sizeof(int*));
for(i = 0; i < 3; ++i)
{
t[i] = (int*) malloc(6*sizeof(int));
}*/
/*WRONG*/
int t[3][6];
t[0][0] = 121;
t[0][1] = 85;
t[0][2] = 54;
t[0][3] = 89;
t[0][4] = 879;
t[0][5] = 11;
for( i = 0; i < 6; ++i )
t[1][i] = i+1;
t[2][0] = 2;
t[2][1] = 4;
t[2][2] = 5;
t[2][3] = 3;
t[2][4] = 1;
t[2][5] = 6;
sort_by_first_row(t, 3, 6);
for(i = 0; i < 3; ++i)
{
for(j = 0; j < 6; ++j)
printf("%d ", t[i][j]);
printf("\n");
}
return 0;
}
My new question is this: How to modify the code, so that the procedure works with int[][] and int** also?
Realize that int **t makes t a pointer to a pointer, while int t[3][6] makes t an array of an array. In most cases, when an array is used in an expression, it will become the value of the address of its first member. So, for int t[3][6], when t is passed to a function, the function will actually be getting the value of &t[0], which has type pointer to an array (in this case, int (*)[6]).
The type of what is being pointed at is important for how the pointer behaves when indexed. When a pointer to an object is incremented by 5, it points to the 5th object following the current object. Thus, for int **t, t + 5 will point to the 5th pointer, while for int (*t)[M], t + 5 will point to the 5th array. That is, the result of t + 5 is the same as the result of &t[5].
In your case, you have implemented void sort_by_first_row(int **t, int n, int m), but you are passing it an incompatible pointer. That is, the type of &t[0] (which is what t will become in main) is not the same as what the function wants, a int **t. Thus, when the sorting function starts to use that address, it will think its indexing into pointers, when the underlying structure is an array of arrays.
int** is quite different from int[][]. int** is simply a pointer to a pointer and would appear like the following:
in reality, you can access the entire multidimensional array with simply int* pointing to the first element, and doing simple math from that.
Here is the result of the separate allocations (in your commented code):
However when you allocate a multidimensional array, all of the memory is contiguous, and therefore easy to do simple math to reach the desired element.
int t[3][6];
int *t = (int*) malloc((3 * 6) * sizeof(int)); // <-- similarly
This will result in a contiguous chunk of memory for all elements.
You certainly can use the separate allocations, however you will need to walk the memory differently.
Hope this helps.
int t[3][6] is very nearly the same thing as int t[18]. A single contiguous block of 18 integers is allocated in both cases. The variable t provides the address of the start of this block of integers, just like the one-dimensional case.
Contrast this with the case you have marked as "working", where t gives you the address of a block of 3 pointers, each of which points to a block of memory with 6 integers. It's a totally different animal.
The difference between t[3][6] and t[18] is that the compiler remembers the size of each dimension of the array, and automatically converts 2D indices into 1D offsets. For example, the compiler automatically converts t[1][2] into *(t + 1*6 + 2) (equivalent to t[8] if it were declared as a one-dimensional array).
When you pass a multi-dimensional array to a function, there are two ways to handle it. The first is to declare the function argument as an array with known dimension sizes. The second is to treat your array like a 1D array.
If you are going to declare the size of your array, you would declare your function like this:
void sort_by_first_row(int t[][6], int n)
or this
void sort_by_first_row(int t[3][6])
You either have to declare all array dimension sizes, or you can leave out the first size. In both cases, you access elements of t using t[i][j]; you've given the compiler enough information to do the offset math that converts from 2D notation to a 1D index offset.
If you treat it as a 1D array, you have to pass the array dimensions and then do the offset math yourself.
Here's a full working example, where f and f2 both generate the same output:
void f(int* t, int m, int n)
{
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
std::cout << t[i * n + j] << " ";
std::cout << std::endl;
}
void f2(int t[][6], int m)
{
for (int i = 0; i < m; i++)
for (int j = 0; j < 6; j++)
std::cout << t[i][j] << " ";
std::cout << std::endl;
}
int main()
{
int t[3][6];
int val = 1;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 6; j++)
{
t[i][j] = val;
val++;
}
}
f(&(t[0][0]), 3, 6);
f2(t, 3);
return 0;
}
One thing to note is the hack-ish way I had to pass t to f. It's been a while since I wrote in C/C++, but I remember being able to pass t directly. Maybe somebody can fill me in on why my current compiler won't let me.
A int ** is a pointer to a pointer to an int, and can be a pointer to an array of pointers to arrays of ints. A int [][] is a 2-dimensional array of ints. A two-dimensional array is exactly the same as a one-dimensional array in C in one respect: It is fundamentally a pointer to the first object. The only difference is the accessing, a two-dimensional array is accessed with two different strides simultaneously.
Long story short, a int[][] is closer to an int* than an int**.

Replace null elements from array with some value in MIPS

I need something similar with this converted in MIPS. Eventualy using a procedure which gets as parameters the array, the lenght of the array, and the value that should replace the null elements of the array. I also have to print "finish" when done, which I also don't know. Thank you in advance.
#include <stdio.h>
int array[40];
int main() {
int i, n = 40; x = 6;
for (i=0, i<n; i++)
if (array[i] == 0)
array[i] = x;
return 0;
}

Resources