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
CodePudding user response:
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
CodePudding user response:
you just have to remove the address from &text because text is a pointer and the string always pointe to the first character.