How can a character and a string with only one character can be differentiated? What is the internal difference between a character and string, with only one character in it?

Questions by dattu.kv   answers by dattu.kv

Showing Answers 1 - 6 of 6 Answers

kalis

  • Nov 17th, 2007
 

A character means a single alphabet. But string means a group of characters enclosed within within double quotes having a null character at the end. In case if you are in a need to use a character you can use a single character rather than a string. What is the purpose of using a single character in a string?

  Was this answer useful?  Yes

kaushalgoa

  • Dec 27th, 2007
 

The following program will crash -


void main()
{
    char a = 'a';
    char *b = "b";

    printf("%sn", a);
    printf("%sn", b);

    return;
}

  Was this answer useful?  Yes

AkterSuriya

  • Jan 21st, 2008
 

There are various things to be observed for this
1. First of all while at the time of storing

single character is stored as char abc = 's';
where as string having single character can be stored as char pqr[] = "s";

2. single character takes one byte for storage
    String (even single character is stored) takes two bytes, one for one character and second for null character.

    This can be verified by following C statement:
    
    printf("%d %d", sizeof(abc), sizeof(pqr));
    which gives output as 1 and 2 respectively. (assuming turbo C compiler and 1 byte for char)

yrenster

  • Feb 5th, 2008
 

A character is a interger in the range -127 to 127. You can set a char value using interger. for example, the character 'a': char cc = 141; The string "a" is not a integer, a string defines a GROUP of characters, and for a single character string, it happens to be a group with only one member. But, the nature is still a group, not a member.

  Was this answer useful?  Yes

kbjarnason

  • Jul 1st, 2010
 

Easy: they're different types.

char s[] = "a";
char c = 'a'';

There are a few cases where this could be problematic.  For example:

void func( char *p )
{
   while ( *p )
     ...
}

func( s );
func( &c );

The compiler is under no obligation to complain here, as you're passing the correct types to func in both cases - but in the second case, expect to have at the very least a bug.

From func's point of view, there is absolutely no way to tell the difference between the two.  They are, to it, absolutely identical.  If you need to let func know that it's dealing with a char rather than a string, you'll have to pass it a flag saying "this is a char", or a length saying "only process one character" or some equivalent.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions