-
Problem with pointers
I must write a program that reads in a file of ints into an array and lets the user choose the array index he wants to see. I can read in the file but when assigning it to an array value I obviously screwed up somewhere because it doesn't work, so here is my code for the main function and the function I am having problems in.
Code:
#include "my.h"
int main(int argc, char* argv[]){
FILE *fpIn;
int *arr;
int lim=0;
int j=0;
if(openFiles(&fpIn,argv)){
lim=getInput (&fpIn, &arr);
oddEvenSort(arr,lim);
do{
printf("\nPlease enter a number between 1 and %d or -1 to exit\n",lim);
scanf("%d",&j);
if(j>0&&j<=lim)
printf("\n%d", arr[j]);
else if(j==-1)
printf("\ngoodbye\n");
else
printf("\nWhoops, that number won't work\n");
}while(j!=-1); }
else
printf("\nOh Snap, I couldn't open the file.\n");
fclose(fpIn);
}
Code:
#include "my.h"
int getInput (FILE** fpIn, int** a)
{
int i,j;
fscanf(*fpIn, "%d",&i);
*a= (int*) calloc(i,sizeof(int));
for(j=0;j<i;j++){
fscanf(*fpIn, "%d",&*a[j]);
}
return i;
}
any help will be greatly appreciated.
-
Perhaps you should start by fixing your indentation...
-
Re-indented (one-time)
Code:
#include "my.h"
int main(int argc, char* argv[]){
FILE *fpIn;
int *arr;
int lim=0;
int j=0;
if(openFiles(&fpIn,argv)){
lim=getInput (&fpIn, &arr);
oddEvenSort(arr,lim);
do{
printf("\nPlease enter a number between 1 and %d or -1 to exit\n",lim);
scanf("%d",&j);
if(j>0&&j<=lim)
printf("\n%d", arr[j]);
else if(j==-1)
printf("\ngoodbye\n");
else
printf("\nWhoops, that number won't work\n");
}while(j!=-1);
}
else
printf("\nOh Snap, I couldn't open the file.\n");
fclose(fpIn);
}
#include "my.h"
int getInput (FILE** fpIn, int** a)
{
int i,j;
fscanf(*fpIn, "%d",&i);
*a= (int*) calloc(i,sizeof(int));
for(j=0;j<i;j++){
fscanf(*fpIn, "%d",&(*a)[j]);
}
return i;
}
You might want to read our FAQ on casting malloc.
Also, don't treat { } as optional.
The cost of adding them (zero if you have a smart IDE) is minimal compared to the time it takes to find some bugs caused by their absence.