SamSam
SamSam

Reputation: 31

C program array print incorrect data

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

Upvotes: 0

Views: 588

Answers (5)

alle_meije
alle_meije

Reputation: 2480

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);
}

Upvotes: 1

poy
poy

Reputation: 10507

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.

Upvotes: 0

ffledgling
ffledgling

Reputation: 12140

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);

Upvotes: 0

sukhvir
sukhvir

Reputation: 5555

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

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70931

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.

Upvotes: 5

Related Questions