-
Char Array problem
Hello everybody! I've a problem with a char array: why i can't give a char in a position of the array? ex:
char array [7]; //declaration of a char array 7 elements
for (int i=0;i<7;i++)
array[i]='x';
array [5]='y'--->error
How could I insert the char 'y' in the 5th position of the array?
-
Re: Char Array problem
You can assign any value of the correct type to any valid index of an array. You cannot insert an element without overwriting another one though----the maximum size of the array cannot change.
The closest to an insertion you can do is first allocating the array larger than you need, and then shifting all elements at indexes >= the insertion point over one index before overwriting the index.
-
Re: Char Array problem
So I can't replace an element of an array? My aim is to create an array that represents the life of one player (for example a list of hearts). When the player lose one life, the content of the array must change and one heart should be replaced by an empty char..so i can't do:
array[pos]=' ';
(to delete the precedent heart on the array)?
-
Re: Char Array problem
Replacing an element should work fine.
-
Re: Char Array problem
I don't see anything wrong with the code you posted. Are you talking about a compile error or a runtime error? Post real code.
-
Re: Char Array problem
i solved my problem in an easy way..I print the array with the life of player1 - i (i is the number of times the player lose one life).
Anyway, i tried to make a little program with replacement of some elements of the array and it works, i don't know why it shows me problems in the previous program. Thank you very much and sorry for my bad English :)
-
Re: Char Array problem
Did you forget the semicolon?
You never told us what error message you were getting