Results 1 to 2 of 2

Thread: Why get these output

  1. #1
    Join Date
    Feb 2012
    Beans
    93

    Why get these output

    Here is my code block

    Code:
    	char * passwd = "123456";
            printf("passwd = %d\n",passwd);
    	printf("passwd = %s\n",passwd);
    	for (int k = 0; k < 19; k++)
    	{
    	    printf("%c", passwd);
    	}
    and got these results, very weird.

    Code:
    passwd = 3068087
    passwd = 123456
    贩贩贩贩贩贩贩贩贩
    Any help is welcome. Thanks.
    Last edited by pellyhawk; November 19th, 2012 at 03:42 PM.

  2. #2

    Re: Why get these output

    You are telling printf to display values of different types, but you are not in fact converting between those types.

    Code:
    	char * passwd = "123456";
            printf("passwd = %d\n",passwd);
    printf interprets the second argument, which is a pointer-to-char, as an int and displays it as such. The result is gibberish -- might not even correspond to an actual memory location, what with alignment and other concerns. If you ever do want to display the value of a pointer, use %p and cast it to (void *), like `printf("%p", (void *)passwd);`
    Code:
    	printf("passwd = %s\n",passwd);
    This acts as you would expect.

    Code:
    	for (int k = 0; k < 19; k++)
    	{
    	    printf("%c", passwd);
    	}
    Here you're again re-interpreting a pointer-to-char, but this time as a char. You probably wanted

    Code:
    for (int k = 0; k < 6; k++) {
        printf("%c", passwd[k]);
    }
    Notice I also changed 19 to 6 so that you won't read off the end of the 6-character string. In the general case, you could just keep printing characters until the null terminator:
    Code:
     for (int k = 0; passwd[k]; k++) {
        printf("%c", passwd[k]);
    }
    This will work for any C string no matter what size.

Bookmarks

Posting Permissions

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