0

This is my code

 int a;
char array[10];

printf("Enter a number \n");
scanf("%d", &a);
array[1] = a;


printf("array = %d\n",array[1]);

problem is if I enter a number that is more than 4 for example 12345 then it will print something else instead of 12345

some help me

5 Answers 5

5

You have the array of type char. The size of a char is 1 byte and so it fits values from -128 to 127. Any bigger value will overflow. If you want to store bigger values use a different type - short, int, even long long if needed.

Sign up to request clarification or add additional context in comments.

Comments

1

why are you storing an int into a char array .. big values of a will overflow ..

we can help you more if you explain what you are trying to do in your code .. because I don't see any reason for you to store an int into a char array

Comments

1

I think you're missing a couple of things.

Firstly: arrays start at index [0] -- is there any reason to start at index 1?

Secondly, as others pointed out, an array of char (i.e. numbers between -128 and 127) will not store numbers outside that range.

Thirdly, what I think you want is convert the binary number a to a string array. For this you need to use sprintf() (in the case of C, or itoa in the case of C++):

#include<stdio.h>
int main() {
  int a;
  char array[10];
  printf("Enter a number \n");
  scanf("%d", &a);
  sprintf(array,"%d",a); 
  printf("array = %s\n",array);
}

Comments

0

Um, this code seems wrong on quite a few levels.

You're scanning a number as a string, and then assigning it to an integer without using stoi(). So the only thing that will be the same b/w array[1] and the number you scan, a will be that their binary representation match up to some degree (upto 1 byte).

If you're scanning 10digit numbers simply use:

long long int a;
scanf("%10lld", &a);

Comments

0

You have a few errors:

So if you want to print what you entered, try this:

printf("a = %d\n", a);

However, if you REALLY want to start putting stuff into arrays, lets talk about a few things...

First of all, arrays are 0 indexed, so instead of array[1] = a, you would do `array[0] = a'

Second, this is casting an int (which is most likely 32-bits) to a char (most likely 8-bits). So the maximum amount you can have in it is 255 (Actually this can get a bit muddy... the standard doesn't specify if char is signed or unsigned. Therefore, the max might actually be 127!).

If you explain what your end goal is, I can expand further.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.