[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\n", re);
    printf("size = %d\n", 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\n", re);
    printf("size = %d\n", 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\n", re);
    printf("size = %d\n", (&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.\n");
}

 

转载于:https://www.cnblogs.com/yiyide266/p/9991250.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值