Why can't I assign a newline character to a char pointer in C?
Asked by
CodeWizard42
I'm trying to understand the behavior of char pointers in C. When I declare a char pointer like this: `char* p = 'n';`, I get a warning because 'n' is being treated as an int, not a char. Why is that? Isn't 'n' a character? How does this relate to the ASCII value? Also, if I'm looking to check for 'n' or EOF, what should I be doing instead? Any insights would be really appreciated!
Answers
Great question! Remember that in C, when you declare a `char*`, it expects a memory address pointing to a string, not a singular character value. The so-called newline character 'n' is not a valid address, which is why you're getting that warning when you use it alone. Stick to string literals to get it right!
Reply to this answer
You're on the right track asking about this! When you try to assign a single character to a char pointer, you're essentially trying to make `p` point to an invalid memory location (since 'n' resolves to its ASCII value). Instead, make sure you're using string notation (double quotes) to define a string literal, like `char* p = "n";`. That should clear up your warnings and confusion!
Reply to this answer
The reason you're seeing that warning is that single quotes in C denote a character literal, which is treated as an integer type. So when you write `char* p = 'n';`, it attempts to assign the integer value of the newline character (which is 10 in ASCII) to a char pointer, and that's not valid since a pointer should reference a memory address, not an integer value. To correctly assign a newline to a char pointer, you should do it like this: `char* p = "n";` since that treats it as a string literal instead.
Reply to this answer
Just a quick clarification: in C, character literals are actually of type int, which is different from C++. That's why you can't just assign a character directly to a char pointer without using a string literal. As for checking for 'n' or EOF, you'll want to compare characters directly with `getchar()` or a similar function. That's the way to go!
Reply to this answer
Character literals are treated as integers in C, hence 'n' has an integer value (10). When you try to assign it to a `char*`, it mistakenly interprets this value as an address, which leads to that warning. If you want to handle strings or characters correctly, use double quotes like "Goodbye!n" which points to a valid memory address holding the string data.
Reply to this answer
Add your answer
Answers are reviewed before publication.
ByteBuster: What's the exact difference between using single and double quotes?