I want to print a two dimensional array's value, one by one. But my code shows one item many times :(
#include<stdio.h>
#include<conio.h>
void main()
{
char words[][5]={"Hiii","Hello"};
int size;
char *cp,*p;
p=words;
clrscr();
printf("%p ",p);
size=sizeof(words);
printf("Size %d\n",size);
for(cp=p;cp<(p+size);cp++)
printf("%s ",cp);
getch();
}
Expected o/p
Hiii
Hello
Unexpected o/p
Hiii
iii
ii
i
Hello
ello
llo
lo
o
First of all, the array words
is laid out in memory like
Hiii\0Hello
Also, since cp
is a pointer to char
, the expression cp++
increments cp
by exactly on byte. That's you're printing "Hiii"
, followed by "iii"
then "ii"
and "i"
. For correctness, cp++
should be changed to cp += 5
.
Finally, the array is incorrectly sized. The length of "Hiii"
is 5
and the length of "Hello"
is 6
, since there is an implicit null terminator \0
at the end of each string. So words
should actually be declared as char words[][6]={"Hiii","Hello"};
. This also means that cp
should now be incremented by 6
each time.
With the corrections made, the for
loop becomes
for(cp=p;cp<(p+size);cp+=6)
printf("%s ",cp);
To make you life easier, since you're working with an array, you can make use of indices rather the relying on pointer arithmetic:
int strCount = size / 6; // since each element of words is 6 characters long
for(int i = 0; i < strCount; i++)
printf("%s ", cp);