I am trying to print every fourth character of a string using pointers.
I was able to achieve it using the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[]){
char* string = "WhatTheeHell";
char* p = string;
while(*p != '\0'){
printf("%c\n", *p);
p += 4;
}
return 0;
}
This correctly gives the output to me as:
W
T
H
Now, I tried another way to do it, which according to my knowledge of pointer arithmetic, should have worked, since the size of int on my machine is 4 bytes.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[]){
char* string = "WhatTheeHell";
int* p = (int*)string;
while(*p != '\0'){
printf("%c\n", *p);
p += 1;
}
return 0;
}
When I print the output for this, it gives me WTH followed by four newlines.
My question, why are the four newlines being printed? Shouldn't it be that after the H is printed, the *p gives a NULL character present at the end of the string literal and the loop gets terminated?
*pbe0when it includes 3 more bytes beyond the array? It's undefined behaviour.