Splitting declaration and assignment with string array in C++

array of strings in c
string in c
how to initialize string array in c
2d array of strings in c
array of strings in c - geeksforgeeks
how to print array of strings in c
dynamic array of strings in c
how to compare array of strings in c

There is probably a really simple solution to this, but I can't seem to figure it out. I can find countless examples of how to create a string array in C++, but I can't find one that shows how to make the assignment separate.

I currently have a declaration with assignment that looks something like this:

static const char *desc[3] = { "apple", "banana", "orange" };

What I would like to do is split the declaration and assignment to separate statements. The declaration:

static const char *desc[3];

...but I can't seem to figure out how to do the assignment. I have tried the following:

desc = { "apple", "banana", "orange" }; // Expression must have a modifiable lvalue. error: assigning to an array from an initializer list
*desc = { "apple", "banana", "orange" }; // Too many initializer values. error: cannot convert '<brace-enclosed initializer list>' to 'const char*' in assignment
desc[3] = { "apple", "banana", "orange" }; // Too many initializer values. error: cannot convert '<brace-enclosed initializer list>' to 'const char*' in assignment
*desc[3] = { "apple", "banana", "orange" }; // Expression must have a modifiable lvalue. error: assignment of read-only location '* desc[3]'

Your first example allocates the array on the stack, which is only possible because the compiler knows the size (since all strings are fixed length and provided during declaration).

When you separate declaration and initialization, your compiler has no way of knowing how much memory to allocate on the stack, so you need to change your type into a pointer (which has a fixed size, no matter what it points to):

static const char** desc;

and then use new to allocate enough memory for the array:

desc = new const char*[3]{ "apple", "banana", "orange" };

However that means that you now also must delete[] the array pointed to by desc, as otherwise you get a memory leak.

Much better would be to use modern container types like std::vector and std::string:

static std::vector<std::string> desc;

and then

desc.push_back("apple");
desc.push_back("banana");
desc.push_back("orange");

These classes take care of all the nasty memory management for you under the hood.


Another alternative, if you really want a raw array, and don't want to rely on new[] and delete[]is to declare a fixed size array with enough space for your strings like so:

static const char desc[3][128];

and then later copy the string values into that block of memory:

std::strcpy(desc[0], "apple");
std::strcpy(desc[1], "banana");
std::strcpy(desc[2], "orange");

However I really don't recommend doing this, as you risk bugs in the long run when you add or remove strings, or change their lengths etc.

Array Of C String - How to play with strings in C, Since all but the highest dimension can be omitted from an array declaration, the above declaration can be reduced to: #define MAX_STRING_SIZE 40 char arr[][  strtok accepts two strings - the first one is the string to split, the second one is a string containing all delimiters. In this case there is only one delimiter. strtok returns a pointer to the character of next token. So the first time it is called, it will point to the first word. char *ptr = strtok (str, delim);

I currently have a declaration with assignment that looks something like this:

static const char *desc[3] = { "apple", "banana", "orange" };

This is not "assignment". This is initialisation.

I can't seem to figure out how to do the assignment.

Arrays are not assignable. You cannot assign to an array.

If you want to modify elements of an array after it has been initialised, you either need to iterate each element and assign them one by one:

const char *arr[] = {"apple", "banana", "orange"};
static_assert(std::size(arr) == std::size(desc));
std::copy_n(arr, std::size(arr), desc);

Or you can wrap the array into a class, in which case an assignment operator will be generated for you. There is a standard template for such array wrapper std::array:

static std::array<const char*, 3> desc;
// later
desc = {"apple", "banana", "orange"};

What Is A String In C - How to play with strings in C, 07 String Split · 08 Array Of C String. 1/8 What Is A String In C. Next: Safety First. A string in C (also known as C string) is an array of characters, followed by a NULL Yes, a C string initialized through a character pointer cannot be modified​. Just like any other array, you can put the array size inside the [] of the declaration: The first subscript of the array i.e 3 denotes the number of strings in the array and the second subscript denotes the maximum length of the string. Recall the that in C, each character occupies 1 byte of data, so when the compiler sees the above statement it allocates 30 bytes (3*10) of memory.

Max Vollmer give some excellent suggestions, although using new and raw pointers is discouraged in "modern C++" (post C++11). See [1] (Sutter is a member of the C++ standard committee, so he knows his thing.

So if you are going for "true C++ way" to have an array of strings, than you should go for:

std::vector<std::string> dest_a;
dest_a.push_back("apple");
dest_a.push_back("banana");
// or
std::vector<std::string> dest_b(3);
dest_b[0] = "orange";
dest_b[1] = "pear";
dest_b[2] = "plumb";

If you need the raw pointers, I think I'd go for the old C strcpy functions.


Although, you might just be looking for this.

  static const char *ptr[2];
  ptr[0] = "orange";
  ptr[1] = "pear";

[1] https://herbsutter.com/elements-of-modern-c-style/

C Programming/Arrays and strings, Arrays in C act to store related data under a single variable name with an index, also known as a For now, we will consider just their declaration and their use. Here, string array and arrays of strings both are same term. For Example, if you want to store the name of students of a class then you can use the arrays of strings. Arrays of strings can be one dimensional or multidimensional. Declaring the string array: There are two ways to declare the arrays of strings as follows. Declaration without size

your declaration is wrong because when you write char [3] it will make your character array containing 3 characters, not an array with 3 different unlimited characters.

Array of Pointers to Strings in C, Let's see how we can declare and initialize an array of pointers to strings. assign a new string to a 2-D array of characters using assignment operator ( = ). Also, to assign the address of an array to a pointer, we do not use the address-of (&) operator since the name of an array (like label) behaves like the address of that array in this context. That's also why you don't use an ampersand when you pass a string variable to scanf() , e.g,

Your first attempt counts as assignment (which you can’t do with an array), not as initialization.

This definition should work:

const char* foo::desc[] = { "apple", "banana", "orange" };

for a declaration looking like this:

class foo {
    static const char* desc[];
};

Declaring and Initializing a string array in different lines , I'm going to assume you want to re-assign array elements in a block There are more C-like features too, as using something like int a[] Often you may want to declare your words as string and use split() to initialize array. Converting a String to a Number ; Declare and initialize a String. A string is a simple array with char as a data type. 'C' language does not directly support string as a data type. Hence, to display a string in 'C', you need to make use of a character array.

C Arrays Basics Explained with 13 Examples, So to store a string, we need an array of characters followed by a null byte. Now we know how to declare and initialize an array. int j = arr[5]; // Accessing the 6th element of integer array arr and assigning its value to integer 'j'. To get the length of an array we have to divide by the size of an item. String arrays. We begin with string arrays. Square brackets are used for all arrays. The syntax is simple and easy to remember (with practice). Version 1: This code creates a string array of 3 elements, and then assign strings to the array indexes (starting at 0). Version 2: This string array is created with an array initializer expression. It

Arrays and Strings, In C, strings are just character arrays which end with a null character. However in C++ Strings can be declared and initialized as follows. Declaration: string str;. In C/C++, a string is a 1-D array of characters and an array of string in C is a 2D array of characters. This comes quite handy in C++. There are 3 ways in which an Array of Strings in C or C++ can be created. Using Pointers(Both C and C++): We actually create string literals by creating an array of pointers.

Strings in C, Declaration of strings: Declaring a string is as simple as declaring a one dimensional array. Below is the basic syntax for declaring a string. char str_name​[size];. In  Assigning Values to an Array. You can assign values to individual array elements, by using the index number, like − double[] balance = new double[10]; balance[0] = 4500.0; You can assign values to the array at the time of declaration, as shown − double[] balance = { 2340.0, 4523.69, 3421.0}; You can also create and initialize an array, as

Comments
  • Do you have to use a const char? if so it could only be initialized at creation.
  • There would be nothing wrong with const char *desc[3] = { "apple", "banana", "orange" };
  • @DavidC.Rankin Yes, there is. I want to have an if statement which assigns desc with different values.
  • You are not prevented from doing that. const char *desc[3] declares an array of 3 pointers to const char*. If you initialize with const char *desc[3] = { "apple", "banana", "orange" }; there is nothing that then prevents you from making a later assignment to one of the pointers, if (somecondition) desc[2] = "grapes"; (now you cannot modify the string-literals pointed to by each of the pointers, but you can change what the pointers point to)
  • I wish to change all of them or none of them, so it doesn't make sense to make initial values if they'll all be changed, and it would be annoying to have statements for changing each element.
  • In my specific case, the possible values that I assign are always going to be the exact same size in memory. Is there a way to optimize the code if I know this?
  • @AaronFranke Optimizations always depend on a multitude of factors, so there is no real catch all. Sometimes the question also is: Do you really need a particular optimization? My general approach is to first implement readable and understandable code, and then profile it for performance and resource usage and optimize specific parts of the code that have been identified as critical. I really reccommend you just use std::vector<std::string> or std::array<std::string, 3>. That being said, the last solution in Emil Vatai's answer might be the "optimization" you are looking for.
  • Typo: initialisation.??
  • @DavidC.Rankin Not a typo.
  • Err..... okay, different side of the pond I guess :) (west side - "initialization")
  • "Arrays are not assignable.You cannot assign to an array." Why?
  • @AaronFranke because the rules of the language say so.
  • I don't see a char [3] in the question.
  • What if desc isn't in a class?