0

So i am going to do some string manipulation, but when i try to print out what my pointer is pointing to at time time, i get really weird output.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (){

    size_t n = 10;
    char *mystring = malloc(10);
    int line = 0;
    int tokens = 0;
    char *ptr;

    if(mystring==NULL){
            fprintf(stderr, "No memory\n");
            exit(1);
    }

    while(getline(&mystring, &n, stdin)>0){
             printf("len = %lu, mystring = %s\n", strlen(mystring), mystring);
             printf("let's tokenize this string\n line = %d tokens = %d\n", line, tokens);

            ptr = mystring;

            printf("ptr = %ch\n", ptr[0]);
    }

return 0;
}

This is what my output looks like when i enter hello

len = 6, mystring = hello

let's tokenize this string line = 0 tokens = 0

ptr = hh

what's with the double hh?

  • 4
    I believe you are looking for `%c`. The first H is from the first character in `hello` while the second is from the `h` in your `printf`. – duncan Oct 24 '16 at 17:06
  • i see, i feel like an idiot lol. Thank you for pointing that out to me – Christian Soto Oct 24 '16 at 17:08
  • Happens to the best of us no worries! – duncan Oct 24 '16 at 17:12
  • it would be a good idea for you to NOT malloc() but rather: `char *mystring = NULL; size_t n = 0;` and call free() and reset the values at the end of each pass through the while loop, – user3629249 Oct 25 '16 at 07:46
  • because the function: `getline()` can read right past a NUL char, the code should use the `n` variable for the length, not the results of a call to `strlen()` – user3629249 Oct 25 '16 at 07:49
  • the posted code never sets the variables `line` and `tokens` after their initial initialization to 0 – user3629249 Oct 25 '16 at 07:52

3 Answers3

3

That is what you're printing. You are printing ptr = <ptr[0]>h. There is an extra h after %c in your printf() statement. You probably want to use:

        printf("ptr = %c\n", ptr[0]);
kichik
  • 33,220
  • 7
  • 94
  • 114
0

The format specifier for printing a character is %c. You have %ch, which is saying "print the character given by the next parameter, then print an 'h'".

Get rid of the extra h in your format string:

printf("ptr = %c\n", ptr[0]);
dbush
  • 205,898
  • 23
  • 218
  • 273
0
printf("ptr = %ch\n", ptr[0]);

ptr = hh

what's with the double hh?

The first h comes from the first character of the hello string, corresponds to ptr[0], and is there since you used %c in the printf format string.

The second h is there since you put it there in the printf format string, after %c.

The correct printf call would be something like:

printf("ptr = %c\n", ptr[0]);

If you want to print an address (pointer), you may want to consider this SO question (you can use the %p format specifier).

Community
  • 1
  • 1
Mr.C64
  • 41,637
  • 14
  • 86
  • 162