![]() |
[c]problem with arrays
I'm having a problem storing a value from an array of type char into an array of type int.
Code:
Code:
Given the array of characters: 1 0 1 What am I doing wrong? |
As far as I know (and that's not alot), you cannot just assign a variable of one type to a variable of another type. Which is probably why
Quote:
I'm just guessing here, but don't you need to parse the char variable to an int before you can assign the value to the iBinary array? |
Thats actually not a problem because char can be implicitly casted to int. They are both integer types, only the size is different and since int is bigger than char there's no type problem with the cast and the compiler does it automatically. There could be a signed/unsigned issue, but I think in most cases char and int are both signed by default, and at worst the compiler will issue a warning and still do the implicit cast.
Your problem is with the inner for loop in the function call. You don't need a loop there at all. Just initialize j to 0 before entering the (outer) loop, and when there's a successful test of cInputOld[i], assign to iBinary[j] and increment j, unless you're trying to do something other than what I'm thinking. Also, you should initialize the iBinary array or only print the values that were actually stored. |
Quote:
what your code currently does is every time there's a '1' or '0', it loops through iBinary[] and replaces every value, up to the size of cInputOld[], with the integer value for the character. since '1' was the last one in cInputOld[], it wrote 9 (size of cInputOld[]) 49's into iBinary[]. if you want it to set itself to 1 or 0, the integer, make sure to subtract the integer 48 from the value of the character. that'll get your numbers in line. only your numbers. |
Code:
/** 1 0 1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 I thought if I initialized the iBinary upfront: iBinary[13] = { -1 }; it should assign the value of -1 to all indices. btw thank you everyone for your help. |
What exactly are you trying to do?
Also use a switch statement instead of the if. It should be more efficient since it can use look up tables and then if you want to do more than just 0 and 1 for your digits you can change them all. Just do something like this: Code:
switch(cInputOld[i]) |
My guess is he wants to print out the binary form of each character. Normally, you could print that using a printf format, but the C standard doesn't require such a format conversion. Here's how to do it.
b.c: Code:
#include <stdio.h> Result: Code:
puck% gcc -Wall -o b b.c && ./b |
Thanks for getting me started, I came up with a solution to my problem:
Code:
|
All times are GMT -8. The time now is 02:09 AM. |
Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2025, vBulletin Solutions, Inc.
Search Engine Optimization by vBSEO 3.6.0 PL2
© 2002-2012 Tilted Forum Project