chopnhack
chopnhack

Reputation: 3

How to pass a variable value to an array in C

I am a novice programmer trying to understand arrays in C. Specifically I want to take the numeric value of a variable and feed it into an array. I tried to assign the value to the array, but failed with error messages. Can someone explain, simplistically, how to push a value into an array and then be able to just access the last digit?

My last attempt:

#include <stdio.h>
unsigned int TMR0 = 158;


int main(void)
{
unsigned int V = TMR0; 
unsigned int Random[2] = {V};
printf("%d \n" , *(Random+2));
return 0;

Thanks.

Upvotes: 0

Views: 289

Answers (2)

paddy
paddy

Reputation: 63461

You don't actually need an array to access digits of your number -- you just need math.

It's important to realise that "digit" implies a particular numeric base. In the computer, numbers are represented in binary. For convenience, they can be represented in our code using common bases: decimal, hexadecimal, and octal are the ones we generally use in languages like C.

So, to get the last digit in base 10, you would take the value modulo 10:

int val = 158;
int last_digit = val % 10;
printf( "%d\n", last_digit );

If you need to find digits other than the last, you can first perform integer division and then modulo:

int second_to_last_digit = (val / 10U) % 10;

Alternatively you can convert the number into a string, and then look at each character in that string. But I'm not going to go into that here, since it can be confusing to provide too much information to new programmers.

Upvotes: 1

Karthikeyan.R.S
Karthikeyan.R.S

Reputation: 4041

unsigned int Random[2];

Array will be declared with two positions.

Random[0] Random[1] // two accessible positions in that array.

When you are assigning the value to the array,

unsigned int Random[2] = { V} ;

Value will be stored in the first position of array. Random[0].

*(Random+2) will access the position Random[2]. Which is not accessible position for this array. It will lead to undefined behaviour.

Another thing is if you need to assign the values to both the position you have to do like this.

unsigned int Random[2] = {V,V} ;

To access the last element in your array,

*(Random+1) or Random[1]

May this link will help.

Upvotes: 2

Related Questions