2016-04-03 20 views
-1

嘿傢伙我試圖打印出字符串文字的地址和命令行參數的開始和結束。字符串文字和命令林德論點的地址

int main(int argc, char *argv[]) { 
    printf("Address of argc: %p\n", (void*)&argc); //Is this how u find the address of argc? 
    //How to find out the start and end of command line arguments? 
    printf("Start of argv: %p\n", (void*)argv); //Like this? I am not sure... 

    char* strLiteral = "Hello world"; 
    //how to find the address of "Hello world"? (Address of string literal) 
} 

我做了我的研究,並且我聽到類似字符串文字的地址這樣的答案是不允許的......這是真的嗎?這是什麼意思?字符串文字沒有地址?請告訴我如何獲得命令行參數的開始和結束地址。 感謝您抽出寶貴時間。

+1

「我聽說過類似於接受字符串字面值的答案是不允許的」 - *你在哪裏聽到了?那? **不允許向所述地址位置寫入**。以只讀方式使用這些地址,否則就不可能將它們發送給任何需要「const char *」的函數(例如,像printf一樣用'%s'指定符來引發)。如果你不能使用他們的地址,他們將毫無價值。 – WhozCraig

+0

from here http://stackoverflow.com/a/12601183/859385 – user859385

+1

你與user6146524有關嗎?請參閱:http://stackoverflow.com/questions/36368780/are-we-able-to-print-out-the-address-for-string-literal –

回答

-1

您可以獲取字符串文字的地址。看看下面的代碼,特別是從主返回之前的行...

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

int main(const int argc, char *argv[]) { 
    assert(argc > 1); 
    printf("argc == %d &argc == %p\n", argc, &argc); 
    printf("argv[0] == %s &argv[0] == %p\n", argv[0], &argv[0]); 
    printf("argv[1] == %s &argv[1] == %p\n", argv[1], &argv[1]); 
    const char *test  = "You can take the address of this"; 
    printf("test == %s  &test == %p\n", test, &test); 
    printf("*address of string literal == %p\n", &"address of string literal"); 
    return 0; 
} 
+4

從這個看起來,我們可以考慮變量測試的地址。不是字符串文字。糾正我,如果我錯了。 – user859385

+0

'argv [1]'是字符串的第一個字符的地址。這可能是您想要作爲指針值打印的內容。 '&argv [1]'是argv數組的地址 - 完全不同。 – selbie

+0

'argv [argc]'最好是不確定的。 – selbie