0

For example, I have a string containing "184553", how do I go about extracting the 3rd character "4" from string string and assigning it to another variable?

I have tried the following code but it does not work, the system crashes:

char string[6] = "184553";
printf("%s",string[2]); // Expecting it to print "4"

Any help??

6
Contributors
7
Replies
11
Views
6 Years
Discussion Span
Last Post by Ancient Dragon
Featured Replies
  • 1
    WaltP 2,905   6 Years Ago

    [QUOTE=Dexxta27;]Yes, %c should be used instead of %s. This isn't technically a C-string, just a simple array. A string would require 7 spaces, to accommodate for the NULL value at the end.[/QUOTE] No, technically it [I]is[/I] a C-string. It has quotes which by definition ends in a NULL value. The … Read More

0

hi there,

As you want to print a single character please use %c as the format specifier instead of %s. Also the size of string variable should be 7.
The code becomes as:

char string[7] = "184553";
   
      printf("%c",string[2]); //prints "4" now

Anirudh

0

Yes, %c should be used instead of %s. This isn't technically a C-string, just a simple array. A string would require 7 spaces, to accommodate for the NULL value at the end.

1

Yes, %c should be used instead of %s. This isn't technically a C-string, just a simple array. A string would require 7 spaces, to accommodate for the NULL value at the end.

No, technically it is a C-string. It has quotes which by definition ends in a NULL value. The definition actually overflows the array.

0

No, technically it is a C-string. It has quotes which by definition ends in a NULL value. The definition actually overflows the array.

Thank-you WaltP

I appreciate your technical prowess with these questions..and I hope you realize this is sincere...

Edited by gerard4143: n/a

0

When you want to declare an array of the same size as a const string literal then don't specify the array size so that the compiler can figure out the size itself char string[] = "184553";

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.