How can I insert value in a char array?

Erik_Ond

I'm trying to create a linked list and save the value "Peter" in the first list element. I'm having a problem with the char array. I can't insert "Peter" in it.

    #include <iostream>
    #include <string>
    #include <stdlib.h>

    using namespace std;

    struct ListElement{
    char name[20];
    ListElement* next;

    };

   int main ()
   {

   ListElement* first;
   first = new ListElement;
   first -> name= "Peter"; // Array type 'char [20]' is not assignable


   };
Adrian Mole

To set the value of a char[] array, you should use the strcpy or strncpy function, like:

strcpy(first->name, "Peter");

But, better would be to use the std::string type, which you can directly assign:

struct ListElement{
    std::string name;
    ListElement* next;
};

Then first->name = "Peter"; is valid code.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do I insert char* to array of structures?

How can I insert value in array inside object field in mongodb?

how can I make a copy the same value on char pointer(its point at) from char array in C?

How can I convert a String to a char array?

How do I insert array value into object?

How can i put a char pointer into an array char in a for loop in {C}

How can I insert array data to a file?

How I can insert array data in laravel?

How can I insert into a Postgresql JSON array

Char array, string represents a memory address how can i add value to that address?

How can I transform a char array to a string representing its value in hexadecimal?

How can I create an std::array of char array?

How can I store an array of char in an array in c++

How can I change value array into array

How can I insert a value in the value attribute of a div with JavaScript?

How can I insert an array into a specific array element using Jolt

How do I return a char array of an unknown value?

How do I change a particular int value in an array to a char in C?

How can I change the value of a char using a pointer?

How can I retrieve Enum from char value?

How can I add to the ascii value of a char letter?

How can I copy a string into a char array pointer?

How can I convert CharArray / Array<Char> to a String?

How can I split char array after certain number of characters

How can I copy an element of an array of chars to a char?

How can I return an char array from a function using malloc

How can i access the char array inside of an std::string?

how can I get char array size in function (language c)?

How can I convert an integer to a hex byte stored in a char array?