Hi all!!!
I'm starting to learn C++ on my own and I have a question about accessing a structure through a dynamic array. I've looked into some previous threads that apply to this but they all deal with structure composed of int variables. This concerns char and is driving me nuts.

#include <iostream>
using namespace std;

struct structname
{
   char pst[10];
};

int main(void)
{
   structname *pointername = new structname[3];
   pointername[0].pst = "Mocha";
   cout << pointername[0].pst << endl;
   delete pointername;   
   return 0 ;
}

I've attempted these syntaxes but to no avail
structname->membername=
(*structname).membername=
(structname).membername=

all I get is error message about const char* not being able to be converted to char.
Thanks for any help.

Dani AI

Generated

The compiler error happens because a C-style array member (like char pst[10]) is not assignable after the object is created, and a string literal has type const char[] which decays to const char*. That is why the direct assignment you tried fails: you cannot do array = "literal" after construction. See the notes on string literals and C-style arrays: string literal and arrays.

As suggested, the simplest modern fix is to use std::string and avoid manual new[] entirely. This makes assignment, copying and bounds handling trivial and safe:

struct Entry {
    std::string pst;
};

std::vector<Entry> list(3);
list[0].pst = "Mocha";

See std::string and std::vector.

If you must use a fixed-size char[], copy the bytes safely and explicitly ensure null-termination. strcpy is simple but unsafe for buffers; strncpy avoids overflow but can omit the terminator, so code must force a '\0' at the end:

char name[10];
std::strncpy(name, "Mocha", sizeof(name) - 1);
name[sizeof(name) - 1] = '\0';

See strncpy and strcpy for details and pitfalls.

Finally, was right about deletion: arrays allocated with new[] must be freed with delete[] (not delete). Prefer RAII: use std::vector, std::unique_ptr<T[]> or smart containers to avoid manual new/delete entirely; see delete and unique_ptr.

Recommended Answers

All 3 Replies

Member Avatar for Member #248612

Use std::string pst instead of char pst[]. Or you have to use strcpy() to assign a value.

thanks so much
I'll give it a shot and see how it goes.

Yeah, STL is the better way to go for C++.

Also, use delete[] pointername; instead of just delete.

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.