So I have this code:
#include <stdio.h>
int arraySum (int *a, int n);
int main(void){
int values[3] = {1, 2, 3};
printf("The sum is %i\n", arraySum(values, 3));
return 0;
}
int arraySum(int *a, int n){
int sum = 0;
int arrayEnd = *a + n;
for ( ; *a < arrayEnd; *a++)
sum += *a;
return sum;
}
For some reason it outputs this:
roman@lmde64 ~/Dropbox/Practice $ gcc practice.c
roman@lmde64 ~/Dropbox/Practice $ ./a.out
The sum is -421028781
roman@lmde64 ~/Dropbox/Practice $ ./a.out
The sum is -362865581
roman@lmde64 ~/Dropbox/Practice $ ./a.out
The sum is -1046881197
roman@lmde64 ~/Dropbox/Practice $ ./a.out
The sum is 6
roman@lmde64 ~/Dropbox/Practice $ ./a.out
The sum is 6
Why is the output strange numbers sometimes and the right answer other times? What am I doing wrong? Thanks for any help.
2.2 Pointers Can Be Dangerous Because pointers provide access a memory location and because data and executable code exist in memory together, misuses of pointers can lead to both bizarre effects and very subtle errors. dangling pointers.
If a pointer points to memory that has been freed, or if it is accidentally assigned a nonzero integer or floating point value, it becomes a dangerous way of corrupting memory, because data written through it can end up anywhere.
For example, C does not prevent the programmer from writing outside an array's bounds. This can result in corrupted memory and introduce potential security risks. In addition, the improper use of pointers is often at the root of many security problems.
Pointers are arguably the most difficult feature of C to understand. But, they are one of the features which make C an excellent language. In this article, we will go from the very basics of pointers to their usage with arrays, functions, and structure.
In arraySum()
, you are confusing when to use a
as a pointer, and when to dereference it to obtain what it is pointing to. When you are calculating the loop limits, etc., you want to be working with the pointer itself:
int arraySum(int *a, int n){
int sum = 0;
int *arrayEnd = a + n;
for ( ; a < arrayEnd; a++)
sum += *a;
return sum;
}
You want to iterate over the array:
int arraySum(int *a, int n){
int sum = 0;
int * arrayEnd = a + n; // arrayEnd points to the first element after your array a
for ( ; a != arrayEnd; ++a) // Iterate over the array until you reach arrayEnd
sum += *a; // Dereference the pointer to current array element in order to retrieve a value
return sum;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With