I am reading course C (this is Dutch, so you probably donโt know), and there is a little exercise to understand the behavior of the strings. So I created a small C program to start the exercise, but the very first output of my program (for me) is amazing.
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 gcc (without special switches) and ran the program several times: (For 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 aggrootmoeder ! 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 aggrootmoeder ! 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 aggrootmoeder ! -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 aggrootmoeder ! 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 aggrootmoeder ! -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 aggrootmoeder ! 68 -75 58
Here is the question:
1) Why am I getting garbage values โโfrom the last 3 index of str? At first, I also had printf() with their %c and noticed that the characters were changed, so I used %d after that to display the integer values.
2) Why do these values โโchange? I do nothing by copying the same line using strcpy() in str.
Thanks for the time spent reading and even more thanx for those in charge!
Jorn