改变全局变量的值,C

标签 c global-variables

因此,我试图找到一种更新变量的方法,并且我尝试将其设为全局变量,以便我可以轻松更改它。唯一的问题是它不工作,我不知道如何修复它。

我希望 SIZE_ARRAY 更改为每次调用 remove_unimportant_words 函数时的值。

声明:

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);
      }

功能:

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);
}

我基本上尝试打印 SIZE_ARRAY 的值,并且在进入函数时它总是从 480 开始。

最佳答案

当您将 SIZE_ARRAY 作为函数 remove_unimportant_words 中的参数传递时,它不再在该函数中用作全局变量。所以全局 SIZE_ARRAY 保持不变。

您不应将 SIZE_ARRAY 作为参数传递。希望您的代码能按预期工作。

void remove_unimportant_words(char word[MAX],  char list[SIZE_ARRAY][MAX] , int j, int i)
{

...

关于改变全局变量的值,C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27734601/

相关文章:

c - 在不使用任何工具等的情况下查找某些 API 函数调用的堆栈使用情况?

c - 将数组保存到文件不起作用,程序崩溃

c - fork 到新的 cygwin 终端

c - 试图反转整数中数字的顺序,显示额外的数字

C : Parsing options the right way

python - 如何使用 tkinter 创建下一个按钮以在多个框架之间切换

dependency-injection - 全局状态和单例依赖注入(inject)

c - 如何隐藏在多个文件中可见的全局变量?

compiler-construction - 单一静态赋值形式的全局变量

Javascript:使用全局变量是否合适?