ポインタを使用して C 内の現在の作業ディレクトリを印刷します

StackOverflow https://stackoverflow.com//questions/9697056

  •  13-12-2019
  •  | 
  •  

質問

標的 :Linux マシン上の c で現在の作業ディレクトリを出力します。

ポインターを使用しなくても、正しい出力が得られます。

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
int main()
{
    //char buf[1024];

    char * buf;
    char * cwd;
    buf = (char *)malloc(sizeof(char) * 1024);

    if((cwd = getcwd(buf, sizeof(buf))) != NULL)
            printf("pwd : %s\n", cwd);
    else
            perror("getcwd() error : ");
    return 0;
}

しかし、ポインタを使用すると、次のエラーが表示されます

getcwd() error : : Numerical result out of range
役に立ちましたか?

解決

bufがポインタである場合、sizeof(buf)は、コメントアウトしたコードのように、アレイのサイズではなく、ポインタを保存するために必要なバイト数です。

代わりに割り当てたサイズ(すなわち、1024)をこのように渡す必要があります。

size_t allocSize = sizeof(char) * 1024;
buf = (char *)malloc(allocSize);
if((cwd = getcwd(buf, allocSize)) != NULL) ...
.

他のヒント

sizeof(buf) のサイズを返します char* プロセッサのビット幅は何ビットでも構いません (32 ビットまたは 64 ビット)。

ここで必要なのは、malloc したマジックナンバー、この場合は 1024 を使用することです。

これを試して:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

int main()
{
    //char buf[1024];

    char * buf;
    char * cwd;
    buf = (char *)malloc(sizeof(char) * 1024);

    if((cwd = getcwd(buf, 1024)) != NULL)
            printf("pwd : %s\n", cwd);
    else
            perror("getcwd() error : ");
    return 0;
}

char *getcwd(char *buf, size_t size);
ここではサイズを次のように指定しています sizeof(buf) のサイズを返します buf マシンに依存するポインター。
引数に 1024 を指定する必要があります。 getcwd.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top