Can't print char!

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • JS

    #1

    Can't print char!

    I would like to print char 'd':

    main(){

    char g[4];
    g[0] = 'a';
    g[1] = 'b';
    g[2] = 'c';
    g[3] = 'd';

    char *pp;
    pp = &g[3];

    printf("%s", *pp);
    getchar();

    }

    But its only possible to get d printed if I change:

    printf("%s", *pp);

    into:

    printf("%s", pp);





    But when I do the same thing with an int I have to use the first version of
    the printf:

    main(){

    int j = 50;

    int *q;

    q = &j;

    printf("%d", *q);
    getchar();

    }

    Why is it the other way around with integers??

    JS


  • simon danner

    #2
    Re: Can't print char!

    with %s in printf you print a string, represented by a pointer of the
    first char. it is just luck that it prints out one char, if the
    following address would have a value of nonzero, it would print out
    garbage (-> a string is null terminated).
    to print an integer, you need to dereference the pointer, because printf
    needs the value, not the address.

    simon

    Comment

    • Walter Roberson

      #3
      Re: Can't print char!

      In article <d1a9gq$r4o$1@n ews.net.uni-c.dk>, JS <sfsdfs@asdas.c om> wrote:
      :I would like to print char 'd':

      : char g[4];
      : g[3] = 'd';

      : pp = &g[3];

      : printf("%s", *pp);

      *pp is a single character, not a string. You should be using a %c
      format to print it -- otherwise the -value- that 'd' corresponds to
      will be used as a pointer to the string to print, with nasty results.

      You also are making a mistake by using a %s format to deal with
      a character array that is not NULL terminated.
      printf("%s", pp); is going to run off the end of the string
      which is a Bad Thing.
      --
      Feep if you love VT-52's.

      Comment

      • Christopher Benson-Manica

        #4
        Re: Can't print char!

        JS <sfsdfs@asdas.c om> spoke thus:
        [color=blue]
        > main(){[/color]

        Invalid in C99. main() returns int.
        [color=blue]
        > char g[4];
        > g[0] = 'a';
        > g[1] = 'b';
        > g[2] = 'c';
        > g[3] = 'd';[/color]
        [color=blue]
        > char *pp;
        > pp = &g[3];[/color]

        pp points to the last element of g, which is a character.
        [color=blue]
        > printf("%s", *pp);[/color]

        You probably meant

        printf( "%c\n", *pp );
        [color=blue]
        > getchar();[/color]

        Omitting the return statement of main() is not permitted in C89.
        [color=blue]
        > printf("%s", pp);[/color]


        Very bad. The %s format specifier requires a null-terminated
        array of characters, which pp is not. Undefined behavior results.

        [color=blue]
        > Why is it the other way around with integers??[/color]

        Because you used the incorrect format specifier, as above.

        --
        Christopher Benson-Manica | I *should* know what I'm talking about - if I
        ataru(at)cybers pace.org | don't, I need to know. Flames welcome.

        Comment

        • Eric Sosman

          #5
          Re: Can't print char!



          JS wrote:[color=blue]
          > I would like to print char 'd':
          >
          > main(){
          >
          > char g[4];
          > g[0] = 'a';
          > g[1] = 'b';
          > g[2] = 'c';
          > g[3] = 'd';
          >
          > char *pp;
          > pp = &g[3];
          >
          > printf("%s", *pp);[/color]

          The argument corresponding to "%s" must be a pointer
          to character, a `char*'. However, `*pp' is not a pointer:
          it is the character value that `pp' points to.

          Furthermore, "%s" can't use a pointer to just any
          character, but requires a pointer to the character at the
          start of a string. A "string" is an array containing
          some number of "payload" characters (perhaps zero of them)
          followed by a character with the value zero, often written
          as '\0'. Since the character sequence beginning with g[3]
          doesn't fit this description (the one-character payload
          is present, but there's no terminating '\0'), the character
          pointer `pp' cannot be used where a string is expected.
          That is, the "correction " to `printf("%s", pp)' would not
          be a correction at all, just a different error.

          What you probably want is one of

          printf("%c", *pp);
          printf("%.1s", pp);

          .... and I'll refer you to your C textbook to figure out
          what these mean.

          --
          Eric.Sosman@sun .com

          Comment

          • Keith Thompson

            #6
            Re: Can't print char!

            roberson@ibd.nr c-cnrc.gc.ca (Walter Roberson) writes:
            [...][color=blue]
            > You also are making a mistake by using a %s format to deal with
            > a character array that is not NULL terminated.
            > printf("%s", pp); is going to run off the end of the string
            > which is a Bad Thing.[/color]

            Quibble: NUL terminated, not NULL terminated. NULL is a macro that
            expands to a null pointer constant; NUL is the common name for the
            null character '\0'.

            --
            Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
            San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
            We must do something. This is something. Therefore, we must do this.

            Comment

            • Keith Thompson

              #7
              Re: Can't print char!

              Christopher Benson-Manica <ataru@nospam.c yberspace.org> writes:[color=blue]
              > JS <sfsdfs@asdas.c om> spoke thus:[/color]
              [...][color=blue][color=green]
              >> char g[4];
              >> g[0] = 'a';
              >> g[1] = 'b';
              >> g[2] = 'c';
              >> g[3] = 'd';[/color]
              >[color=green]
              >> char *pp;
              >> pp = &g[3];[/color][/color]
              [...][color=blue][color=green]
              >> printf("%s", pp);[/color]
              >
              >
              > Very bad. The %s format specifier requires a null-terminated
              > array of characters, which pp is not. Undefined behavior results.[/color]

              A small quibble: %s requires *a pointer to the first character of* a
              null-terminated array of characters. (If you give it an array name,
              the name decays to a pointer to its first element.)

              If not yet enlightened, see section 6 of the C FAQ.

              --
              Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
              San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
              We must do something. This is something. Therefore, we must do this.

              Comment

              • Martin Ambuhl

                #8
                Re: Can't print char!

                JS wrote:[color=blue]
                > I would like to print char 'd':
                >
                > main(){
                >
                > char g[4];
                > g[0] = 'a';
                > g[1] = 'b';
                > g[2] = 'c';
                > g[3] = 'd';
                >
                > char *pp;
                > pp = &g[3];
                >
                > printf("%s", *pp);[/color]
                ^^
                wrong specifier. %c is for characters[color=blue]
                > getchar();
                >
                > }
                >
                > But its only possible to get d printed if I change:
                > printf("%s", *pp);
                > into:
                > printf("%s", pp);[/color]
                *pp is a char, pp is pointer to char, and it is in your code not
                necessarily a pointer to a string, since you have no '\0' following
                {'a','b','c','d '}. See the code below for an initialization with such a
                '\0'.
                [color=blue]
                > But when I do the same thing with an int I have to use the first version of
                > the printf:
                >
                > main(){
                > int j = 50;
                > int *q;
                > q = &j;
                > printf("%d", *q);
                > getchar();
                > }[/color]
                [color=blue]
                > Why is it the other way around with integers??[/color]


                #include <stdio.h>

                void first_main(void )
                {
                char g[] = "abcd";
                char *pp = &g[3];
                printf("g is at %p; pp = &g[3] is %p\n", (void *) g, (void *) pp);
                printf("This prints the string containing "
                "{'a','b','c',' d',0}: \"%s\"\n", g);
                printf("So does this: \"%s\"\n\n", g);
                printf("This prints the string containing {'d',0}: \"%s\"\n", pp);
                printf("This prints the character 'd': '%c'\n\n", *pp);
                }


                void second_main(voi d)
                {
                int j = 50;
                int *q = &j;
                printf("j is at %p; q = &j is %p\n", (void *) &j, (void *) q);
                printf("This prints the int j: %d\n", j);
                printf("This prints the int *(&j): %d\n", *(&j));
                printf("This prints the int *(q = (&j)): %d\n\n", *q);
                }

                int main(void)
                {
                printf("[output]\n");
                first_main();
                second_main();
                return 0;
                }



                [output]
                g is at eff90; pp = &g[3] is eff93
                This prints the string containing {'a','b','c','d ',0}: "abcd"
                So does this: "abcd"

                This prints the string containing {'d',0}: "d"
                This prints the character 'd': 'd'

                j is at effa4; q = &j is effa4
                This prints the int j: 50
                This prints the int *(&j): 50
                This prints the int *(q = (&j)): 50

                Comment

                • Walter Roberson

                  #9
                  Re: Can't print char!

                  In article <lnmzt3b52z.fsf @nuthaus.mib.or g>,
                  Keith Thompson <kst-u@mib.org> wrote:
                  :roberson@ibd.n rc-cnrc.gc.ca (Walter Roberson) writes:
                  :> a character array that is not NULL terminated.

                  :Quibble: NUL terminated, not NULL terminated. NULL is a macro that
                  :expands to a null pointer constant; NUL is the common name for the
                  :null character '\0'.



                  # The entries are in ANSI X3.4 order.
                  #
                  0x00 0x0000 # NULL
                  --
                  Look out, there are llamas!

                  Comment

                  • Joe Wright

                    #10
                    Re: Can't print char!

                    JS wrote:[color=blue]
                    > I would like to print char 'd':
                    >
                    > main(){
                    >
                    > char g[4];
                    > g[0] = 'a';
                    > g[1] = 'b';
                    > g[2] = 'c';
                    > g[3] = 'd';
                    >
                    > char *pp;
                    > pp = &g[3];
                    >
                    > printf("%s", *pp);
                    > getchar();
                    >
                    > }
                    >
                    > But its only possible to get d printed if I change:
                    >
                    > printf("%s", *pp);
                    >
                    > into:
                    >
                    > printf("%s", pp);
                    >
                    >
                    >
                    >
                    >
                    > But when I do the same thing with an int I have to use the first version of
                    > the printf:
                    >
                    > main(){
                    >
                    > int j = 50;
                    >
                    > int *q;
                    >
                    > q = &j;
                    >
                    > printf("%d", *q);
                    > getchar();
                    >
                    > }
                    >
                    > Why is it the other way around with integers??
                    >
                    > JS
                    >
                    >[/color]

                    Study this..

                    /* I would like to print char 'd': */
                    #include <stdio.h>
                    int main()
                    {
                    char g[4];
                    g[0] = 'a';
                    g[1] = 'b';
                    g[2] = 'c';
                    g[3] = 'd';

                    char *pp;
                    pp = &g[3];

                    printf("%c", *pp);
                    return 0;
                    }


                    --
                    Joe Wright mailto:joewwrig ht@comcast.net
                    "Everything should be made as simple as possible, but not simpler."
                    --- Albert Einstein ---

                    Comment

                    • CBFalconer

                      #11
                      Re: Can't print char!

                      JS wrote:[color=blue]
                      >
                      > I would like to print char 'd':
                      >
                      > main(){[/color]

                      int main(void) {
                      [color=blue]
                      >
                      > char g[4];[/color]

                      char g[5];
                      [color=blue]
                      > g[0] = 'a';
                      > g[1] = 'b';
                      > g[2] = 'c';
                      > g[3] = 'd';[/color]

                      g[4] = '\0';

                      or replace the whole mess with:

                      char g[] = "abcd"; /* which will append the '\0' for you */
                      [color=blue]
                      >
                      > char *pp;
                      > pp = &g[3];
                      >
                      > printf("%s", *pp);[/color]

                      printf("%c", *pp); /* *pp is a char, not a string */
                      fflush(stdout);
                      [color=blue]
                      > getchar();[/color]

                      Pointless, except possibly to prevent an IDE window exiting.
                      Simpler to just run it from a command line window. You are still
                      missing:

                      return 0;[color=blue]
                      > }
                      >
                      > But its only possible to get d printed if I change:
                      >
                      > printf("%s", *pp);
                      > into:
                      > printf("%s", pp);[/color]

                      without the g[4] = '\0' here you are running into undefined
                      behaviour. Strings require a terminating '\0'.
                      [color=blue]
                      >
                      > But when I do the same thing with an int I have to use the first version of
                      > the printf:
                      >[/color]
                      .... snip ...[color=blue]
                      >
                      > Why is it the other way around with integers??[/color]

                      Because C passes things by value, except arrays. Arrays are passed
                      by a pointer to the first member. A C string is an array of char,
                      with a terminal '\0' appended.

                      --
                      "If you want to post a followup via groups.google.c om, don't use
                      the broken "Reply" link at the bottom of the article. Click on
                      "show options" at the top of the article, then click on the
                      "Reply" at the bottom of the article headers." - Keith Thompson


                      Comment

                      • Keith Thompson

                        #12
                        Re: Can't print char!

                        roberson@ibd.nr c-cnrc.gc.ca (Walter Roberson) writes:[color=blue]
                        > In article <lnmzt3b52z.fsf @nuthaus.mib.or g>,
                        > Keith Thompson <kst-u@mib.org> wrote:
                        > :roberson@ibd.n rc-cnrc.gc.ca (Walter Roberson) writes:
                        > :> a character array that is not NULL terminated.
                        >
                        > :Quibble: NUL terminated, not NULL terminated. NULL is a macro that
                        > :expands to a null pointer constant; NUL is the common name for the
                        > :null character '\0'.
                        >
                        > http://www.unicode.org/Public/MAPPIN...CII-QUOTES.TXT
                        >
                        > # The entries are in ANSI X3.4 order.
                        > #
                        > 0x00 0x0000 # NULL[/color]

                        Ok, but (1) NUL is an abbreviation for NULL, and is a more common name
                        for the character, and (2) NULL has a specific meaning in C, so using
                        the term for anything else *in comp.lang.c* should be avoided.

                        --
                        Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
                        San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
                        We must do something. This is something. Therefore, we must do this.

                        Comment

                        • osmium

                          #13
                          Re: Can't print char!

                          "Walter Roberson" writes:
                          [color=blue]
                          > In article <lnmzt3b52z.fsf @nuthaus.mib.or g>,
                          > Keith Thompson <kst-u@mib.org> wrote:
                          > :roberson@ibd.n rc-cnrc.gc.ca (Walter Roberson) writes:
                          > :> a character array that is not NULL terminated.
                          >
                          > :Quibble: NUL terminated, not NULL terminated. NULL is a macro that
                          > :expands to a null pointer constant; NUL is the common name for the
                          > :null character '\0'.
                          >
                          > http://www.unicode.org/Public/MAPPIN...CII-QUOTES.TXT
                          >
                          > # The entries are in ANSI X3.4 order.
                          > #
                          > 0x00 0x0000 # NULL[/color]

                          I really dislike threads such as this, on the various meanings of nul, null,
                          NUL and NULL. But your reference is specious, the *official;* ASCII chart
                          lists the character with a value of binary zero as NUL. Not NULL, as your
                          link above says. The control codes were specified with a maximum of three
                          upper case letters. You can recognize the official document by it's red,
                          white and blue cover.


                          Comment

                          • pete

                            #14
                            Re: Can't print char!

                            osmium wrote:
                            [color=blue]
                            > I really dislike threads such as this,
                            > on the various meanings of nul, null, NUL and NULL.[/color]

                            I don't.

                            --
                            pete

                            Comment

                            • Walter Roberson

                              #15
                              Re: Can't print char!

                              In article <39teq9F66t1q7U 1@individual.ne t>,
                              osmium <r124c4u102@com cast.net> wrote:

                              :the *official;* ASCII chart

                              :You can recognize the official document by it's red,
                              :white and blue cover.

                              Which edition? 1968? 1974? 1983?

                              I visited the ANSI online store, but the official X3.4 document is no
                              longer orderable; X3.48 is the closets they have.
                              --
                              Studies show that the average reader ignores 106% of all statistics
                              they see in .signatures.

                              Comment

                              Working...