Browse Source

more examples

master
T. Meissner 11 years ago
parent
commit
d223b5807c
1 changed files with 66 additions and 0 deletions
  1. +66
    -0
      c_pointers/chapter_5.c

+ 66
- 0
c_pointers/chapter_5.c View File

@ -3,6 +3,22 @@
#include <string.h>
// summary ofstring placement
/*
char *globalHeader = "Chapter";
char globalArrayHeader[] = "Chapter";
void displayHeader() {
static char *staticHeader = "Chapter";
char *localHeader = "Chapter";
static char staticArrayHeader[] = "Chapter";
char localArrayHeader[] = "Chapter";
char *heapHeader = malloc(strlen("Chapter")+1);
strcpy(heapHeader, "Chapter");
}
*/
int main(void) {
// print size of char & character literal
@ -51,6 +67,56 @@ int main(void) {
}
printf("\n");
// direct init with character pointer
// don't create a new copy, instead a reference to string literal pool only
char *headerRef = "Media Player";
printf("%s\n", headerRef);
// you shouldn't assign a char pointer with a character literal
// because character literals is of type int
// wrong:
// char *prefix = '+';
// better:
char *prefix = malloc(2);
*prefix = '+';
*(prefix + 1) = 0;
printf("%s\n", prefix);
free(prefix);
// string initialisation from standard in
// don't forget to allocate memory before read from standard in
// wrong:
// char *command;
// printf("%s: ", "Enter a command");
// scanf("%s", command);
// better:
char *command = malloc(11);
printf("%s: ", "Enter a command");
scanf("%10s", command);
printf("You entered: %s with length: %zu\n", command, strlen(command));
free(command);
// memset buffer overflow test
// executes without warnings or errors on osx :D
char *mem = malloc(11);
memset(mem, 0x42, 64);
free(mem);
}
// standard string operations
// comparing strings
{
char command[16];
printf("Enter a command: ");
scanf("%15s", command);
// return value of strlen == 0 -> strings are equal
if (!strcmp(command, "quit")) {
printf("The command was quit\n");
} else {
printf("The command wasn't quit\n");
}
}
return 0;


Loading…
Cancel
Save