Array showing random characters at the end

  • A+

I wanted to test things out with arrays on C as I'm just starting to learn the language. Here is my code:

#include <stdio.h> main(){   int i,t;   char orig[5];   for(i=0;i<=4;i++){     orig[i] = '.';   }    printf("%s/n", orig); } 

Here is my output:


It is exactly that. What are those mysterious characters? What have i done wrong?


char orig[5];//creates an array of 5 char.  (with indices ranging from 0 to 4)  |?|?|?|0|0|0|0|0|?|?|?|?|       |         ^memory you do not own (your mysterious characters)       ^start of orig  for(i=0;i<=4;i++){  //attempts to populate array with '.'     orig[i] = '.';  |?|?|?|.|.|.|.|.|?|?|?|?|       |         ^memory you do not own (your mysterious characters)       ^start of orig 

This results in a non null terminated char array, which will invoke undefined behavior if used in a function that expects a C string. C strings must contain enough space to allow for null termination. Change your declaration to the following to accommodate.

char orig[6]; 

Then add the null termination to the end of your loop:

  ...   for(i=0;i<=4;i++){     orig[i] = '.';   }   orig[i] = 0; 

Resulting in:

|?|?|?|.|.|.|.|.|0|?|?|?|       |           ^memory you do not own       ^start of orig 

Note: Because the null termination results in a C string, the function using it knows how to interpret its contents (i.e. no undefined behavior), and your mysterious characters are held at bay.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: