0

This is the struct

typedef struct struct1
{
    char words[kInputSize];
    struct WordNode* next;
}struct1;

I am getting error for allocationg memory block for block->words.

struct1* add(struct1** newHead)
{
    struct1* block= NULL;


    // allocate a block of memory for new record
    block->words = malloc(strlen(words) + 1);  //I am trying to add this line but I am not able to do it.
    }

I am getting E0137 and C3863 error of visual studio code in the last line

Yakozah
  • 3
  • 2
  • 2
    You appear to be writing C code. If so, please use the appropriate language tag. C++ is a different language, and the tags can't be used interchangeably. – cigien Apr 05 '21 at 04:35
  • Does this answer your question? [Cannot modify char array](https://stackoverflow.com/questions/14396202/cannot-modify-char-array) – Ranoiaetep Apr 05 '21 at 04:36
  • `block->words` is an array. You are assigning to it as if it is a pointer. An array is not a pointer, and a pointer is not an array. Specifically, an array is a collection of elements. A pointer is a variable that contains the address of something else. The fact that pointers and arrays can be used interchangeably *in some circumstances* does not mean they are the same thing. One difference - resulting from them being different things - is that pointers can be assigned (`const` qualifiers and the type system permitting) and arrays cannot. – Peter Apr 05 '21 at 05:35

1 Answers1

2

In your posted struct1, words is declared like this:

char words[kInputSize];

... and then you try to set it equal to a pointer, here:

block->words = malloc(strlen(words) + 1);

This doesn't work because in C++ (or C for that matter) you are not allowed to set an array equal to a pointer.

If you want to be able to set words equal to a pointer (as returned by malloc()) you would need to declare it as a pointer inside the struct, instead:

char * words;

If, on the other hand, you really just want to copy over the string-data from words into the existing char-array at block->words, one way to do that would be:

#include <cstring>

[...]

strncpy(block->words, words, sizeof(block->words));

(Note that the sizeof(block->words) invocation to determine the number of bytes in the char-array only works when block->words is declared as a char-array; if you change it to char * words as suggested above, then sizeof(block->words) will then return either 4 or 8 [depending on the size of a pointer on your system] and that is almost certainly not what you want)

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234