Ask coding questions

← Back to all posts
What's wromg with this SIMPLE code snippet
boowho (0)

It throws segmentation error.... BTW, I'm a returning C programmer after MANY years away from programming....


#include <stdio.h>
#include <stdint.h>

struct xxx
{
int nr;
uint32_t *rk;
uint32_t buf[68];
};

xxx *ctx;

int main()
{

ctx->nr = 10;

return 0;

}

Commentshotnewtop
boowho (0)

OK, so line 21 is the problem..... What SHOULD it look like??
I did a quick search of the differences in C and C++ regarding pointers and didn't really find anything I understood. Thanks

tree5673 (0)

Your pointer needs to point to something. A pointer is a variable that holds the location in the program memory of a specific value. You need to initialize the pointer like so:

xxx *ctx = &[Any object]; // Do not put []
Then you can dereference (follow) the pointer to the structure with the "->" operator.

Also, if you do not need to change where the pointer points to, you can just use a reference (type &name = [reference_to]) instead of a pointer and you do not need to dereference operator (* or ->).

boowho (0)

@tree5673
EDIT: I got it working. Thanks to all!!

Did as you suggested the & operator throws a compiler error. Took the && out and segmentation srror.

#include <stdio.h>
#include <stdint.h>

struct xxx
{
int nr;
uint32_t *rk;
uint32_t buf[68];
};

struct xxx *ctx;
struct xxx yyy;

int main()
{
*ctx = &yyy;
ctx->nr = 10;

return 0;

}

CodeLongAndPros (875)
  1. This is C++
  2. Line 21 is the problem.
CodeLongAndPros (875)

@Mohammad96 I'm not very good with pointers, but I'm guessing that you are trying to access memory outside your segment. I don't see anything that I know is wrong.

StudentFires (327)

@Mohammad96 C++ compilers work differently than C compilers, not everything is compatible.

boowho (0)

@StudentFires Thanks to all for advice. I DID eventually get it worked out.

boowho (0)

@StudentFires Ignore I figured it out myself.

Thanks

StudentFires (327)

@boowho I know that you figured it out, but I'm curious, what is this all for?