Home > OS >  How to move the pointer to the beginning?
How to move the pointer to the beginning?

Time:01-08

I am using malloc and realloc to get string input from user, using scanf: The code below is what I am using. I have managed to get all the user's input, but my pointer after the realloc is pointing to the end of the string. How can I make it point to the beginning?

int main() {
    char *ptr = NULL, input[2];
    ptr = (char *)malloc(sizeof(char));

    if (ptr == NULL) {
        printf("Memory not allocated");
        exit(0);
    }

    scanf("%c", &input[0]);
    // printf("%s\n", input);
    *ptr = input[0];
    int counter = 1; 
    scanf("%c", &input[0]);
    // printf("%s\n", input); 

    while (input[0] != '\n') {
        counter  ;
        ptr = realloc(ptr, counter * sizeof(char));
    
        if (ptr == NULL) {
            printf("Mermory not allocated");
            exit(0);
        }
    
        strncat(ptr, input,1);
        scanf("%c", &input[0]);
        // printf("%s\n", input);
    }

    printf("%s\n", ptr);
    return 0; 
}

CodePudding user response:

You are overcomplicating very simple task.

int main(void) 
{
    char *ptr = NULL;
    size_t size = 0;
    int ch;

    while((ch = fgetc(stdin)) != EOF && ch != '\n')
    {
        char *tmp = realloc(ptr, (size   2) * sizeof(*tmp));
        if(!tmp) {/* handle allocation error */}
        ptr = tmp;
        ptr[size  ] = ch;
        ptr[size] = 0;
    }

    printf("You have entered %zu characters and the string is: `%s`\n", 
           size, ptr ? ptr : "(NULL)");
    free(ptr);
    return 0; 
}

https://godbolt.org/z/soEdM6ojc

CodePudding user response:

but my pointer after the realloc is pointing to the end of the string.

No, it isn't. Supposing that the size of the the block that ptr points to is initially less than or equal to counter, and that the realloc(ptr, counter * sizeof(char)) call succeeds, the resulting value of ptr points to the same data that the original value of ptr pointed to, though its location in memory (the value of ptr itself) may be different. Since ptr originally pointed to the beginning of the string, the result of the realloc also points to the beginning of the string or an identical copy of it.

How can I make it point to the beginning?

It already does.

  •  Tags:  
  • Related