I\'m fairly competent in a few scripting languages, but I\'m finally forcing myself to learn raw C. I\'m just playing around with some basic stuff (I/O right now). How can
char *toParseStr = (char*)malloc(10);
printf("Enter string here: ");
scanf("%s",toParseStr);
printf("%s",toParseStr);
free(toParseStr);
Firstly, the string in scanf
is specifies the input it's going to receive. In order to display a string before accepting keyboard input, use printf
as shown.
Secondly, you don't need to dereference toParseStr
since it's pointing to a character array of size 10 as you allocated with malloc
. If you were using a function which would point it to another memory location, then &toParseStr
is required.
For example, suppose you wanted to write a function to allocate memory. Then you'd need &toParseStr
since you're changing the contents of the pointer variable (which is an address in memory --- you can see for yourself by printing its contents).
void AllocateString(char ** ptr_string, const int n)
{
*ptr_string = (char*)malloc(sizeof(char) * n);
}
As you can see, it accepts char ** ptr_string
which reads as a pointer which stores the memory location of a pointer which will store the memory address (after the malloc
operation) of the first byte of an allocated block of n
bytes (right now it has some garbage memory address since it is uninitialized).
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 memory you allocate. Even though this is your whole program, and this memory will be deallocated when the program quits, it's still good practice.