• [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.
    ");
    }
  • 相关阅读:
    【区间DP】低价回文
    【二分图】文理分班
    【线型DP】洛谷P2066 机器分配
    电路原理 —— 电路基本概念和电路定律(1)
    数据结构(1) —— 绪论
    静电场 —— 电通量 高斯定理
    电路原理 —— 三相电路(1)
    静电场 —— 电场 电场强度
    静电场 —— 电荷 库伦定律
    Python——jieba库初使用
  • 原文地址:https://www.cnblogs.com/yiyide266/p/9991250.html
Copyright © 2020-2023  润新知