From 4d7a74593beaa722625c10599e920ecb471e3c5e Mon Sep 17 00:00:00 2001 From: tmeissner Date: Sun, 25 May 2014 14:36:10 +0200 Subject: [PATCH] new examples of string initialisation --- c_pointers/chapter_5.c | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/c_pointers/chapter_5.c b/c_pointers/chapter_5.c index c3adceb..afbe96c 100644 --- a/c_pointers/chapter_5.c +++ b/c_pointers/chapter_5.c @@ -10,17 +10,49 @@ int main(void) { printf("%zu\n", sizeof('a')); - // when a string is not a constant // doesn't work with gcc anymore, also with -Wno-deprecated-writable-strings // gives 'Bus error: 10' { char *tabHeader = "Sound"; - *tabHeader = 'L'; + //*tabHeader = 'L'; printf("%s\n", tabHeader); } + // string initialization + { + // array of char + char header[] = "Media Player"; + printf("%s\n", header); + + header[0] = 'W'; + header[1] = 'u'; + header[2] = 'r'; + header[3] = 's'; + header[4] = 't'; + header[5] = '\0'; + printf("%s\n", header); + + // pointer to char (with memory allocation) + char *headerPtr = malloc(strlen("Media Player") + 1); + strcpy(headerPtr, "Media Player"); + printf("%s\n", headerPtr); + + *headerPtr = 'W'; + *(headerPtr + 1) = 'u'; + *(headerPtr + 2) = 'r'; + *(headerPtr + 3) = 's'; + *(headerPtr + 4) = 't'; + *(headerPtr + 5) = '\0'; + printf("%s\n", headerPtr); + for (size_t j = 0; j < strlen(headerPtr); j++) { + printf("headerPtr[%zu] Address: %p Value: %c\n", j, &headerPtr[j], headerPtr[j]); + } + printf("\n"); + + } + return 0; } \ No newline at end of file