why this program crashes?. what is the fix?.

    #include <iostream>
    typedef struct test
    {
        int array[10];
    }test;
    static test *p;
    int main(int argc, char* argv[])
    {
        p->array[0] = 10;
        std::cout << p->array[0] << std::endl;
        return 0;
    }

Recommended Answers

All 4 Replies

By using the key word typedef, you are just defining the struct and no memory is being allocated for it. Hence, static test *p; is not pointing to any valid memory location.

If using a typedef for your struct use something like:

typedef struct _test {
    int array[10];
} test, *ptest; 

Where test and ptest are the types used by your variables.
e.g test t = {0}; for static allocation, ptest p = new test; for dynamic allocation.

So to dynamically use the struct you'd have:

int main(int argc, char* argv[])
{
    ptest p = new test; // allocate memory
    if (nullptr == p)   // check whether memory was allocated
        return 1;

    p->array[0] = 10;
    std::cout << p->array[0] << std::endl;

    delete p; // free the memory

    std::cin.get();

    return 0;
}

this works. is this ok?.

#include <iostream>
typedef struct {
int Array[10];
}test; 

static test t;

void display()
{
    for (int i = 0; i < 10; i++)
        std::cout << t.Array[i] << std::endl;
}

int main(int argc, char* argv[])
{
    for (int i = 0; i < 10; i++)
        t.Array[i] = i;

    display();
    return 0;
}

Yes that's fine, though you could avoid the use of a global variable by declaring static test t; inside main and the passing the variable instance to your display function.

void display(const test &t)
{
    // rest of code
}

and call it with display(t);

Why this program crashes not because of typedef but because of using an uninitialized variable. Look at your code at line #6: You declared static test *p and, without allocating it, used in your int main() function.

On your second post, static test p should work of course because variable p is automatically allocated from the stack.

If you want to use a pointer to your test struct like test *p, you must allocated some memory for it either by using the new operator (as suggested by nullptr) or by any appropriate method.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.