我從指標開始,我看不出這段代碼出現段錯誤的原因。我想我以錯誤的方式訪問陣列,那么我應該如何訪問它呢?
const int MAXIMO_LIBROS_INICIAL = 20;
typedef struct {
string titulo;
char genero;
int puntaje;
} libro_t;
int main(){
libro_t** libros = new libro_t*[MAXIMO_LIBROS_INICIAL];
int tope_libros = 0;
libros[tope_libros]->titulo = "hola";
return 0;
}
uj5u.com熱心網友回復:
您正在創建一個不指向任何地方的指標陣列。您嘗試訪問無效記憶體時遇到段錯誤。您需要創建指標將指向的各個物件,例如:
const int MAXIMO_LIBROS_INICIAL = 20;
struct libro_t {
string titulo;
char genero;
int puntaje;
};
int main(){
libro_t** libros = new libro_t*[MAXIMO_LIBROS_INICIAL];
for (int i = 0; i < MAXIMO_LIBROS_INICIAL; i) {
libros[i] = new libro_t;
}
int tope_libros = 0;
libros[tope_libros]->titulo = "hola";
...
for (int i = 0; i < MAXIMO_LIBROS_INICIAL; i) {
delete libros[i];
}
delete[] libros;
return 0;
}
不過,您確實有 1 級間接太多,應該降低 1 級*,例如:
const int MAXIMO_LIBROS_INICIAL = 20;
struct libro_t {
string titulo;
char genero;
int puntaje;
};
int main(){
libro_t* libros = new libro_t[MAXIMO_LIBROS_INICIAL];
int tope_libros = 0;
libros[tope_libros].titulo = "hola";
...
delete[] libro_t;
return 0;
}
話雖如此,請考慮使用std::vector或std::array改為讓他們為您管理記憶體,例如:
#include <vector> // or: <array>
const int MAXIMO_LIBROS_INICIAL = 20;
struct libro_t {
string titulo;
char genero;
int puntaje;
};
int main(){
std::vector<libro_t> libros(MAXIMO_LIBROS_INICIAL);
// or: std::array<libro_t, MAXIMO_LIBROS_INICIAL> libros;
int tope_libros = 0;
libros[tope_libros].titulo = "hola";
...
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/506473.html
下一篇:ORM增刪改查并發性能測驗2
