Reputation: 39
So I'm trying to find a way to update a variable and I've tried to make it global so I can change it easily. The only problem is it isn't working and i don't know how to fix it.
I want SIZE_ARRAY to change to the value it becomes every time I call the remove_unimportant_words function.
Decleration:
int SIZE_ARRAY = 480;
char list[SIZE_ARRAY][MAX];
void remove_unimportant_words(char word[MAX], int SIZE_ARRAY, char list[SIZE_ARRAY][MAX] , int j, int i);
int main():
while (fscanf(file, "%s", word) != EOF){
remove_unimportant_words(word, SIZE_ARRAY, list, j, i);
}
Function:
void remove_unimportant_words(char word[MAX], int SIZE_ARRAY, char list[SIZE_ARRAY][MAX] , int j, int i)
{
for (i=0; i<SIZE_ARRAY; i++) {
if(strcmp(list[i],word) == 0){
for (j=i; j<SIZE_ARRAY; j++) {
strcpy(list[j], list[j+1]);
}
SIZE_ARRAY--;
i--;
}
}
printf("%d\n", SIZE_ARRAY);
}
I've basically tried printing the value of SIZE_ARRAY and it always starts at 480 when going in the function.
Upvotes: 0
Views: 6194
Reputation: 7159
Just do not use SIZE_ARRAY
as a parameter, function remove_unimportant_words
can access it just as usual
Upvotes: 0
Reputation: 8415
If SIZE_ARRAY
is a global variable as you stated, you need not pass another integer parameter to the function remove_unimportant_words()
.
The SIZE_ARRAY
you passed into remove_unimportant_words() effectively shadows the global variable with a local copy of a unrelated, newly allocated variable also under the name SIZE_ARRAY
which will be deallocated as the function returns.
In essence:
void remove_unimportant_words(char word[MAX], int SIZE_ARRAY, char list[SIZE_ARRAY][MAX] , int j, int i);
the int SIZE_ARRAY
parameter there shows no relation to the actual global SIZE_ARRAY variable and should be removed as so that code within the function body references the global SIZE_ARRAY
variable directly.
You could potentially also use addresses and pointers to pass the variable by reference if you mean to merely pass SIZE_ARRAY
from one function to another.
As a side note, are you sure the code you provided compiles? I see a lot of syntax that doesn't seem valid...
Upvotes: 1
Reputation: 13814
As you are passing SIZE_ARRAY as parameter in your function remove_unimportant_words
, This is not using as global in that function any more.. So Global SIZE_ARRAY remains same.
You should not pass SIZE_ARRAY as parameter. Hope your code will work as expected.
void remove_unimportant_words(char word[MAX], char list[SIZE_ARRAY][MAX] , int j, int i)
{
...
Upvotes: 1