-
confused with pointers
ok so I'm writing a program that will read a data file with 30 integers in it into an array, then pass the array to a function that counts the number of positive numbers, zero's, and negative numbers, then back in main print out those numbers. Its supposed to be done using pointers but Im confused as to what I am doing. heres my code so far
Code:
#include <stdio.h>
#define maxNum 30
#define FILENAME "assign10in.txt"
int readfile( int x[]);
void signs( int x[], int nNum, int *nPos, int *nZero, int *nNeg);
int main()
{
int nNum;
int x[maxNum];
int *nPos, *nZero, *nNeg;
nNum = readfile(x);
signs(x, nNum, nPos, nZero, nNeg);
printf("\n %d", nPos);
return 0;
}
int readfile( int x[])
{
int nNum=0;
FILE *assign10in;
assign10in = fopen(FILENAME, "r");
if (assign10in == NULL)
printf("Error Opening Input File. \n");
else
{
while (nNum<maxNum)
{
fscanf(assign10in, "%d", &x[nNum]);
printf("%d ", x[nNum]);
nNum++;
}
}
fclose(assign10in);
return nNum;
}
void signs( int x[], int nNum, int *nPos, int *nZero, int *nNeg)
{
int i;
for (i=0; i<nNum; i++)
{
if (x[i]>0)
{
now what Im trying to write next is for if x[i]>0 then nPos will be increased by one, but with pointers im unsure of which way to do this
&nPos++; ??
I tried it several ways but when I throw in a print function to check it either prints 0 or a number such as 2289452 (I'm assuming thats the actual address?)
anyone care to straighten me out?
-
Declaration of a pointer:
Assignment of a pointer to a regular variable:
Code:
int k;
....
p = &k;
Assigning a value to whatever a pointer points to:
This means k is equal to 5. Whenever you do *p, it is resolved to be the variable that p points to.
-
If you increment a pointer, you will increment the address it points to by the size of the object type in bytes. If you imagine memory as a long line of cubby holes, what's happening should be easier to visualize: you're moving to the next cubby hole. Obviously not what needs to be done.
You seem to be confused about the difference between dereferecing and the address-of operator. The address of operator only fetches the address of an object: it can be useful if you want to store a different memory address in a pointer. It follows though, that the address-of operator is not intuitively on the left hand side of an assignment. The dereferencing operator fetches the value of the object at the address stored in the pointer. Because this is what we want to change, the dereference operator becomes important.
We could do something like
*nPos = *nPos + 1;