Thread: Peculiar Problem with char variable in C Language

  1. #1
    Unregistered
    Guest

    Angry Peculiar Problem with char variable in C Language

    Reading a input stream assigning 1 thru 6 character to a str1 variable

    using memmove function like this

    buffer="abcdefgh";
    memmove(str1,buffer,6);

    somtimes what happens is i get str1 value more than 6

    for example :-
    According to this

    memmove(str1,buffer,6);

    I should get str1="abcdef" but in sometime i get str1=""abcdefgh"

    Could you please help me out of this,

    Thanks,
    Khan

  2. #2
    Registered User
    Join Date
    Sep 2001
    Posts
    412
    Your str1, which I assume you allocate only 6 bytes for? will indeed have "abcdef" -- the problem is, when you use functions that expect strings, you don't have the required null terminator to tell the function where the string ends. You need to make str1 one byte larger than the max val, and make the last char 0.

    So, do this:

    char str1[7];
    char * buffer = "abcdefgh"
    memmove(str1,buffer,6*sizeof(char));
    str1[6] = '\0';

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 05:42 PM
  2. problem in char variable
    By hitesh_best in forum C Programming
    Replies: 2
    Last Post: 08-11-2007, 12:01 AM
  3. Beginner question
    By Tride in forum C Programming
    Replies: 30
    Last Post: 05-24-2003, 08:36 AM
  4. problem printf after inserting single list from file
    By jetfreggel in forum C Programming
    Replies: 3
    Last Post: 04-15-2003, 02:30 PM