-1

why when i run this code to take in a string input by the user why does it not print out the final result ?

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

/* Function Declerations */

/* Global Variables */
char *text = NULL;
int size;
int main(){
    /* Initializing Global Variables */

    printf("enter a number limit for text: ");
    scanf("%d", &size);
    /* Initial memory allocation */
    text = (char *) malloc(size * sizeof(char));

    if(text != NULL){
        printf("Enter some text: \n");
        scanf("%s", &text);
        // scanf(" ");
        // gets(text);
        printf("You inputed: %s", text);
    }

    free(text);
    return 0;
}

/* Function Details */

in fact the end result looks like this

enter a number limit for text: 20
Enter some text: 
jason
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Oh Oh
  • 35
  • 3

2 Answers2

3

text is already a char *, so you don't have to pass &text to scanf, but only text.

scanf takes a pointer as argument in order to modify the pointed value, but if you pass a char ** as an argument, you will modify the pointer to the string instead of the pointed string

Marco Balo
  • 336
  • 2
  • 9
0

you just have to remove the address from &text because text is a pointer and the string always pointe to the first character.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 13 '22 at 22:17