I have this code in c and it's working properly.
char* str2 = string + (str_len - end_len);
str_len
and end_len
are two integers and string
is another char pointer string.
I don't understand why I am able to add an integer to a character pointer string.
Shouldn't this give a type error?
str2
will be assigned the pointer value of string
+ (str_len - end_len)
. If offset = str_len - end_len
< 0 or offset
> size of string
(array) + 1 then it's undefined behavior (note: sizeof "hello "
counts the trailing '\0' for a string hence the -1
). Here's an example:
#include <stdio.h>
int main() {
char string[] = "hello world";
char *str2 = string + (sizeof "hello " - 1);
printf("%s\n", str2);
}
prints:
world