Program prints the next letter of the alphabet instead of the next char on the pointer

Asked

Viewed 59 times

0

My program is printing the letter P instead of i, I would like to understand the problem behind this and what is wrong in my code. If I put the letter A instead of O, the program would print the letter B.

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

int main (){
    char *p = {'O', 'i'};
    p++;
    printf("%c\n", p);
}

2 answers

3


There are two errors in this code. One of it is that it did not allocate memory to put the content, so it will access garbage in memory.

And the other is that is not accessing the content pointed by p rather the value of p, then you need to dereference the value. If you want to access the value of p then have to use another formatter, but still will not give what you want:

#include <stdio.h>
#include <stdlib.h>
 
int main () {
    char *p = malloc(2);
    p[0] = 'O';
    p[1] = 'i';
    p++;
    printf("%c\n", *p);
    printf("%p\n", p);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • If I put 1 in the malloc () the code continues to function normally and shows the i, wouldn’t it be right to allocate 1 byte for each index? So malloc (2) can allocate the p[0] and p[1]. Thank you for your response.

  • 3

    https://i.stack.Imgur.com/zdAbK.jpg. It is right to allocate one byte for each index, so 2.

1

As you stated only a pointer *p char. Progamma is only storing the first position, that is the letter 'O'. When increments p++, Voce is not jumping to the next memory address, it is only increasing the value 79 that corresponds to the ASCII code of the letter 'O' in the ascii table. The same occurs with the character 'B'. So when giving a printf("%c",p) the letter corresponding to the ascii code is printed on the screen see more

To print the ascii code instead of the letter just change the %c for %d, thus printf("%d", p). In the table the codes of the letters are organized in sequence so the following letter is printed

Browser other questions tagged

You are not signed in. Login or sign up in order to post.