singularity
singularity

Reputation: 15

Is a manually assigned address overwritten by the compiler? (Please see code as well)

Some interesting bugs pop up when I run this code... Inside the input loop, things seem fine (not really, addresses aren't working properly but hey! *c atleast gives me the right value)

However in the output loop, things get messy. Can anyone tell me why?

#include<stdio.h>

int main(void)
{
    char a;
    int count = 1, flag = 0;
    unsigned long int f = (unsigned long int)&a;
    do
    {
        char *c = (char*)(f+count);
        char temp = getchar();
        if (temp == '\n')
        {
            flag = 1;
            *c = '\0';
        }
        else
            *c = temp;
        printf("%p %c\n", c, *c);
        count++;
    }
    while( flag == 0);

    count = 0;
    char *h = (char *)f+1;
    do
    {
        printf("%p\n", (h+count));
        count++;
    } while (count < 5);

    return 0;
}

Upvotes: 0

Views: 53

Answers (2)

0___________
0___________

Reputation: 67835

If I understand what you want mean - you want to store string in the object of other type

char *getStringToAnotherType(FILE *fp, void *mydata, size_t sizeofMyData)
{
    return fgets(mydata, sizeofMyData, fp);
}

int main(void)
{
    int x;
    double y;
    char *str = getStringToAnotherType(stdin, &x, sizeof(x));
    printf("\"%s\"\n", str);

    str = getStringToAnotherType(stdin, &y, sizeof(y));
    printf("\"%s\"\n", str);
}

https://godbolt.org/z/TGmnX7

Upvotes: 1

lnksz
lnksz

Reputation: 501

Not "addresses are not working", you are misusing the language.

It seem you need to learn about C memory concepts.

Here you have a single char a but you want to write there possibly many chars... By accessing it through a pointer, then incrementing the pointer you enter into some memory addresses you are not meant to touch.

Have a look at https://en.m.wikibooks.org/wiki/C_Programming/stdio.h/getchar

Upvotes: 2

Related Questions