0

I have been reading C book by K&R. I came across this words

Character arrays are a special case of initialization; a string may be used instead of the braces and commas notation:

char pattern = "ould";

is a shorthand for the longer but equivalent

char pattern[] = { 'o', 'u', 'l', 'd', '\0' };

In this case, the array size is five (four characters plus the terminating '\0').

I coded a simple program to test it as

#include<stdio.h>
int main()
{
    char c= "Hello";
    printf("%s",c);
    return 0;
}

According to that book there should be no error but it returns an error

`cannot convert char * to char` 

As per my previous knowledge of arrays,the array statement should be like char *c="Hello"; Can you explain the meaning of the words in that book please. Did i Misunderstand the meaning of that words??

10
  • Is there really a line in your book telling " char pattern = "ould"; " ? Commented Aug 4, 2014 at 9:58
  • Yes I just copied and pasted them Here Commented Aug 4, 2014 at 9:59
  • 3
    Are you really sure ? I think it misses brackets ... Commented Aug 4, 2014 at 10:02
  • 3
    Page 86 of my copy of K&R (2nd Edition) reads char pattern[] = "ould";. If you have a digital copy (you did say you copied and pasted it), it may have been an oversight in the transcription or automated scanning process. Commented Aug 4, 2014 at 10:06
  • Yep i now think the same... Commented Aug 4, 2014 at 10:06

2 Answers 2

2

Well it's missing two brackets. char pattern[] = "ould"; will work fine. Time to trash that book !

Sign up to request clarification or add additional context in comments.

Comments

1

It should be:

char pattern[] =  "ould" ;

Also be careful with :

char* pattern = "ould";  

Please note that with "" you define a const characters array. It is supposed not to change anymore during app execution. If you do:

pattern[2] = '9'; 

your app may crash.

Correct is:

const char* pattern = "ould";

Why is that? Your compiler probably will allocate the "ould" in a protected read only memory block and pattern is just a pointer to it. If you however define :

char pattern[] = { 'o', 'u', 'l', 'd', '\0' };

It is totally different. It is a modifiable buffer in your local program stack. You can write pattern[2] = '9'; in this case. It is the same as to define char buffer with size 5 and copy text in it. Please read from somewhere else about string initializations and string literals.

3 Comments

it should be: {thecode} that's wrong. It wouldn't fit the context, since the one you've provided is not equivalent to the other.
Sorry. char pattern[] = "ould" ; is also Ok.
The string literal is not const h, however it causes undefined behaviour to modify it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.