How to get string from user when using typedef? (typedef char * string;
)
string bob
needs to be assigned a value, a memory location is which to store the data read.
#define N 80
// local array
char buf[N];
string bob = buf;
fgets(bob, N, stdin);
// or malloc
string bob = malloc(N);
if (bob == NULL) Handle_OutOfMemory();
fgets(bob, N, stdin);
Now trim the potential '\n'
bob[strcspn(bob, "\n")] = '\0';
Print result
printf("<%s>\n", bob);
... and use the contents later.
This implies code should use a right-sized memory allocation for use well passed this input code. strdup()
is not in the standard C library, but very common.
Sample code.
// local array approach
bob = strdup(bob);
// Now bob points to allocated memory
// malloc approach
// re-size to be efficient
void *t = realloc(bob, strlen(bob) + 1);
if (t) {
bob = t;
}
// Detail: A realloc to a smaller amount of memory rarely ever fails.
// If it did fail, just continue with old pointer.
If bob
points to allocated memory, clean up when done with bob
.
free(bob);
Only use scanf()
if required and you can't drop the class or get employment elsewhere.