所以我遇到了一個非常令人困惑的問題,我試圖將字串從結構陣列的向量列印到控制臺。整數列印得很好,但是存盤在這些結構中的字串被設定為“”。我不知道這里發生了什么,但是在設定了如下所示的測驗后,這個問題仍然存在。任何解決這個問題的幫助都會非常有用。
還應該提到我對c 還是新手,所以如果這里的問題很簡單,我深表歉意。
#include <iostream>
#include <string>
#include <vector>
#include "Header.h"
//Test struct
struct testStruct
{
string testString;
int testInt;
};
testStruct testArray[1] = {
testArray[0] = {"String works", 69}
};
int main()
{
srand(time(NULL));
vector < testStruct > test;
test.push_back({ testArray[0] });
cout << test[0].testString << "\n"; // prints "", should print "String works"
cout << test[0].testInt << "\n"; // prints 69
characterCreation();
checkPlayerStats();
introduction();
return 0;
}
uj5u.com熱心網友回復:
這讓我很驚訝。以下代碼是合法的(至少在語法上)
testStruct testArray[1] = {
testArray[0] = {"String works", 69}
};
但是如果你用合理的版本替換它
testStruct testArray[1] = {
{"String works", 69}
};
然后您的程式按預期作業。
我希望您的版本具有未定義的行為,因為您將(此處testArray[0] = ...)分配給尚未創建的陣列元素。
uj5u.com熱心網友回復:
testStruct testArray[1] = {
這定義了這個陣列。然后,這個陣列被構造出來。對于這個問題,究竟在什么時候構造這個陣列并不重要。注意到里面的內容{ ... }被評估并用于構造這個陣列就足夠了。
testArray[0] = {"String works", 69}
此運算式構造陣列的第一個值。此運算式為 賦值testArray[0]。
問題是testArray[0]尚未構建,這就是現在正在發生的事情。這是未定義的行為。就像先來的一樣:先有雞還是先有蛋。這是未定義的。
您在程式的結果中看到了未定義行為的結果。程式的結果可以是任何東西,而這恰好是動搖的結果,因為在塵埃落定之前,就可執行代碼而言,您的編譯器和 C 庫碰巧產生了什么。
uj5u.com熱心網友回復:
所以首先你需要使用std::vector,而且std::cout你還沒有使用過using namespace std。
但你的主要問題是:
testStruct testArray[1] = {
testArray[0] = {"String works", 69}
};
首先,它不應該是全球性的,因為它不需要。
其次,這是不正確的:
testArray[0] = {"String works", 69}
您不應該在陣列中執行此操作。您可能打算這樣做:
testStruct testArray[1] = {{"String works", 69}}; // uses aggragate initialization.
所以現在這將有正確的輸出,使用以下程式:
#include <iostream>
#include <string>
#include <vector>
#include "Header.h"
//Test struct
struct testStruct
{
string testString;
int testInt;
};
int main()
{
testStruct testArray[1] = {{"String works", 69}};
srand(time(NULL));
vector < testStruct > test;
test.push_back({ testArray[0] });
cout << test[0].testString << "\n"; // prints "String works".
cout << test[0].testInt << "\n"; // prints 69.
characterCreation();
checkPlayerStats();
introduction();
return 0;
}
假設你有Header.h頭檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/532350.html
標籤:C 数组细绳向量结构
下一篇:在主類中呼叫陣列方法
