Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
This is for homework
Here is my program
#include <stdio.h>
void swap (int *a , int *b , int *c , int *d , int *e ) {
int temp1 = a;
a = b;
b = temp1;
int temp2 = b;
c = d;
d = temp2;
int temp3 = e
e = a;
a = temp3;
}
void swap (int *a , int *b , int *c , int *d , int *e );
int main(void)
{
int arr[15] = {0};
int i;
int a = arr[0], b = arr[7], c = arr[8], d = arr[3], e = arr[14];
printf("Enter 15 integers\n");
for(i = 0; i < 15; ++i) {
scanf("%d" , &arr[i]);
//printf("The ints are %d " , arr[i]); checked if all the ints were recorded
}
swap(a, b, c, d, e);
printf("Swapped array:\n %d" , arr[i]);
return 0;
}
So The program is asking me to have the user enter 15 integers. The function would have to swap the 1st integer entered (arr[0]) with the seventh integer entered (arr[7]). Then swap the 8th with the 3rd, then swap the last one with the first. My program complies but gives a handful of warnings and when I try to print my swapped array, all I get is a value of 0. Any help would be appreciated!
Edit
Sorry I heard from someone to not worry about the warnings- counter-intuitive to listen. The warnings are:
[In the function]
assignment makes pointer from integer without a cast
initialization makes integer from pointer without a cast
In main
passing argument [numbers] of swap makes pointer from integer without a cast
There's several problems with your code.
First, the swap function doesn't work. You're swapping the values of the pointers that are local variables inside the function, you're not swapping the array elements they point to. You need to indirect through pointers to get the values.
int temp1 = *a;
*a = *b;
*b = temp1;
And similar for all the other pairs you're swapping.
Second, swap expects pointers as arguments, but you're passing int variables from main(). You need to use pointer variables, which you set to the addresses of the array elements:
int *a = &arr[0], *b = &arr[7], *c = &arr[8], *d = &arr[3], *e = &arr[14];
You might consider changing the swap() function so it just takes two pointers, and call it 3 times to do all 3 swaps.
Finally, to print the array, you need to print the elements in a loop:
printf("Swapped array: ");
for (i = 0; i < 15; i++) {
printf("%d ", arr[i]);
}
printf("\n");
Related
So I'm doing pointer arithmetic homework and I need to decrement and increment pointers with this as its expected outcome. This is what I did
#include <stdio.h>
void main(void){
int d = 10;
int c = 8;
int b = 6;
int a = 4;
int *ptr; //these lines are given
printf("decrement \n");
for (ptr = &d; ptr >= &a; ptr--)
{
printf("%d \n",*ptr);
}
printf("increment \n");
for (ptr = &a; ptr <= &d; ptr++)
{
printf("%d \n",*ptr);
}
}
But the results skip 8 and 6:
decrement
10
4
increment
4
10
And so I decided to print the addresses at the beginning to help debug
printf("%p\n",(void*)&d);
printf("%p\n",(void*)&c);
printf("%p\n",(void*)&a);
printf("%p\n",(void*)&b);
But after running it, it just works
000000fc6a9ffb34
000000fc6a9ffb30
000000fc6a9ffb28
000000fc6a9ffb2c
decrement
10
8
6
4
increment
4
6
8
10
So I know that the logic works out, but it just doesn't work without printing first and I don't know why
I'm using Vscode and GCC
So I know that the logic works out, but it just doesn't work without printing first
Undefined behavior (UB), anything may happen.
int d = 10;
int a = 4;
int *ptr = &d;
ptr >= &a
ptr >= &a is undefined behavior (UB).
Order comparisons of pointers in C are UB when not part of the same array (or one after).
ptr-- is also UB as that attmepts to form the address before d. Pointer math only good within an array/object (or one after)
In your first example, you are not using variables b and c, just a and d - therefore (I suspect) the implementation is optimizing them away
In the second example, you are using variables all four variables a, b, c and d therefore they cannot be optimised away
your program have four different variables not an array of size four. So address of variables is unpredictable.
int d = 10;
int c = 8;
int b = 6;
int a = 4;
in Array memory is allocated contiguously, so use array if you want to do so.
#include<stdio.h>
int main(){
int arr[4] = {1, 2, 3, 4};
// increment
for(int i=0; i<4; i++)
printf("%d\n",*(arr + i));
// decrement
printf("-------------------------------\n");
for(int i=3; i>=0; i--)
printf("%d\n",*(arr + i));
return 0;
}
This question already has answers here:
Triple pointers in C: is it a matter of style?
(5 answers)
Closed 4 years ago.
While I have seen some threads on this, I fail to understand the meaning behind triple pointers, since it seems that it's possible to do the same without them.
void Reading(int *N, int ***M) {
printf("Input an integer N: \n");
scanf("%d", N);
*M = malloc(N * sizeof(int*));
int i;
for (i = 0; i < N; i++)
*(*M+i) = malloc(N * sizeof(int));
printf("Input N*N integers that will form a matrix \n");
int i, j;
for (i = 0; i < *N; i++)
for (j = 0; j < *N; j++)
scanf("%d", &((*M)[i][j]));
}
This code makes **M a 2D array. If I take the malloc procedures and put them into main, the triple pointer isn't needed anymore. Could someone please explain why this is the case ?
If I take the malloc procedures and put them into main, the triple pointer isn't needed anymore.
There are two ways to pass a variable to a function: either by value or by reference. When you pass the reference of a variable, that allows you to modify it.
Example:
void fun(int a) {
a = 42; // Does nothing
}
int b = 9;
fun(b);
// b is unchanged.
void fun(int *a) {
*a = 42;
}
int b = 9;
fun(&b);
// b equals 42.
Your variable happens to be a of type int **, when you pass the address (reference) of this variable, this makes it a int ***.
I would like to swap two variables containing 2D arrays. I believe this can be simply done by swapping their pointers. I tried this code, but it does not work and I have no idea why, perhaps I am not understanding pointers correctly.
#include <stdio.h>
void swap(int ***a, int ***b) {
int ** temp = *a;
*a = *b;
*b = temp;
}
int main(void) {
int a[10][10];
int b[10][10];
a[1][5] = 4;
b[1][5] = 2;
printf("%d, %d\n", a[1][5], b[1][5]);
swap(&b, &a);
printf("%d, %d\n", a[1][5], b[1][5]);
return 0;
}
This outputs
4, 2
4, 2
I would expect it to output
4, 2
2, 4
So, what am I doing wrong?
a and b in main function are not pointers but arrays.
If you want to use pointers, use pointers.
#include <stdio.h>
#define N 10
void swap(int (**a)[N][N], int (**b)[N][N]) {
int (*temp)[N][N] = *a;
*a = *b;
*b = temp;
}
int main(void) {
int a[N][N];
int b[N][N];
int (*pa)[N][N] = &a;
int (*pb)[N][N] = &b;
(*pa)[1][5] = 4;
(*pb)[1][5] = 2;
printf("%d, %d\n", (*pa)[1][5], (*pb)[1][5]);
swap(&pb, &pa);
printf("%d, %d\n", (*pa)[1][5], (*pb)[1][5]);
return 0;
}
This would not work because what you are swapping is actually what the variables in the swap() function are pointing to, and not what they are pointing at. Its like if a was pointing at 5 and b was pointing at 6 in the swap() function, then it will make a point at 6 and b point at 5, without changing the contents of the memory. This would mean the in the main() function they would be residing at the same place and would be getting pointed by the same variable a and b (different from the variable in swap())
To swap you need to swap the contents of that memory in the swap() function, so that it is reflected in the main() function.
Recall that while doing swapping using pointers, one sends the address and actually swaps the content by dereferencing (*p and *q).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So I have the following code so far:
#include <stdio.h>
int foo (int *pointer, int row, int col);
int main() {
int array[3][3] ={ {1,2,3},{4,5,6},{7,8,9}};
int *pointer= array[0];
int row = 2;
int col = 2;
int answer = foo (pointer, row, col);
printf("%d", answer); //prints 5 (which is wrong)
printf("%d", array[2][2]); //prints 9
}
int foo (int *pointer, int row, int col){ //I don't want to use any square brackets here, unless I really have to.
int value;
value = *((int *)(pointer+row)+col);
return value;
}
So my main issue is with passing a 2D pointer, please explain in detail as I am still new at coding. I don't want to really change what I am passing (as in I want to use the pointer in foo(pointer, row, col) and not foo (array, row, col).
passing a 2D pointer
From how you (ab)used the terminology, it's quite clear that you're under the wrong impression that pointers and arrays are the same. They aren't.
If you want to access a multidimensional array using pointers, you must specify all its dimensions (except the first, innermost one) and use pointer arithmetic correctly, possibly using pointers-to-array, since multidimensional arrays are contiguous in memory:
const size_t h = 2;
const size_t w = 3;
int arr[h][w] = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
int *p = &arr[1][2];
int *q = arr[1];
int (*t)[3] = &arr[1];
printf("arr[1][2] == %d == %d == %d\n", *p, q[2], (*t)[2]);
return 0;
int *pointer= array[0];
Instead of use this
int *pointer= &array[0];
Or
int *pointer= array;
I have a certain struct structXand a 2D array which holds these kind of structs.
I want to be able to save a pointer to that 2D struct and iterate over it
in a dynamic way, meaning, the pointer can hold any structX and iterate.
Example in general lines:
struct structX *ptr = NULL;
...
if(i == OK)
{
ptr = General_struct_which_holds_others->ptr1;
}
else if(i ==NOT_OK)
{
ptr = General_struct_which_holds_others->ptr2;
}
Now the iteration:
if(ptr[x][y] == OK) <----Error, subscripted value is neither array nor pointer
{
...
}
I hope i'm understood, As i was saying this is very general.
How can the iteration be made? meaning not getting errors?
Thanks!
Two problem I can noticce in your code if(ptr[x][y] == OK)
(1):
ptr is pointer to structure (single *) you can't use double indices [][] so error at if(ptr[x][y] == OK)
error, subscripted value is neither array nor pointer because of ptr[][]
(2):
error: used struct type value where scalar is required means if(struct are not allow).
if(should be a scalar value )
scalar value means can be convert into 0/1.
Pointer to 2D struct array C
struct structX matrix2D[ROW][COL];
its pointer
struct structX (*ptr2D)[ROW][COL];
ptr2D = &matrix2D;
ok, access you array structure like this:
struct structX i;
(*ptr2D)[r][c] = i;
If you want to pass in an function do like:
void to(struct structX* ptr2D[][COL]){
struct structX i;
ptr2D[][COL] = i;
}
void from(){
struct structX matrix2D[ROW][COL];
to(matrix2D);
}
Just to make you sure I written a simple code shows how to work with ptr2D. Hope you find it helpful:
#include<stdio.h>
#define ROW 10
#define COL 5
typedef struct {
int a;
char b;
} structX;
void to(structX ptr2D[][COL], int r, int c){
printf("in to: %d %c\n", ptr2D[r][c].a, ptr2D[r][c].b);
}
int main(){
structX matrix[ROW][COL];
structX (*ptr2D)[ROW][COL];
ptr2D = &matrix;
structX i;
i.a = 5;
i.b = 'a';
int r = 3;
int c = 2;
(*ptr2D)[r][c] = i;
printf("%d %c\n", (*ptr2D)[r][c].a, (*ptr2D)[r][c].b);
to(matrix, r, c);
}
And its working, Output:
5 a
in to: 5 a
EDIT
I wanted to show two tricks but now I think I should provide a uniform method(as you commented):
So here is the code:
#include<stdio.h>
#define ROW 10
#define COL 5
typedef struct {
int a;
char b;
} structX;
void to(structX (*ptr2D)[ROW][COL], int r, int c){
printf("in to: %d %c\n", (*ptr2D)[r][c].a, (*ptr2D)[r][c].b);
}
int main(){
structX matrix[ROW][COL];
structX (*ptr2D)[ROW][COL];
ptr2D = &matrix;
structX i;
i.a = 5;
i.b = 'a';
int r = 3;
int c = 2;
(*ptr2D)[r][c] = i;
printf("%d %c\n", (*ptr2D)[r][c].a, (*ptr2D)[r][c].b);
to(&matrix, r, c);
}
Output
5 a
in to: 5 a
EDIT:
error: used struct type value where scalar is required means if(struct are not allow).
if(should be a scalar value )
you can't do like if((*ptr2D)[r][c]);
but this is allow:
if((*ptr2D)[r][c].a == 5);
or
if((*ptr2D)[r][c].b == 'a');
or
if((*ptr2D)[r][c].a == 5 && (*ptr2D)[r][c].b == 'a');
or
structX i;
if((*ptr2D)[r][c] == i);
You might want to ready this article about multidimensional arrays. If you want to iterate over an array, you need to know how big it is (whether it is dynamic or not). If you want it to be dynamic, that means you need to allocate memory for it when it needs to grow and you need to free the old memory. You also have a problem in your question - you declare a single pointer which is null and then try to dereference it but you never allocated memory for it.
If you did allocate memory for it, you could dereference it by saying
ptr[x * ROW_WIDTH + y]
if you set ROW_WIDTH to the maximum value of y. Depending on whether you want to represent a rows major or column major array, you might use y * width instead of x * width.