char *toParseStr = (char*)malloc(10); printf("Enter string here: "); scanf("%s",toParseStr); printf("%s",toParseStr); free(toParseStr);
First, the line in scanf indicates the input it is about to receive. To display a string before accepting keyboard input, use printf as shown.
Secondly, you do not need to dereference toParseStr since it points to a character array of size 10, like you toParseStr using malloc . If you used a function that would point to another place in memory, then &toParseStr is required.
For example, suppose you want to write a function to allocate memory. Then you will need &toParseStr since you are changing the contents of the pointer variable (this is the address in memory - you can see for yourself by typing its contents).
void AllocateString(char ** ptr_string, const int n) { *ptr_string = (char*)malloc(sizeof(char) * n); }
As you can see, it takes a char ** ptr_string which reads as a pointer that stores a memory cell of a pointer that will store the memory address (after the malloc operation) of the first byte of the allocated block of n bytes (right now). it has some memory address for garbage, as it is not initialized).
int main(int argc, char *argv[]) { char *toParseStr; const int n = 10; printf("Garbage: %p\n",toParseStr); AllocateString(&toParseStr,n); printf("Address of the first element of a contiguous array of %d bytes: %p\n",n,toParseStr); printf("Enter string here: "); scanf("%s",toParseStr); printf("%s\n",toParseStr); free(toParseStr); return 0; }
Thirdly, it is recommended to free the allocated memory. Despite the fact that this is your entire program, and this memory will be freed upon exiting the program, it is still good practice.