The compiler treats the types “char * var” and “char var[]” differently when it comes to taking the address of a variable via the & operator. Here’s a little snippet of code to demonstrate:
#include <stdio.h>
#include <stdint.h>
#include <string.h>
int main(int argc, char ** argv) {
const char * str1 = "This is string 1";
char str2[32];
snprintf(str2, sizeof(str2), "This is string 2");
if ((uint32_t)str1 == (uint32_t)&str1) {
printf("str1 == &str1n");
} else { printf("str1 != &str1n"); }
if ((uint32_t)str2 == (uint32_t)&str2) {
printf("str2 == &str2n");
} else { printf("str2 != &str2n"); }
return 0;
}
The output:
iuser@MyXPS MINGW64 ~/Documents/pointers
$ ./run.sh
str1 != &str1
str2 == &str2
Can someone please explain why the compiler refuses to get the address of a character array pointer? Moreover, I would really like the compiler to at least generate a compile time warning when I take the address of a character array that says “fuck you, I never created that pointer and I’m about to fuck you with no warning message” rather than just cause a runtime failure that breaks shit and takes hours to debug.
Anger…….
gilfoyle is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.