I am trying to do the following. I have 2 character arrays and I want to append characters from the second to the first. However, I have am really confused about pointers and arrays.
First of all, I am declaring my array like this
int length=10;
char *firstArray=new char[length];
When I do that, Visual Studio 2008, initializes the pointer's values with unreadable garbage.When I am assigning a value to firstArray like that
firstArray[0]="A";
I get an error that I can't convert a char* array to char. I guess this is because by using "" the compiler creates a char* array with A and appends the'\n' character, is that right?
When I am writing
firstArray[0]='A';
The first element indeed becomes A, but the rest is garbage. I thought that this was because this was an assignement to some address, instead of assigning a value to the pointer. So, I thought about writing
*firstArray[0]='A';
but I get an error "illegal indirection".
So, how can I get rid of all the garbage and then be able to add new values to the array? I think that this would be easy by using std::string, but I am doing an exercise whose main point is char arrays.
Hey, thank you! This cleared up my garbage. But why is the pointer initialized with garbage in the first place? Especially, why does the compiler initialize the pointer with an array of 16 characters while I said I want a char* array of length 4?
char *firstArray=newchar[length]; Declares a pointer ( firstArray ), allocates an array of characters, and makes the pointer point to that array
"A" Has type constchar*, it's an array containing 'A' and '\0' ( the string terminator ) firstArray[0] returns the first element of your array ( which has type char ) firstArray[0]="A"; is illegal because you are trying to assign a pointer ( "A" ) to a character ( firstArray[0] ) firstArray[0]='A'; assigns 'A' to the first character of your array but leaves the others unchanged ( thus with garbage values )
If you try to print firstArray you'll get your 'A' and some garbage until the next 0-byte in memory, this is because the function you are using to print it is expecting a nul-terminated string ( Your isn't )
If you assigned the second character to nul, it would print just 'A'
eg:
1 2
firstArray[0]='A';
firstArray[1] = '\0';
*x dereferences the pointer x, in your case x is firstArray[0] which is not a pointer ( but a char )
You can manipulate C-style strings using functions from <cstring>
dummy is filled with the appropriate value, with garbage appended. Before that line, everything is fine.
An additional problem is that later in the code I am using strlen to identify the length of dummy and strlen reads all the garbage and outputs more characters than I want.
I don't know why, but this line compiles. I am running Visual Studio 2008. Furthermore, in order not to have garbage, do I only have to add '\n' at the end? In this code