I think I must be losing my mind because I thought that passing a pointer to a function would be passing its address, but I can't get the function to alter the elements of the parent's array. For example, I wrote code to make sure all input was in the correct case for interpretation. I didn't want to create a class, and don't want to deal with the memory issues of returning arrays.
Is there a way to make this work as I wish? It isn't a compiler issue, is it? Could this be something different about c++ as opposed to c?
#include <stdio.h>
#define TERM_LENGTH 32 /* defines the maximum length of acceptable terms */
#define NEWITEM "new\0"
void toLowerCase(char*);
int areEqual(char*,char*);
int main(){
int i;
char input[TERM_LENGTH];
FILE * source;
printf("What file to check?\n");
scanf("%s",source); /* I'm assuming no spaces, but I know some OS's allow them */
i = 0;
while(fscanf("%s",input) != EOF){
toLowerCase(input);
if(areEqual(input,NEWITEM)) printf("You now have %d items!\n",++i);
}
return 0;
}
/* I figure it's probably bad etiquette and practice to have predefined term sizes,
* but it lets me worry about other things, instead of where the input ends */
void toLowerCase(char * term){
int i;
for(i = 0; i < TERM_LENGTH; i++){
if(term[i] >= 'A' && term[i] <= 'Z')
term[i] -= (int)('A' - 'a');
}
}
/* I have it written differently out of caution, but I also wonder if the *
* following will cause any memory problems because of leaving a function *
* from the middle of a loop. */
int areEqual(char * term0, char * term1){
/* I have it go until '\0' because, after the input ends, the array is *
* undefined. */
while(str0[i] != '\0' && str1[i] != '\0'){
if(str0[i] != str1[i]) return 0;
}
return 1;
}
In this code, the problem is when the terms read from the file aren't lowercase in main's code block, even after the function has been called. I don't know why this would happen because C is pass-by-value (right?) and I figured that would mean the array's address would be passed in this case. *sigh*
rather than using the array syntax. Strictly speaking it isn't an array in toLowerCase() and although the compiler will let you do array syntax, it is effectively dereferencing an element of the array and I suspect thats the problem, it's probably making a local copy each time you do it. I'd have to run it in a debugger and look at the addresses to make sure. Another possibility would be to pass a pointer to input to toLowerCase() changing the parameter to a char **. Either should work.