stardust
stardust

Reputation: 1

Printing a row of 2d char array (C++)

So I've declared a 2d array and want to display its rows one by one.But when I execute the following code I see all the rows in the matrix starting from the one I require.

Code:

#include<iostream.h>
#include<conio.h>
#include<stdio.h>

char topics[3][10]={"Literature","Science---","Sports----"};

void main()
{
    clrscr();
    cout<<topics[0][0]<<endl<<topics[1][0]<<endl<<topics[2][0]<<endl;
    puts(topics[0]);
    cout<<endl;
    puts(topics[1]);
    getch();
}

Output:

L    
S   
S   
LiteratureScience---Sports----         
Science---Sports----

What I want my program to do is that when puts(0) is executed, only 'Literature' should be displayed and when puts(1) is executed, only 'Science---' is displayed.

I am a beginner. Please suggest what corrections should I make.Thank you. :)

Upvotes: 0

Views: 1376

Answers (3)

Jonathan von Schroeder
Jonathan von Schroeder

Reputation: 1713

The problem is that strings in C are terminated by \0. Thus you need 11 chars to store a string of length 10. This last char is simply skipped if you make your array too small (see Why "initializer-string for array of chars is too long" compiles fine in C & not in C++?). Therefore puts does not find a \0 at the end of the string and instead goes to the end of the array because (luckily) the memory after the array contains a zero. As commented this can be fixed making the array the correct size

#include <stdio.h>

char topics[3][11]={"Literature","Science---","Sports----"};

int main()
{
    puts(topics[0]);
    puts(topics[1]);
}

The output is

Literature
Science---

A C++ compiler would not accept your program:

3:59: error: initializer-string for array of chars is too long [-fpermissive]
3:59: error: initializer-string for array of chars is too long [-fpermissive]
3:59: error: initializer-string for array of chars is too long [-fpermissive]

go away.

Upvotes: 1

frogatto
frogatto

Reputation: 29285

You wouldn't need to mention that array's dimensions explicity. The compiler does the job.

const char *topics[] = {"Literature", "Science---", "Sports----"};

int main() {
    puts(topics[0]);
    puts(topics[1]);
}

Note that in this way, those strings are read-only.

Upvotes: 1

barak manos
barak manos

Reputation: 30126

The declaration:

char topics[3][10]={"Literature","Science---","Sports----"};

Is taken by the compiler as:

char topics[3][10]={"Literature\0","Science---\0","Sports----\0"};

Which means that each one of those strings consists of 11 characters.

Therefore you need to change topics[3][10] to topics[3][11].

Upvotes: 3

Related Questions