我有一個相對簡單的問題,我試圖保持儘可能最小的問題,但希望包含一個例子,以便人們能夠理解我所引用的內容。局部變量指向投射
我有一個函數聲明一個局部變量(unsigned int
),然後我使用一個指針將該unsigned int
的值複製到一個指針。我知道在該函數結束之後,該局部變量將不再存在。唯一真正重要的是價值。然後我試着將它傳遞給func2()
它必須有一個void *
作爲參數(是不是我的選擇),只是單純的看價值,我認爲應該是2
自從我加入1
:
void func2(void * arg){
//was not my choice to have void * be the argument.. was a requirment
unsigned int val = *(unsigned int) arg;
//When I print this the value should be 2..
}
void createPointer(){
unsigned int localVariable = 1;
localVariable = localVariable + 1;
unsigned int *pointer = &localValue;
*pointer = localValue;
//my goal here is to copy the VALUE of the local variable
//as I need this pointer to still point to this value after this function returns
//in my actual code, this function is on a whole seperate file.. so it is really important that the pointer is stored in memory
func2((void *) pointer);
}
int main(int argc, char *argv[]){
createPointer();
}
但是,當我試圖在func2()
中打印變量val
時,它只是打印出一些隨機地址作爲文本,這讓我認爲它仍然引用了localVariable
,我只想複製它的值。
所以,我的問題是有沒有適當的語法方法來複制本地變量的值?當我投射並取消投射到void *
時,我做錯了什麼?
此代碼不會編譯... –
請顯示真正完整的代碼。那是[mcve]。代碼存在多個問題,並且我們不知道這是否代表您的代碼的真實性,或者它是否只是您描述問題的方式中的問題。因此,總是顯示一個完全重現你的問題的MCVE。 – kaylum
@OliverCharlesworth是 – Gaurav