0

コードは次のとおりです。

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

void foo(int* ptr) {
    printf("ptr is %x\n", ptr);
}

void main() {
    int* ptr = (int*)malloc(sizeof(int));
    printf("ptr is %x\n", ptr);
    foo(ptr);
    free(ptr);
}

...そして彼は出力です:

ptr is 0x007446c0
ptr is 0x00000000

...そしてここで質問です:
なぜこれが私に起こっているのですか?

4

2 に答える 2

3

これは、 inがポインタではなく符号なし整数を想定しているため%xに発生します。printf

必要な動作を得るためにプログラムを修正する方法は次のとおりです。

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

void foo(int* ptr) {
    printf("ptr is %p\n", (void*)ptr);
}

int main() {
    int* ptr = malloc(sizeof(int));
    printf("ptr is %p\n", (void*)ptr);
    foo(ptr);
    free(ptr);
    return 0;
}

ここに ideone へのリンクがあります。実行すると、期待どおりの結果が得られます。

ptr is 0x8fa3008
ptr is 0x8fa3008
于 2013-03-22T13:07:57.090 に答える
1

あなたのプログラムは未定義の動作を呼び出すため、私は推測します。これがあなたが意味したと思うことです:

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

void foo(int* ptr) {
    printf("ptr is %p\n", (void *) ptr); /* %x tells printf to expect an unsigned int. ptr is not an unsigned int. %p tells printf to expect a void *, which looks a little better, yeh? */
}

int main() { /* main ALWAYS returns int... ALWAYS! */
    int* ptr = malloc(sizeof(int)); /* There is no need to cast malloc. Stop using a C++ compiler to compile C. */
    printf("ptr is %p\n", (void *) ptr);
    foo(ptr);
    free(ptr);
}

それはあなたの問題を解決しますか?

于 2013-03-22T13:08:02.360 に答える