[英]Returning a pointer to an array of ints in c++ (converted from string) - “invalid conversion” error
標頭:
#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
int i[8];
#endif
主要:
#include <iostream>
#include <string>
#include "header.h"
using namespace std
int main(){
int *test;
string bits = "10011011";
*test = func(bits); // ERROR 2 HERE
//my goal here is to have a pointer in main that
//points to the 1 address of the global var array i
} //if im totally missing the point and there is a
//better way to do this please let me know
功能:
#include <iostream>
#include <string>
using namespace std
int *func(string str){
int l = str.size();
int *ptr;
for(int k=0; k < l; ++k){
i[k] = s[k] - '0';
}
*ptr = i; // ERROR 1 HERE
return ptr;
}
大家好,
當我嘗試編譯以上代碼時,出現兩個錯誤,如標簽所示。 他們是:
錯誤1:從int *到int的無效對話錯誤2:從int到* int的無效轉換
似乎我必須對在這里使用的內容有基本的了解。 我不是將* ptr設置為指向數組i []的第一個內存地址嗎? 為什么編譯器告訴我我正在嘗試將指針的值設置為i []的值? 我想將指針的值設置為i []的ADDRESS。 如果我添加&,則會出現相同的錯誤。
錯誤2顯然跟隨錯誤1。這是相同的錯誤,只是向后。
我的問題是,當我試圖將func()中的* ptr指向數組i []時,我到底在做什么錯? 我想找到其他地方的答案都無濟於事。
謝謝。
編輯:這段代碼是原始代碼(從另一台PC上)的粗略復制,因此,如果您嘗試對其進行編譯,並且有錯別字,我深表歉意。
int *ptr;
聲明一個指向int
的指針,所以ptr
是一個指針:一個存儲某個int
的內存位置的變量。 當前,它並沒有特別指向任何內容,只是您可能不擁有的內存中的隨機位置。
*ptr
取消引用ptr
,因此*ptr
是ptr
指向的int
。
當你做*ptr = i;
您正在嘗試將ptr
指向的int
設置為i
,它是8 int
的數組。 在這種情況下,數組會衰減為指向其第一個元素的指針,因此您嘗試將int
設置為等於int*
,從而導致錯誤。
這應該只是ptr = i;
,但這不是必需的,因為您可以return i;
而且i
會變成一個指向數組第一個元素的指針。
同樣, *test = func(bits);
嘗試將test
指向的int
設置為等於func
返回的指針。 它應該只是test = func(bits);
,在這種情況下, test
包含的地址將成為func
返回的地址。 在這種情況下, test
將指向i
的第一個元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.