Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing Char Array Element

Tags:

arrays

c

I've been hung up on this for the past two hours, and it's really starting to irritate me. I'm using standard C, trying to print a char array's element.

The following is a snippet that works(prints entire array),

CreditCard validate_card(long long n) {

    CreditCard cc; // specify new credit card
    cc.n = n; // specify card num as passed
    cc.valid = false; // initialize as invalid
    cc.type = AEX; // initialize at american express

    bool valid;

    char s[20];
    sprintf( s, "%d", n ); // convert credit card number into char array
    printf("%s\n", s);
    return cc;
}

The following snippet does not work,

CreditCard validate_card(long long n) {

    CreditCard cc; // specify new credit card
    cc.n = n; // specify card num as passed
    cc.valid = false; // initialize as invalid
    cc.type = AEX; // initialize at american express

    bool valid;

    char s[20];
    sprintf( s, "%d", n ); // convert credit card number into char array
    printf("%s\n", s[0]);
    return cc;
}

On that note, if anyone could also too explain to me how to concatinate char array elements to char pointers, I'd be grateful.

like image 818
user1117742456 Avatar asked May 11 '14 07:05

user1117742456


2 Answers

When you use this line.

printf("%s\n", s[0]);

The compiler should print some warning about mismatch of the format string %s and the corresponding argument, s[0].

The type of s[0] is char, not char*.

What's your intention?

If you want to print just one character, use:

printf("%c\n", s[0]);

If you want to print the entire array of chracters, use:

printf("%s\n", s);
like image 108
R Sahu Avatar answered Oct 03 '22 07:10

R Sahu


You need to replace below line

printf("%s\n", s[0]);

with

printf("%c\n", s[0]);

to print 1 character.

To print all characters 1 by 1, use a loop.

like image 41
Mohit Jain Avatar answered Oct 03 '22 07:10

Mohit Jain