• [C]关于函数指针参数的赋值


    问题

    在有一次尝试用stat()函数获取文件属性的时候,发现如果直接声明一个指针,然后把这个指针作为参数传给函数,会导致函数执行失败,原代码:

    #include <sys/stat.h>
    #include <unistd.h>
    #include <stdio.h>
    int main(void)
    {
        struct stat *sta_1;
        char pth_1[] = "./c12.txt";
        int re = stat(pth_1, sta_1);
        printf("result = %d
    ", re);
        printf("size = %d
    ", sta_1->st_size);
    }

    原因

    我猜测是因为声明指针并不代表在正文创建了这个变量,实际上它只是一个属于这个类型的指针,并不指向任何变量。所以,但凡用指针传入函数赋值的情况,必须在程序正文声明这个变量。

    示例代码1:

    int main(void)
    {
        struct stat *sta_p;
        struct stat stat_1;
        sta_p = &stat_1;
        char pth_1[] = "./c12.txt";
        int re = stat(pth_1, sta_p);
        printf("result = %d
    ", re);
        printf("size = %d
    ", sta_p->st_size);
    }

    示例代码2:

    int main(void)
    {
        struct stat stat_1;
        char pth_1[] = "./c12.txt";
        int re = stat(pth_1, &stat_1);
        printf("result = %d
    ", re);
        printf("size = %d
    ", (&stat_1)->st_size);
    }

    另一个案例,从文件读取内容到buff变量,也是必须在正文声明一个变量

    #include <unistd.h>
    #include <fcntl.h>
    #include <string.h>
    #include <stdio.h>
    
    int main(void)
    {
        #define BUFFER 4096
        char err_1[] = "Opps~an error occurred when copy.";
        char buf[BUFFER];
        short rnum = 0;
        char copy_1_pth[] = "./c14_copy.dat";
        int copy_1_fd = open(copy_1_pth, O_RDWR|O_CREAT, 0777);
        while((rnum = read(STDIN_FILENO, buf, BUFFER)) != 0){
            if(rnum != write(copy_1_fd, buf, rnum)){
                write(STDERR_FILENO, err_1, strlen(err_1));
                break;
            }
        }
        printf("Okay.
    ");
    }
  • 相关阅读:
    移动端开发基础【4】uniapp项目发布
    移动端开发案例【3】通讯录开发
    移动端开发基础【2】uni-app项目调试
    np.cross, np.count_nonzeros, np.isnan, np.transpose
    numpy中用None扩充维度
    NTU RGB+D数据集,骨架数据可视化
    文件映射,mmap
    转:Python pickle模块:实现Python对象的持久化存储
    Temporal Convolutional Networks (TCN)资料,扩张卷积
    梯度消失和爆炸,RNN,LSTM
  • 原文地址:https://www.cnblogs.com/yiyide266/p/9991250.html
Copyright © 2020-2023  润新知