1

I have a struct defined as

typedef struct {
char *somechar;
} Random;

I instantiate a struct like this -

Random *r=(Random *)malloc(sizeof(Random));

How to individually assign characters one by one to somechar? I"ve used

r->somechar+0='b';
r->somechar+1='a';

and this doesn't work.

Chethana
  • 21
  • 5

2 Answers2

4

First of all you need to allocate the data pointed by char* somechar: you are allocating space for the struct which contains the pointer, not the pointed data. You need to allocate it separately

Random *r = malloc(sizeof(Random));
r->somechar = malloc(20); // allocate space for 20 characters

Mind that you don't need to cast the result of malloc since in C a void* can implicitly be converted to any other pointer type. In addition you must make sure that the value returned by malloc is a valid address (hence it's != NULL) to be sure that the heap allocation didn't fail.

Finally to access the individual elements of the char* you have two options:

  • using the correct index access operator, so r->somechar[1] = ..
  • using pointer arithmetic directly, *(r->somechar+1) = ..

The latter is similar to what you were trying but you need to use the dereference * operator to tell the compiler that you want to assign to the value pointed by the address.

Don't forget that you need to deallocate memory too, for both somechar and r by calling free(r->somechar) and free(r).

Jack
  • 131,802
  • 30
  • 241
  • 343
2
typedef struct {
    char *somechar;
} Random;

Requires first to allocate the struct itself:

Random *r = malloc(sizeof(*r));

and then an array somechar has to point to. Without this, it will be uninitialized, invoking undefined behaviour if you dereference it.

r->somechar = malloc(MAX_ARRAY_LENGTH);

MAX_ARRAY_LENGTH has to be set to the max. number of entries you want to store into that char array. As sizeof(char) is defined 1 by the standard, no need to specify this explicitly.

Note that you should not cast void * as returned by malloc & friends. Whoever tells you should read here.

Caution:

  • Always check the result of system functions. malloc can fail, returning a null pointer. Dereferencing such is undefined behaviour and can make your program crash - if you are lucky (if not, you will not notice anything, but get strange behaviour - like nasal demons).
  • If you want to store a C-string in that char array, account for the trailing '\'
  • Note that all malloced memory is uninitialized. If you want zeroed memory, use calloc.
  • free both allocated blocks! Use the reverse order of allocation.

If using C99 or C11 (recent standard), you can use a flexible array member and avoid the second allocation:

typedef struct {
    char somechar[];    // must be last member of the struct
} Random;

...

Random *r = malloc(sizeof(*r) + MAX_ARRAY_LENGTH);

This will allocate the struct with the array of the given size in a single block.

Community
  • 1
  • 1
too honest for this site
  • 12,050
  • 4
  • 30
  • 52