Reputation: 17
i've tried searching for the answer/ looking at the C library for pointers, but wasn't sure on the right solution. My question concerns changing the parameters of a function. I've been reading on pointers/functions, and from my understanding, if a function takes in (int x1), then when the function is done with x1, x1 outside the function remains untouched. However, if you pass in a int *x1, then it is changed.
I've been experimenting with it, and i've tried using this with a sort method...
void sorting(int *arr, int size) {
int *i, *j, temp;
int *len = arr + size - 1;
for(i = arr; i < len; i++) {
for(j = i + 1; j <= len; j++) {
if(*j < *i) {
temp = *i;
*i = *j;
*j = temp;
}
}
}
int k;
for(k = 0; k < size; k++) {
printf("k: %d, arr[k]: %d \n", k, *(arr + k));
}
}
What this would print is a fully sorted list. However, in my main function, if I called this...
int main() {
int temp[5] = {0, 2, 1, 3, 1};
int *p = &temp[5];
sorting(pa, 5);
print the values of pa...
}
Then the list remains unsorted if printing out the values of pa.
If this question has already been solved, could someone please link the question, and i'll delete the post.
Upvotes: 1
Views: 62
Reputation: 227410
You're accessing the array out of bounds here:
int *p = &temp[5];
The valid indices are [0, 5)
. Presumably you want a pointer to the first element:
int *p = &temp[0];
But note that you can pass an array to a function that expects a pointer. In this case the array decays to a pointer to the first element:
sorting(temp, 5);
Upvotes: 2