Question

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

Was it helpful?

Solution

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);

OTHER TIPS

You are using ("%s ",cp) - prints null terminated string starting form cp, when you want print a character cp points to.

 char words[][5]={"Hiii", "Hello"};

The string literal Hello is 6 characters long (including the null character) but it is initializing an array of type char[5] (remember words is an array 2 of array 5 of char).

When a string literal is used to initialize an array of fixed size (here the char[5] array), only the the number of elements that fit into the array are used to initialize the array.

That is, the memory layout of words is:

Hiii\0Hello

the terminating null character of "Hello" is not copied, as it does not fit into the char[5] object.

(Note that this is true for C, in C++ it would not be valid to initialize an array with a string literal with more characters that the number of elements in the array).

In your case, you want to make some room for the terminated null character of "Hello" and so you should declare words as:

 char words[][6]={"Hiii", "Hello"};
              ^ instead of 5
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top