I am reading a C course (it is dutch so probably you won't know) and there is a small exercise to understand string behaviour. Therefor i created a small C program to start the exercise but already the first output of my program is (for me) astonishing.
Source of my C program :
#include <string.h>
#include <stdio.h>
void printString(char *string)
{
printf("0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19\n");
printf("%c ",string[0]);
printf("%c ",string[1]);
printf("%c ",string[2]);
printf("%c ",string[3]);
printf("%c ",string[4]);
printf("%c ",string[5]);
printf("%c ",string[6]);
printf("%c ",string[7]);
printf("%c ",string[8]);
printf("%c ",string[9]);
printf("%c ",string[10]);
printf("%c ",string[11]);
printf("%c ",string[12]);
printf("%c ",string[13]);
printf("%c ",string[14]);
printf("%c ",string[15]);
printf("%c ",string[16]);
printf("%d ",string[17]);
printf("%d ",string[18]);
printf("%d\n",string[19]);
}
void main(){
char str[20];
strcpy(str,"Dag grootmoeder!");
printString(str);
}
I compiled with gcc (no special switches) and ran the program several times :
(For the English speaking people Dag grootmoeder! == Hi grandma!)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
D a g g r o o t m o e d e r ! 94 -90 111
$./oefString
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
D a g g r o o t m o e d e r ! 51 -12 96
$./oefString
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
D a g g r o o t m o e d e r ! -17 -117 28
$./oefString
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
D a g g r o o t m o e d e r ! 96 15 -28
$./oefString
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
D a g g r o o t m o e d e r ! -20 -46 -18
$./oefString
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
D a g g r o o t m o e d e r ! 68 -75 58
Here is the question :
1) Why do I get rubbish values for the last 3 indexes of str ? At first I was also printf()'ing them with %c and noticed the chars changed, that is why I used %d thereafter to display the integer values.
2) Why do these values change? I do nothing more then copying the same string using strcpy() into str.
Thx for taking time to read and even more thanx for those who respond !
Jorn