8. 1 Why is this code not working?
Char * answer; <---- space not explicitly allocated
Printf ("Type something:/n");
Gets (answer );
Printf ("You typed/"% S/"/N", Answer );
The answer pointer variable passes in gets (), which is intended to point to the location of the saved response, but does not point to any valid location. In other words, we do not know where the answer Pointer Points. Because local variables are not initialized and usually contain junk information, you cannot even ensure that answer is a valid pointer. The simplest solution to correct the questioning program is to use a local array instead of a pointer, so that the compiler can consider the issue of allocation:
#include <stdio.h>
#include <string.h>
char answer[100], *p;
printf("Type something:/n");
fgets(answer, sizeof answer, stdin);
if((p = strchr(answer, '/n')) != NULL)
*p = '/0';
printf("You typed /"%s/"/n", answer);
In this example, fgets () is used to replace gets () so that the array Terminator is not rewritten. Unfortunately, fgets () in this example will not be like gets ()
Remove the ending/n automatically. You can also use malloc () to allocate an answer buffer.
Also: Use strcat as little as possible
Char * S1 ="Hello,";
Char * S2 ="World!";
Char * S3 = strcat (S1, S2 );
As with the above problem, the main problem here is that the space is not properly allocated for the connection results. C does not provide automatically managed string types.
The C compiler only allocates space for objects explicitly mentioned in the source code (for strings, this includes character arrays and string constants ). The programmer must be a string.
Allocate enough space for the result of such operation during the runtime. It can usually be done by declaring an array or calling malloc.
Strcat () is not allocated. The second string is attached after the first string. Therefore, one solution is to declare the first string as an array:
Char S1 [20] = "hello ,";
Because strcat () returns the value of the first parameter, in this example, It is S1, and S3 is actually redundant. After strcat () is called, S1 contains the result.
The strcat () call actually has two problems:
1. The String constant pointed to by S1. The space is insufficient for the connected string.
2. Not necessarily writable.
For:
Char * P;
Strcpy (p,"ABC");
Uninitialized pointer P points to the random address, which may lead to a disaster.