zoukankan      html  css  js  c++  java
  • [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.
    ");
    }
  • 相关阅读:
    redis集群报Jedis does not support password protected Redis Cluster configurations异常解决办法
    redis集群密码设置
    Redis 3.2.4集群实战
    Redis3.2.4 Cluster集群搭建
    redis集群环境的搭建和错误分析
    Centos iptables防火墙关闭启动详解
    动态的表格数据
    ubuntu使用抓包工具,charles
    layer结合art实现弹出功能
    禅道开源版源码安装
  • 原文地址:https://www.cnblogs.com/yiyide266/p/9991250.html
Copyright © 2011-2022 走看看