CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    May 2002
    Location
    Mumbai
    Posts
    197

    Post How to assign null value to a char array

    Hi
    I have a character array, say
    char name[10] ;
    I want to assign null value to it.
    Can I do something like
    name = null ;
    or
    strcpy(name,null) ;

    Help is needed.

    Regards
    SunnyPriya Joshi

  2. #2
    Join Date
    Apr 2002
    Location
    Russia, Saint-Petersburg
    Posts
    5
    memset(name, 0, sizeof(char) * 10)

  3. #3
    Join Date
    Oct 2001
    Location
    Dublin, Eire
    Posts
    880
    2 possibilities:

    If you want to use it as a string, then, set the fisrt character to null should be the best:
    name[0] = '\0';

    If you want to put all the elements of your array to nul, then use memset as WildCat says.
    Elrond
    A chess genius is a human being who focuses vast, little-understood mental gifts and labors on an ultimately trivial human enterprise.
    -- George Steiner

  4. #4
    Join Date
    May 2000
    Location
    Washington DC, USA
    Posts
    715
    Null is a pointer value. So you could say

    char *pszMyString = Null;

    and thus set a pointer to NULL but not set a string to NULL.

    Now the termination character for a string is also called the NULL terminator but it is something different than NULL which as I said is a pointer value. The NULL termination character for a string is the ascii value absolute Zero... [ 0 ]. or '\0'.

    One can set the first character of a character array to this value which effectively ends the string at element Zero.. Like this..

    char szMyString[5] = "abcd"

    szMyString[0] = '\0';

    Now this doesn't exactly overwrite the entire array. Anybody trying to access this array as a string will just think it ends at element 0. The contents of the szMyString array looks like this..
    0 123 4
    '\0bcd\0'

    To overwrite the entire array with the Null terminator use memset as has already been discussed..

    memset ( (void *) &szMystring, '\0', sizeof(szMystring));

    this will make the array contents
    0 1 2 3 4
    '\0\0\0\0\0'

    get it?

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