[英]Need to fill an array with const char* using std::string but it's not working(i think it's storing the pointers instead)?
我在 class 中定義了一個 const char* ,我需要先填充數字數據,然后再將其存儲在數組中
像這樣的東西
編輯:更好的最小可重現示例代碼
#include <string>
class A
{
public:
const char* a[3];
std::string s1;
void func1();
void func2();
void func3();
//func4(), func5(), func6()............func50();
void output();
void print();
};
void A::func1()
{
s1 = "1";//can be any number determined by the function being called
}
void A::func2()
{
s1 = "2";
}
void A::func3()
{
s1 = "3";
}
void A::output()
{
int i = 0, j = 0;
for (int i = 0; i < 3; i++)
{
switch (i)
{
case 0:
func1();
break;
case 1:
func2();
break;
case 2:
func3();
break;
}
a[i] = s1.c_str();
}
}
void A::print()
{
for (int i = 0; i < 3; i++)
{
printf("%s ", a[i]);
}
}
int main()
{
A example;
example.output();
example.print();
}
我希望這里的數組是 = {1, 2, 3},但它是 {3, 3, 3}。 有幾個這樣的功能。
這是上一個,解釋起來有點復雜,所以我在上面寫了
class A:
{
public:
const char* s1;
void func1();
void func2();
void func3();
//etc.. there are several 50 other functions like this but i've omitted them
void output();
}
void A::func1()
{
//do some function work here
int data = 6//can be anything
std::string n = std::to_string(n);
s1 = n.c_str();
//do something else
}
void A::func2()
{
//do some function work here
int data = 6//can be anything
std::string n = std::to_string(n);
s1 = n.c_str();
//do something else
}
//etc...
void output()
{
const char* a[16];
int j = 0;
while(something)
{
switch(i):
{
case 1:
func1();
break;
case 2:
func2();
break;
case 3:
func3();
break;
//etc..
}
const char* a[j % 16] = s1;
j++;
}
//draw a to the screen
}
基本上我需要以字符串的形式存儲來自各個 function 的“當前”16 個 int 數據並實時繪制它(數組預先填充了“NULL”),但問題是數組得到填充相同的值。 例如,如果 func1() 為 6 且 func2() 為 5 且 func3() 為 4 且當前 func3() 已被調用,則 const char* a 數組為 = {"4", "4", "4" , "NULL"....} 當它應該是 {"6", "5", "4", "NULL", "NULL"....} 所以當我將它實時繪制到屏幕上時當它應該是 = 6、5、4、NULL、NULL、NUll 時,我只看到 4。陣列變化。 如果需要更清楚,我可以解釋
歡迎來到懸空指針的世界。 據說 C++ 對那些(或至少對 C 不太敏感)免疫,但前提是您不在中間混合原始指針。
當你寫a[i] = s1.c_str();
您使a[i]
指向s1
擁有的數據。 該指針僅在s1
被修改之前有效。 在這里你很幸運,因為s1
的所有 3 個值都具有相同的大小,因此實現重新使用了相同的 memory。 所以這 3 個指針仍然指向一個有效地址,它只包含s1
的最后一個值。
但形式上, a[0]
和a[1]
是懸空指針,因為它們指向的 object 已經到了生命的盡頭,只有a[2]
是一個有效的指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.