簡體   English   中英

linux stat函數中struct stat * buffer和&buffer有什么區別

[英]what is the different between struct stat * buffer and &buffer in linux stat function

我正在嘗試獲取父目錄的統計信息。

如果我像下面這樣寫代碼,則會返回error: Bad address

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <dirent.h>

int main(int agrc, char * argv[]){
    struct stat *buffer;
    int res = stat("..", buffer);
    if(res != 0){
        perror("error");
        exit(1);
    }
    //printf("%d", buffer->st_ino);

}

但是,如果我在下面編寫這樣的代碼,就沒有問題。

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <dirent.h>

int main(int agrc, char * argv[]){
    /* struct stat *buffer; */
    struct stat buffer;
    int res = stat("..", &buffer);
    if(res != 0){
        perror("error");
        exit(1);
    }
    //printf("%d", buffer->st_ino);
    printf("%d", buffer.st_ino);

}

我不知道為什么結果不同。

定義struct stat * buffer的變量buffer struct stat * bufferstruct stat的指針

&buffer也是struct stat的指針

該功能在手冊頁中定義如下

SYNOPSIS
       #include <sys/types.h>
       #include <sys/stat.h>
       #include <unistd.h>

       int stat(const char *pathname, struct stat *buf);
       ...

我希望結果都能成功,為什么結果不同? 任何人都可以提供幫助,非常感謝。

struct stat buffer; ,堆棧上已為buffer分配了內存。
但是使用struct stat *buffer; 沒有為buffer分配內存。 您必須使用內存分配功能來分配內存。 這種分配發生在所謂的堆上。

struct stat *buffer = malloc(sizeof(struct stat));

請注意, stat()統計path指向的文件並填寫buf 因此,如果buf不指向程序所擁有的內存,則會導致error: Bad address

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM