Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an instance of a struct in C++?

Tags:

c++

struct

The issue is an "Access violation writing location 0x00000000" error message right after I initialize the bk variable to NULL. My guess is I should reserve memory space in advance to assign NULL ( something like Book bk = new Book(); ) but I have not been able to figure out how to do it in C++ till now.

Book.h

#ifndef Book_H
#define Book_H

struct _book;
typedef _book* Book;

Book CreateBook(unsigned int pageNum);

Book.cpp

#include "Book.h"
#include <iostream>

#ifndef Book_CPP
#define Book_CPP

using namespace std;

struct _book
{
    int pageNum;
};

Book CreateBook( unsigned int pageNum){

    Book bk = NULL; 

    bk->pageNum = pageNum;

    return bk;
};
like image 385
G21 Avatar asked Sep 26 '13 18:09

G21


2 Answers

You're assigning bk to NULL and then trying to access a member of it. That's the same as a null pointer in Java, and what you're doing would typically raise a NullPointerException (thanks from the comments). If you want to create a pointer to your struct, you need to use operator new:

bk = new _book;
// ...
return bk;

and then make sure you call delete on the pointer when you're done with it.

I would advise against using pointers here, though. Unlike other languages, C++ lets you create objects by value. It also allows for references and pointers, but only use pointers when you absolutely must. If you simply want to create a book object with a given pageNum, you should create a constructor while you're at it:

struct _book {
    int pageNum;
    _book(int n) : pageNum(n) // Create an object of type _book.
    {
    }
};

and then you can invoke it like

_book myBook(5); // myBook.pageNum == 5

If you're new to C++, please get yourself a good book on it. It's not just a low-level language, and it's also not just an OOP language. It's a multi-paradigm swiss army knife language.

like image 98
bstamour Avatar answered Oct 02 '22 03:10

bstamour


This is what you need:

Book CreateBook( unsigned int pageNum){

    Book bk = new _book();

    bk->pageNum = pageNum;

    return bk;
}

your bk was null and you cannot access pageNum when the pointer is null.

And don't forget to call delete on bk when you are done using it.

like image 33
qxixp Avatar answered Oct 02 '22 01:10

qxixp