我在這個問題有一段時間一直盯着我似乎不能找到一個顯而易見的解決方案,也沒有描述具體問題的詞彙。我會盡我所能:C函數輸入被莫名其妙地採取同樣的內存地址
#include <stdio.h>
#include <malloc.h>
#include <string.h>
char** findWords(char** words, int wordsSize, int* returnSize) {
*returnSize = 15; //<- wordsSize and returnSize have the same memory address????
printf("wordsSize is %d\n", wordsSize);
for(int i=0; i<wordsSize; i++)
{
printf("i: %d first word: %s, len: %d\n", i, words[i], strlen(words[i]));
}
}
int main(void){
char **test; // this should be const char but func decl is predefined
test[0] = "Hello";
test[1] = "Alaska";
test[2] = "Dad";
test[3] = "Peace";
int *foo;
findWords(test, 4, foo);
printf("%d", *foo);
}
當findWords()被調用時,我看到& wordsSize和* returnSize是相同的(即它們具有相同的內存地址)
[New Thread 3492.0x9d0]
Breakpoint 1, findWords (words=0x7efde000, wordsSize=4, returnSize=0x28ff24) at keyboardrow.c:15
15 printf("wordsSize is %d\n", wordsSize);
(gdb) print &wordsSize
$1 = (int *) 0x28ff24
(gdb) print returnSize
$2 = (int *) 0x28ff24
(gdb)
上午我錯過明顯的東西?在我看來,wordsSize和returnSize應該有不同的內存地址,因爲它們是兩個單獨的變量。
你的程序的行爲是不確定的。你沒有初始化'test',那麼它是指向'test [0]'分配的是什麼? – StoryTeller
你想找到並閱讀一本好的C書。你也想看看你的編譯器給你的警告。不這樣做==浪費你的時間。將'-Wall -Wextra -Wpedantic -Werror'添加到您的編譯標誌。 –
謝謝,我重新閱讀K&R2,和我已經添加這些標誌 - 它提出了一個:「測試」是在此函數中使用的未初始化[-Werror =未初始化] 測試[0] =「你好」; – jaytielle