Char pointers clarification

Hi guys,

I`m trying really hard to understand pointers and especially char pointers, but I have 3 questions and 1 example, that my brain simply can`t understand. PLEASE HELP

--Example--

char s1[] ="Joe";
char *s = s1;
s = "Frederick"; // 1.
*s = 'x'; // 2.
s= &s1; // 3.


1. why can I change this without dereference operator? I thought s can take only an address memory
2. why is this causing memory acces violation and the fore one didn`t?
3. cannot convert from 'char (*)[4]' to 'char *' -- what`s the correct statement?
Last edited on
1. why can I change this without dereference operator? I thought s can take only an address memory


s indeed will get an adsress of the first element of the sttring literal "Frederick"

It would be better to declare s as

const char *s;

if you are going to assign it a string literal. String literals have type const char[] which means that they may not be modified.


2. why is this causing memory acces violation and the fore one didn`t?


As I have said above string literals have type const char [] and the C++ Standard (and the C Standard though in C string literals have type char[]) does not allow to change character literals.


3. cannot convert from 'char (*)[7]' to 'char *' -- what`s the correct
statement?


The error message is clear enough.
You declared s as
char *s;
that is as a pointer to char while the expression &s1 has type

char ( * )[7]


that is a pointer to an array of 7 elements.

If you would write

s = s1;

then this would be correct code and s would point to the first element of the array.
Very clear now (surprised how easy it was, and I spent days)
Thanks Vlad
спасибо
Topic archived. No new replies allowed.