CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1
    Join Date
    Feb 2011
    Location
    Cosenza,Italy
    Posts
    62

    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?

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    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.

  3. #3
    Join Date
    Feb 2011
    Location
    Cosenza,Italy
    Posts
    62

    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)?

  4. #4
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Char Array problem

    Replacing an element should work fine.

  5. #5
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,637

    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.

  6. #6
    Join Date
    Feb 2011
    Location
    Cosenza,Italy
    Posts
    62

    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

  7. #7
    Join Date
    Jun 2009
    Location
    oklahoma
    Posts
    199

    Re: Char Array problem

    Did you forget the semicolon?
    You never told us what error message you were getting

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured