syntagma
syntagma

Reputation: 24324

Behaviour of char pointers in C

I am reading a string from a file in the following format: N // length of string abcdef // string of length N

like that:

char necklace[400];
fin = fopen("file.in", "r");
fscanf(fin, "%d %s", &N, necklace);
char* left = &necklace[0];
char* right = &necklace[N-1];

However, when I declare char* before using them, it gives me compilation errors:

char necklace[400];
char* left, right;   // this causes the problem

fin = fopen("file.in", "r");
fscanf(fin, "%d %s", &N, necklace);

left = &necklace[0];
right = &necklace[N-1];

Could you please explain to me this behaviour?

Upvotes: 0

Views: 63

Answers (2)

Gopi
Gopi

Reputation: 19864

The right way to do it is :

char *left,*right;

When you do

char *left,right;

Then what you get is

char *left;
char right; /*This is not what you need you need *right but got right*/

So you see compilation errors

Upvotes: 6

M.M
M.M

Reputation: 141554

char *left, right; should be:

char *left;
char *right;

Alternatively you can write char *left, *right; but as we can see from your example this is a bit more prone to error.

Upvotes: 2

Related Questions