c - 在函数中静态标识的数组

标签 c arrays function pointers static

我在理解这个程序的特定情况下的静态标识符时遇到了问题。这个节目的上下文是关于“指针”的讲座。

这个程序的工作是为临时文件创建一个新名称,它通过每次函数 tmp_name 被调用。

  1. 第一次调用 –> "tmp0"
  2. 第二次调用 –> "tmp1"
  3. ...

[代码]

#include <stdio.h>
#include <string.h>

/*******************************************************
 * tmp_name -- Return a temporary filename             *
 *                                                     *
 * Each time this function is called, a new name will  *
 * be returned.                                        *
 *                                                     *
 * Returns                                             *
 *      Pointer to the new filename                    *
 *******************************************************/
char *tmp_name(void){

    static char name[30]; /* The name we are generating */
    static int sequence = 0; /* Sequence number for last digit */

    ++sequence; /* Move to the next filename */

    strcpy(name, "tmp");

    name[3] = sequence + '0';

    /* End the string */
    name[4] = '\0';

    return(name);
}

int main(){

    char *tmp_name(void); /* Get the name of temporary file, very first call */
    char *name1; /* Name of a temporary file, second call */
    char *name2; /* Name of another temporary file, third call */

    name1 = tmp_name();
    name2 = tmp_name();

    printf("Name1: %s\nName2: %s\n", name1, name2);
    return(0);
}

所以程序的输出(因为调用了printf函数)是打印“tmp1”和“tmp2”(“tmp0”打印不出来,完全没问题)。

那么这个程序是完美运行的,那么问题是什么?问题是,如果我从 static char name[30] 中删除 static,程序就会中断。它打印出来:

Name1: \340\364\277\357\376
Name2: \340\364\277\357\376

我研究了 static 的含义及其含义,因此 static int sequence 的使用对我来说非常清楚,但我真的不明白为什么还要声明数组 [name]静态的。

最佳答案

char *stuff() {
    char thing[100];
    strcpy(thing, "what are you returning??");

    return thing;
}

现在,你在这里返回什么?一个指针。去什么?请记住,非静态局部变量在函数返回后被销毁。因此,在 char *data = stuff(); 中,变量 data 将充满垃圾,因为 thing 已被处理掉。

然而,静态变量仍然存在并且完全有效即使函数退出,所以您返回的指针仍然指向您的程序拥有的内存这肯定包含你放在那里的数据,而在非静态变量的情况下,一旦函数退出你就失去了对这个内存的控制,因此任何程序都可以把任何东西放在那里,这就是你如何获得这些垃圾数据。

关于c - 在函数中静态标识的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49071410/

相关文章:

c++ - 用 C++ 编写 GUI 应用程序时使用的最佳库是什么?

c++ - 如何通过迭代将数字范围插入数组?

c# - 如何比较两个数组列表?

c - 如何在 C 中不使用指针的情况下通过函数传递 2D 数组

mysql - 递归函数,保存DynamicPreparedStatement

c - "Expected expression before ' { ' token"

C中的cc编译器问题

c - 在二维中,如何判断三角形和 AABB 是否相交

c - 如何访问二维数组的外边界元素?

c - 这个奇怪的函数定义是什么意思?