You are here:

C/doubt in very basics of c

Advertisement


Question
pls tell me how to assign an integer value to a char.
for ex
int a=10;
char b[10];
b=a;//but this shows a error "lvalue required"
   //so i tried:->
b[10]=a;//it compiled but didnt give the expected o/p
printf("%s %s",b,b[10]);//printing some ascii value

pls tell me how solving this


Answer
What do you mean by "assign an integer value to a char"?
If a is 10 and you have a char array b.
What do you expect the value of array b to be.

When you declare:
b[10]
that means b has 10 storage locations starting from 0.
So, the last location is b[9] and it is illegal to access b[10].

So, if you can tell me the expected o/p, I can try to give you a solution.

If you want value of a (10 in this case) to be stored in b, then here is the code which you can try:

main()
{
  int a = 10;
  char b[10] = {0};

  sprintf(b, "%d", a);

  printf("A = %d\n");
  printf("B = %s\n", b);
}

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.