Thread: Using cout on a struct passed by pointer

  1. #1
    Registered User
    Join Date
    May 2016
    Posts
    3

    Using cout on a struct passed by pointer

    So I've been playing around with linked lists, and since I like to see the data I'm working with I tried to make a print function that would print out all the data in the list.

    I distilled the problem into simplest runnable code I could here,
    Code:
    #include <iostream>
    
    using namespace std;
    
    struct stuff
    {
        int data;
    };
    
    void printStructPointer(stuff *s)
    {
        cout << s->data << endl; // and this is what kills the program
    }
    
    int main()
    {
        stuff *p_stuff;
        p_stuff->data = 10;
    
        printStructPointer(p_stuff);
    
        return 0;
    }
    The program crashes. I'm confused because I'm able to change data member values when passing in the struct by pointer, so there's no problem accessing the data. But as soon as I use cout on a member variable the program crashes. Is there a limitation with cout that I don't know of, or am I missing something obvious?

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Actually your debugger would tell you that the crash occured because there was a problem accessing the data.

    Code:
    Program received signal SIGSEGV, Segmentation fault.
    0x00401400 in main () at PropaneACCS.cpp:18
    18          p_stuff->data = 10;
    (gdb) x p_stuff
    0x1f:   Cannot access memory at address 0x1f
    When you use pointers, you have to be very careful. One of the first steps in using pointers correctly is setting up something for the pointers to point to. See this training video for more: Binky Pointer Fun Video C++ (High Quality 640x560) - YouTube.

  3. #3
    Registered User
    Join Date
    May 2016
    Posts
    3
    stuff *p_stuff = new stuff; fixed it. Thanks

    I guess the confusion stemmed from being able to set data in a function, but not display it.
    I could only take that video for 37 seconds.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 12-23-2015, 07:35 AM
  2. Replies: 7
    Last Post: 03-04-2012, 11:17 AM
  3. Problem Modifying Struct Member Passed Into Function
    By soj0mq3 in forum C Programming
    Replies: 1
    Last Post: 04-27-2010, 01:07 AM
  4. help undestanding what pointer is being passed
    By reakinator in forum C Programming
    Replies: 1
    Last Post: 05-10-2008, 12:06 AM
  5. Comparing A Struct To A Passed Parameter
    By Anonymous in forum C++ Programming
    Replies: 1
    Last Post: 11-09-2002, 11:38 PM

Tags for this Thread