From d98f46ce647846b0aa30b2e16a30fd4e152a1bf5 Mon Sep 17 00:00:00 2001 From: Carlos Maiolino Date: Thu, 10 Jul 2025 22:55:07 +0200 Subject: Add new code Signed-off-by: Carlos Maiolino --- C/Pointers/addr.c | 47 ++++++++++++++++++++++++++++++++++++++++++ C/Pointers/multi_indirection.c | 42 +++++++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 C/Pointers/addr.c create mode 100644 C/Pointers/multi_indirection.c (limited to 'C/Pointers') diff --git a/C/Pointers/addr.c b/C/Pointers/addr.c new file mode 100644 index 0000000..f77a9c6 --- /dev/null +++ b/C/Pointers/addr.c @@ -0,0 +1,47 @@ +#include + +int main (void) +{ + /* + * Arrays in C are just sequential data items + * stored in a memory location + * The address of the array, is the same as the first + * element in the array + * The name of the array is also the address of the array. + */ + + char str1[] = "Hello cruel world"; /* \0 is automatically added */ + + /* Those variables look the same, but they are not. */ + + /* This is an array */ + + /* + * str2, is the address of the "ARRAY" which the characters + * of the string are stored + * str2 is not a 'pointer' to the location of the Hello char array + * str2 IS THE LOCATION of the array. + */ + char str2[] = "Hello"; + + /* + * This is a pointer. + * + * Whose value is not the string, but the - address of that string - + * + */ + char *str3 = "Goodbye"; + + str3 = NULL; + str2 = NULL; + /* + * &str1, &str1[0] and str1, all points to the very same address. + * + * The array name, str1, is also the address of the array. + * */ + printf("%s, %c, %d, %d %d\n", str1, str1[0], &str1, &str1[0], str1); + + printf("%p %p %s\n", &str2, str2, str2); + printf("%p %p %s\n", &str3, str3, str3); + +} diff --git a/C/Pointers/multi_indirection.c b/C/Pointers/multi_indirection.c new file mode 100644 index 0000000..92b677c --- /dev/null +++ b/C/Pointers/multi_indirection.c @@ -0,0 +1,42 @@ +#include + +char *words[3]; + +int main(void) +{ + char *pc; + char **ppc; + int i; + char *foo, *bar; + + printf("multiple indirection example\n"); + + words[0] = "zero"; + foo = "FOO"; + words[1] = "one"; + bar = "BAR"; + words[2] = "two"; + + for (int i = 0; i < 3; i++) + printf("%s\n", words[i]); + + printf("Print each char in each string...\n"); + + ppc = words; + + printf("Addr of array head %p\n", words); + for (i = 0; i < 3; i ++) { + ppc = words + i; + pc = *ppc; + + printf("array %d -> loc %p -> deref: %p\n", i, &words[i], *ppc); + while (*pc != 0) { + printf("addr: %p - content: %c \n", pc, *pc); + pc += 1; + } + + printf("\n"); + } + + return 0; +} -- cgit v1.2.3