Can i declare a char and a char array on the same line?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Thread: Can i declare a char and a char array on the same line?

  1. #1
    Join Date
    May 2007
    Posts
    26

    Can i declare a char and a char array on the same line?

    I had a char "chr" and a char array "filename" declared on the same line "char chr, filename[256];", and i was getting a weird segmentation fault when i tried to free an array of char pointers for which i had allocated memory with malloc. It seemed it was only the first pointer i tried to free that was causing the problem, and i eventually found out its address gets changed by 0x10 when i assign "chr" a value via scanf. So i moved the declaration of "chr" to a new line and now the pointer address doesn't change.

    So is this not allowed? It usually seems to work.

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,888

    Re: Can i declare a char and a char array on the same line?

    Should be fine. Odds are, you were either writing or reading out of bounds somewhere.

  3. #3
    Join Date
    May 2001
    Location
    Germany
    Posts
    1,108

    Re: Can i declare a char and a char array on the same line?

    when using scanf, make sure to use '%c' to assign a value, otherwise you might overwright your memory.

  4. #4
    Join Date
    May 2007
    Posts
    26

    Re: Can i declare a char and a char array on the same line?

    This is the scanf line: res = scanf("%1[yn]", &chr); Is there anything wrong there?

  5. #5
    Join Date
    Apr 1999
    Posts
    27,422

    Re: Can i declare a char and a char array on the same line?

    Quote Originally Posted by codingnewbie View Post
    This is the scanf line: res = scanf("%1[yn]", &chr); Is there anything wrong there?
    Where in that format specifier do you say "%c"?

    Regards,

    Paul McKenzie

  6. #6
    Join Date
    May 2007
    Posts
    26

    Re: Can i declare a char and a char array on the same line?

    Ok the problem was that I forgot that with the range specifier you need to have enough room for a terminating null byte as well, so that was overwriting the first byte of the next declaration with a null which is why it worked when I changed its declaration position to the line after the char array.

Posting Permissions

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


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center