Abhijatya Singh
Abhijatya Singh

Reputation: 642

String of special characters

I am required to use string of special characters like: !,",#,~ etc

If I do :

char arr[10]  = "''''''''''";
char arr1[10] = "!!!!!!!!!!";
char arr2[10] = "##########";
printf("%s\t%s\t%s\n",arr,arr1,arr2);

then the printf prints the string and some garbage.

Where I am going wrong?

Upvotes: 0

Views: 2544

Answers (3)

Sourav Ghosh
Sourav Ghosh

Reputation: 134326

I hope you got your answer, however, just to clarify things a bit more, for %s format specifier in printf(), as per C11 standard document , chapter §7.21.6.1,

s

If no l length modifier is present, the argument shall be a pointer to the initial element of an array of character type. Characters from the array are written up to (but not including) the terminating null character.

That means, the argument pointer supplied for %s, should be a pointer to char, having a null in the end to mark the end-of-array. Thus, null-terminated char array are considered strings in C.

Now, coming back to your case,

char arr[10]  = "''''''''''";

you have exactly 10 initializer to a 10-element char array. thus, no space for null-termiantor. When you sypplu the base address of this array as an argument for printf() to be used for %s, printf() does not know where to stop, thus reading beyond allocated memory which in turn invokes undefined behaviour.

Solution:

  1. Leave the size allocation to the compiler, best approach.

     char arr[]  = "''''''''''";
    
  2. or, atleast, allocate enough memory so that the null-termiantor can be accomodated.

     char arr[11]  = "''''''''''";  //10 elements + 1 null
    

Please do the same for arr1 and arr2 also.

Upvotes: 1

Arun A S
Arun A S

Reputation: 7006

Characters arrays ( also known as C strings ) are null terminated, so you need an extra index in the array to store the null character. If you need a string of 10 characters, you need to create a string which can store 11 characters ( the extra character for the null character '\0' )

So, change your code to

char arr[11]  = "''''''''''";
char arr1[11] = "!!!!!!!!!!";
char arr2[11] = "##########";
printf("%s\t%s\t%s\n",arr,arr1,arr2);

or even better, as suggested by @TheParamagneticCroissant , you can do

char arr[]  = "''''''''''";
char arr1[] = "!!!!!!!!!!";
char arr2[] = "##########";
printf("%s\t%s\t%s\n",arr,arr1,arr2);

With this, the compiler will find out the length by itself.

Upvotes: 4

Sadique
Sadique

Reputation: 22821

You need one byte space more for the nul character:

char arr[11]  = "''''''''''";
char arr1[11] = "!!!!!!!!!!";
char arr2[11] = "##########";
printf("%s\t%s\t%s\n",arr,arr1,arr2);

Or simply:

char arr[]  = "''''''''''";
char arr1[] = "!!!!!!!!!!";
char arr2[] = "##########";
printf("%s\t%s\t%s\n",arr,arr1,arr2);

Upvotes: 1

Related Questions