Suraksha Bisht
Suraksha Bisht

Reputation: 1

Storing any kind of ASCII values in pointer and then doing some operation using pointers

#include <stdio.h>

int main(){
    int *x;

    scanf("%d ", x);

    for (int i = 0; i < 26; i++)
        printf("%c\n", *(x+i));

    return 0;
}

I want to pass the value 65 (as it is the ASCII value of A) to a pointer through scanf and then I wanted to add 1 in a loop and print an alphabet from A to Z using %c, but my program is not giving any kind of output. Why? I have tried many things but the program is not giving me any kind of result after differant changes.

Upvotes: -8

Views: 92

Answers (1)

Chris
Chris

Reputation: 36506

Multiple problems with your code. The primary issue is that you're passing a pointer to scanf, which is correct, but that pointer doesn't point to valid memory. Thus undefined behavior is invoked. One of the possible outcomes of undefined behavior is the behavior you expected.

Any time you use a pointer in C you really need to stop and ask yourself: "What does this point to?"

Rather you want x to be an int and to pass its address to scanf.

#include <stdio.h>

int main(){
    int x;

    scanf("%d", &x);
}

Your second issue, related to the first, if x is a pointer, is that you're doing pointer arithmetic on x. If we were keeping x as a pointer, you'd need to dereference x and then add i to it. E.g. *x + i rather than *(x + i).

As a matter of style, you also want to check the return value from scanf` to ensure it succeeded before proceeding with an indeterminate value.

Upvotes: 0

Related Questions