Reputation: 808
I made a simple function in C which takes as arguments 1 pointer to int, 1 double pointer to int and an integer (the third argument is possibly useless since it represents the number of integers that are stored in the space which the first argument points to). What it does is: First, makes enough space in memory to hold 2 integers and sets the second argument to point to that space. Second, copies the integers from the space to which the first argument points to the space which the second argument points to. Third, it increments all integers in the space that the first argument points to by 1. I know that this function is useless, but I wanna know what's going wrong with my solution. Here is the code:
#include <stdlib.h>
#include <stdio.h>
int *x, *y;
void duplicateAndIncreaseByOne(int *arg1, int **arg2, int arg1Elements){
int ctr;
*arg2 = (int *) malloc(arg1Elements * sizeof(int));
for(ctr = 0; ctr < arg1Elements; ctr++){
**(arg2 + ctr) = *(arg1 + ctr);
*(arg1 + ctr) = *(arg1 + ctr) + 1;
}
}
int main() {
int j;
y=(int *)malloc(2*sizeof(int));
*y=10; *(y+1)=50;
duplicateAndIncreaseByOne(y, &x, 2);
printf("The pointer y contains the elements y[0] = %d and y[1] = %d\n", y[0], y[1]);
printf("The pointer x contains the elements x[0] = %d and x[1] = %d\n", x[0], x[1]);
}
Upvotes: 0
Views: 84
Reputation: 183888
In the line
**(arg2 + ctr) = *(arg1 + ctr);
you are adding the offset to arg2
instead of *arg2
. That should be
*(*arg2 + ctr) = *(arg1 + ctr);
At the moment, you are dereferencing a nonexistent int**
past arg2
.
Upvotes: 2