[英]Why am i getting seg. fault?
I'm starting with pointers, and I can't see the reason why I'm getting a segfault with this code.我从指针开始,我看不出这段代码出现段错误的原因。 I guess I'm accessing the array the wrong way, so how should I access it?我想我以错误的方式访问数组,那么我应该如何访问它呢?
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;
}
You are creating an array of pointers that don't point anywhere.您正在创建一个不指向任何地方的指针数组。 You are getting a segfault from trying to access invalid memory.您尝试访问无效的 memory 时遇到了段错误。 You need to create the individual objects that the pointers will point at, eg:您需要创建指针将指向的各个对象,例如:
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;
}
Though, you really have 1 level of indirection too many, and should drop one level of *
, eg:不过,您确实有 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;
}
That being said, consider using std::vector
or std::array
instead, let them manage the memory for you, eg:话虽如此,请考虑改用std::vector
或std::array
,让他们为您管理 memory ,例如:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.