Is there a way to initialize arrays with mixed chars and "strings" - c++

I would want to initialize char array during compilation time with least amount of manual work.
Is there a working shorthand format for this
char arr[5] = {0x4, 'a', 's', 'd' 'c'};
such as
char arr[5] = {0x4, "asdc"};

You could integrate the char int the string with escape sequences:
char arr[6] = { "\x04asdc"};
edit: corrected the wrog length of the array.

No that's not possible. But you could do
char arr[] = "\04asdc";
The problem with this is that is would not be exactly like the original array you show, since it would include the string terminator and therefore have six elements.

Related

Could I get help finding the output of this function? (C++)

What would the output of this code be, with all of the appropriate includes?
I understand what everything does up until *(x+4) = x[n];, and from there I got a little lost.
int main(){
int n;
char y[10] = "tasked";
char *x = y;
n = strlen (x);
*(x+4) = x[n];
x++;
printf ("%s",x);
}
Edit: I didn't understand what *(x+4) = x[n]; did to the string, thank you all!
The output of the program will be
ask
After this declaration
char y[10] = "tasked";
the array y is initialized the following way
char y[10] = { 't', 'a', 's', 'k', 'e', 'd', '\0', '\0', '\0', '\0' };
That is all characters that do not have a corresponding initializing character from the string literal are zero-initialized.
After this statement
n = strlen (x);
n is equal to 6.
So this statement
*(x+4) = x[n];
do the following. It substitutes the character 'e' (at index 4) for the character '\0' (at index 6);
So after that the array has the following content
{ 't', 'a', 's', 'k', '\0', 'd', '\0', '\0', '\0', '\0' }
Then the pointer advances one position and points to the second character of the array (with index 1) that is to the character 'a'.
So starting from this character 'a' until the terminating zero is encountered the characters 'a', 's', and 'k' are outputted.
Open this site : and paste your code, then add the following before the "int main()" line:
#include <string.h>
This will allow you to use the "strlen" function.
Click the green "Run" button to get the output.
Then follow #Vlad from Moscow's answer and you will be informed.

C Char Array Creation Differences

In C I've noticed that there are a few ways to declare a char array. What's the difference between:
char arr[10] = "abcdefghij";
char* arr2[10] = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"};
gcc says I need the star after char in 2 and not in 1.
when printing 1 I can use printf("%s\n", arr); and it prints abcdefghij#
when printing 2 I have to use a for loop
Why are they different?
Because 1 is a char array, while the second is an array of arrays as "a" is in fact an array of 2 chars 'a' and '\0'
arr is a vector of char of 10 elements, and arr2 is a vector of chars pointers of 10 elements
char arr2[10] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
It is equal arr.
In the first one you are just declaring a string, but in the second one you are creating 10 pointers to 10 strings. As an example
char* arr2_0 = "a" ;
char* arr2_1 = "b" ;
char* arr2_2 = "c" ;
char* arr2_3 = "d" ;
char* arr2_4 = "e" ;
char* arr2_5 = "f" ;
char* arr2_6 = "g" ;
char* arr2_7 = "h" ;
char* arr2_8 = "i" ;
char* arr2_9 = "j" ;
To understand this behavior, you have to know the difference between strings and chars. The former are created with " and can contain several chars, while the latter are created with ' and represent only one char. Since you used " in your array initialisation, you created an array of strings, not chars. Now strings are represented via pointers to chars. Therefore the compiler wanted you to create an array of pointers to chars, instead of an array of chars.

console outputs smiley face

I have this code:
#include "stdafx.h"
#include <iostream>
typedef struct{
int s1;
int s2;
char c1;
char* arr;
}inner_struc;
int _tmain(int argc, _TCHAR* argv[])
{
inner_struc myinner_struct;
myinner_struct.s1 = myinner_struct.s2 = 3;
myinner_struct.c1 = 'D';
char arr[3] = {1,2,3};
myinner_struct.arr = arr;
std::cout << "first array element: " << myinner_struct.arr[1] << std::endl;
return 0;
}
I wonder why am I getting a smiley face instead of the first array element! what am I doing wrong here? It compiles and runs fine however the output is
first array element: "smiley face"
What does this means?
I am using Visual Studio 2010. Thanks
You are outputing the second element in this array:
char arr[3] = {1,2,3};
You have assigned it the values 1 2 and 3, but the variable is of type char, so it is being interpreted as ascii. If you look up what character has a value of 2 on an ascii chart, you will see that it is a smily face. So it is indeed doing what you asked it to do.
http://mathbits.com/MathBits/CompSci/Introduction/ASCIIch.jpg
What are you expecting the output to be? if you wanted it to be a number, then you will have to add the character representation of that number into the array. ie in stead of 1, 2 or 3 use '1', '2', and '3'
As far, as I can see, you are trying to output the first array element. But instead, you are printing the second one (the arrays are indexed starting from 0, not 1). The second element is 2. Now, please, take a look at this table, as you can see: the number 2 is a smiley face. The problem is that you are outputing a character with code 2, not '2'. In order to output a deuce, make your array look like this:
char arr[3] = {'1','2','3'};
inner_struct.arr is declared as char *, which means it holds an array of characters (bytes). Do you want an array to hold the numbers 1, 2, 3? If so, use int. If you want letters, initialize the array with:
char arr[3] = { 'a', 'b', 'c' };
KC

Char array allocation

In C++, if I do:
char myArray[] = {'1','2','3','4','5','6','7','8','9'};
Does that allocate 10 spaces? The last element being '/0'?
What about:
char myArray[9] = {'1','2','3','4','5','6','7','8','9'};
Did I allocate only 9 spaces in this case? Is this bad?
And, finally, what happens when I do:
char myArray[10] = {'1','2','3','4','5','6','7','8','9','/0'};
char myArray[] = {'1','2','3','4','5','6','7','8','9'};
Does that allocate 10 spaces? The last element being '/0'?
No. 9.
char myArray[9] = {'1','2','3','4','5','6','7','8','9'};
Did I allocate only 9 spaces in this case?
Yes.
Is this bad?
No.
and finally what happens when I do
char myArray[10] = {'1','2','3','4','5','6','7','8','9','/0'};
Assuming you meant '\0', exactly what it looks like.
There's no magic in any of these cases — you get precisely what you're asking for.
Automatic null-termination is something that comes into play with string literals:
char myArray1[10] = "123456789";
char myArray2[9] = "123456789"; // won't compile - wrong size
char myArray3[] = "123456789"; // still 10 elements - includes null terminator
No, you'll only get the trailing NUL when using a string literal, i.e.:
// Array of 10 bytes
char myArray[] = "123456789";
// same as:
char myArray[] = {'1','2','3','4','5','6','7','8','9','\0'};
char myArray[] = {'1','2','3','4','5','6','7','8','9'};
This only allocates 9 elements.
char myArray[9] = {'1','2','3','4','5','6','7','8','9'};
Yes, this line also allocates 9 elements.
char myArray[10] = {'1','2','3','4','5','6','7','8','9','/0'};
The last one should be '\0' instead of '/0'.
What you are thinking about should be
char myArray[] = "123456789";
which allocates 10 characters (1 for the trailing '\0' at the end of the string literal)
char arrays don't behave differently than any other arrays when you use list-initialization. Would you expect
int x[] = {1,2};
to magically append a 0 as the last element and make x have 3 elements?
In case you provide fewer elements, then the last ones are value-initialized, so
char myArray[10] = {'1','2','3','4','5','6','7','8','9'};
would be null-terminated, but
char myArray[9] = {'1','2','3','4','5','6','7','8','9'};
isn't.

Length of String

String manipulation problem
http://www.ideone.com/qyTkL
In the above program (given in the book C++ Primer, Third Edition By Stanley B. Lippman, Josée Lajoie Exercise 3.14) the length of the Character pointer taken is len+1
char *pc2 = new char[ len + 1];
http://www.ideone.com/pGa6c
However, in this program the length of the Character pointer i have taken is len
char *pc2 = new char[ len ];
Why is there the need to take the length of new string as 1 greater when we get the same result. Please Explain.
Mind it the Programs i have shown here are altered slightly. Not exactly the same one as in the book.
To store a string of length n in C, you need n+1 chars. This is because a string in C is simply an array of chars terminated by the null character \0. Thus, the memory that stores the string "hello" looks like
'h' 'e' 'l' 'l' 'o' '\0'
and consists of 6 chars even though the word hello is only 5 letters long.
The inconsistency you're seeing could be a semantic one; some would say that length of the word hello is len = 5, so we need to allocate len+1 chars, while some would say that since hello requires 6 chars we should say its length (as a C string) is len=6.
Note, by the way, that the C way of storing strings is not the only possible one. For example, one could store a string as an integer (giving the string's length) followed by characters. (I believe this is what Pascal does?). If one doesn't use a length field such as this, one needs another way to know when the string stops. The C way is that the string stops whenever a null character is reached.
To get a feel for how this works, you might want to try the following:
char* string = "hello, world!";
printf("%s\n", string);
char* string2 = "hello\0, world!";
printf("%s\n", string2);
(The assignment char* string = "foo"; is just a shorthand way of creating an array with 4 elements, and giving the first the value 'f', the second 'o', the third 'o', and the fourth '\0').
It's a convention that the string is terminated by an extra null character so whoever allocates storage has to allocate len + 1 characters.
It causes problem. But, sometimes, when len isn't aligned, the OS adds some bytes after it, so the problem is hidden.