C - Int Array to Integer with Mixed Digit Numbers - c

I need to convert an integer array of size 4 into an int. I've seen solutions for int arrays that look like {1, 2, 3, 4} turn into 1234, and I've also seen ones where an array like {10, 20, 30} would turn into 102030. However, my problem is that I'll have an array that might look like {0, 6, 88, 54} and the solutions I previously mentioned only work on arrays with ints of the same type {e.g all one digit or all two digit}.
What should I do to solve this?
My expected output from the {0, 6, 88, 54} array would be 68854.
Examples An output with zeros in the middle should keep them, i.e. {6, 0, 0, 8} would be 6008 but {0, 6, 0, 0, 8} by default would still be 6008 in int form. I need this in an int but I wouldn't mind having a string intermediate.

You could do something like this:
int res = 0;
int nums[4] = {1, 4, 3, 2}
int i = 0, temp;
for (i = 0; i < 4; ++i) {
temp = nums[i];
do {
res *= 10;
} while ((temp /= 10) > 0);
res += nums[i];
}

What about this solution?
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int arr[] = {0, 6, 88, 54};
char buffer[1000] = { 0 };
for(size_t i = 0; i < sizeof arr / sizeof *arr; ++i)
sprintf(buffer, "%s%d", buffer, arr[i]);
int val = strtol(buffer, NULL, 10);
printf("%d\n", val);
return 0;
}
int prints 608854.

a neat solution would perhaps be to print to a string then convert the string back to an integer
char dummy[100];
int answer;
int input[4];
....
sprintf(dummy,"%d%d%d%d",input[0],input[1],input[2],input[3]);
answer=atoi(dummy);
the sprintf prints your integers into a string
the atoi converts the string into your integer, and it should be able to handle a 0 at the front.
full program
#include <stdio.h>
#include <stdlib.h>
int main()
{
char dummy[100];
int answer;
int input[4]={3,4,0,345};
sprintf(dummy,"%d%d%d%d",input[0],input[1],input[2],input[3]);
answer=atoi(dummy);
printf("%d\n",answer);
return 0;
}

Related

how to slice an array in c

I am wondering if it is possible to get part of an array in c, with list slicing. In python it van be done in de next code. I like to do this in c.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = a[3:5]
print(b)
Output: [4, 5]
You can use a struct as an array wrapper in the slice function. This way you can return the extracted slice from the function without bothering with malloc and free for dynamic memory allocation. Here's a basic outline.
#define MAX 100
typedef struct{
int myarr[MAX];
int mysize;
} wrapper;
wrapper slice(const int* arr, int size, int include, int exclude) {
wrapper result = { .myarr = {0}, .mysize = 0 };
if (include >= 0 && exclude <= size) {
int count = 0;
for (int i = include; i < exclude; i++) {
result.myarr[count] = arr[i];
count++;
}
result.mysize = exclude - include;
return result;
}
else {
printf("Array index out-of-bounds\n");
result.mysize = -1;
return result;
}
}
This can then be called on any array as follows:
int source[10] = {0,1,2,3,4,5,6,7,8,9};
wrapper s = slice(source, 10, 5, 10);
It will take quite a bit more work to implement the full Python slice functionality, though (here there's no third term to set the step size, nor are the various negative values implemented).
Well, you could start with something like the following:
// Get half-open range of values from array (includes first index,
// excludes last). Parameter 'source' is the source array, 'from'
// and 'to' are the range ends, and `target` is the destination
// buffer. If you provide buffer, make sure it's big enough. If
// you pass in NULL, a buffer will be allocated for you.
// Will return buffer address or NULL if either range is invalid
// or memory could not be allocated.
int *sliceIntArray(int *source, int from, int to, int *target) {
// Invalid, return null.
if (to <= from) {
return NULL;
}
// Only allocate if target buffer not given by caller.
if (target == NULL) {
target = malloc((to - from) * sizeof(int));
if (target == NULL) {
return NULL;
}
}
// Copy the data and return it.
memcpy(target, &(source[from]), (to - from) * sizeof(int));
return target;
}
This lets you pass in a buffer if you already have it, or it will allocate one for you if you don't (which you will need to free() at some point):
int naturals[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int slice1[2];
sliceIntArray(naturals, 3, 5, slice1);
// Use slice1 for whatever nefarious purpose you have :-)
int *slice2 = sliceIntArray(naturals, 3, 5, NULL);
// Use slice2 similarly, just make sure you free it when done.
free(slice2);
No, you can't.
You can create a new array and copy it, though:
int src[10] = { ... };
int dest[3];
memcpy(dest, src + 3, sizeof(src[0]) * 2);
In a short simple function:
int* slice(int a[], size_t start, size_t end)
{
return memcpy(malloc(sizeof(int)*(end-start)), a+start, sizeof(int)*(end-start));
}
Example usage:
#include <stdio.h>
int main(void) {
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *b = slice(a,3,5);
for(int i=0; i<2; ++i)
{
printf("b[%d] = %d\n", i, b[i]);
}
return 0;
}
Output:
b[0] = 4
b[1] = 5

Assign an array to array in struct

I'm trying to assign an array to one of the fields of a typedef struct and I can't find a way to do it practically.
I've searched for this problem but all I seem to find is answers for char * arrays which is not what I'm looking for, I'm just trying to assign an array to an int array, and looking for a practical way for the code below to work without having to initialize all the variables in the struct (they will be initialized later, but I just want to set the array variable):
typedef struct {
int array[5];
int number;
} Rot;
Rot RA;
void config()
{
RA.array = {1, 2, 3, 4, 5}; //This returns an "expected expression before "{"" error
int arr[5];
int i;
for (i = 0; i < 5; i++)
{
arr[i] = i + 1;
}
RA.array = arr; //I understand why this fails, but I need to do this in a practical way
}
Please assume that config is called later and the struct and RA are all accessible to it.
RA.array = {1, 2, 3, 4, 5};
memcpy(RA.array, (int[]){1, 2, 3, 4, 5}, sizeof RA.array);
RA.array = arr;
memcpy(RA.array, arr, sizeof arr); // better: sizeof RA.array
You can use memcpy as shown in another answer. Or alternatively, copy the whole struct and not just the array, using a temporary variable in the form of a compound literal:
RA = (Rot) { {1, 2, 3, 4, 5}, 0 };
This is possible because while C doesn't allow run-time assignment of arrays, it does allow it of structs.
You can use memcpy as shown in another answer, or copy the whole struct as shown in another answer (although your question states that you just want to set the array, not the remainder of the struct).
Another option is to embed just the array into another struct:
typedef struct {
int elem[5];
} RotArr;
typedef struct {
RotArr arr;
int number;
} Rot;
Then you can access element i of the array in Rot RA as RA.arr.elem[i]. Also, you can assign values to a whole RotArr object. The remainder of your code could look something like this:
Rot RA;
void config(void)
{
RA.arr = (RotArr){{1, 2, 3, 4, 5}};
RotArr arr;
int i;
for (i = 0; i < 5; i++)
{
arr.elem[i] = i + 1;
}
RA.arr = arr;
}
Note that (RotArr){{1, 2, 3, 4, 5}} is a compound literal value of RotArr type. It could also be written as (RotArr){ .elem = {1, 2, 3, 4, 5} } or (RotArr){ .elem = { [0] = 1, [1] = 2, [2] = 3, [3] = 4, [4] = 5 } } to be absolutely clear which parts of the compound literal are being set explicitly (any remaining parts will be set to 0), but since it only has a single member, these forms of the compound literal value are a bit over-the-top.
The following works according to C syntax. Not sure this is what you wanted.
#include <string.h>
#include <stdio.h>
typedef struct {
int array[5];
int number;
} Rot;
Rot RA = {{1,2,3,4,5}};
void main()
{
RA = (Rot) {{5, 6, 7, 8, 9}};
int arr[5];
int i;
for (i = 0; i < 5; i++)
{
arr[i] = i + 1;
}
memmove(RA.array, arr, sizeof(RA.array));
// OR
int l = sizeof(arr)/sizeof(arr[0]);
for(int i =0 ; i < l ; ++i) {
*(RA.array + i) = *(arr + i);
printf("%d\n",RA.array[i]);
}
}
Moreover, use memmove since that allows memory overlap.

C program to compute length of array

I'm learning C, and tried writing a function that, given an array of integer, returns the length of the array. Here is my code:
#include <stdio.h>
int length_of_array(int array[])
{
int length = 0;
int i = 0;
while (array[i] != '\0') {
length += 1;
i += 1;
}
return length;
}
int main()
{
int test_array[] = {1, 2, 3, 4, 5};
printf("%d\n", length_of_array(test_array));
return 0;
}
However, when I compile this code and run it, I says that the length of the array passed in is 14. Does anyone know what could be the problem here?
Strings in C are NUL-terminated. Arrays are not (unless you explicitly do it yourself). The size of array is just the size of array: if allocated as a constant, you can find out the size with sizeof operator. If all you have is a plain pointer, you need to remember the size - there is no way in C to get it once you forget it.
#include <stdio.h>
int main() {
int test_array[] = {1, 2, 3, 4, 5};
int *test_ptr = test_array;
printf("%lu\n", sizeof(test_array) / sizeof(*test_array)); // correct
printf("%lu\n", sizeof(test_ptr) / sizeof(*test_ptr)); // incorrect
return 0;
}

Decrementing an array from last element in C

I want to decrement an array from last element in C. I first wrote the following code to increment an array from the first element:
#include<stdio.h>
int x[11] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *pointer, count;
int main (void) {
pointer = x;
for (count = 0; count < 11; count++)
printf("%d\n", *pointer++);
return 0;
}
This works fine. But then I tried to decrement the elements by modifying the code to this:
#include<stdio.h>
int x[11] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *pointer, count;
int main (void) {
pointer = x[10];
for (count = 0; count < 11; count++)
printf("%d\n", *pointer--);
return 0;
}
But of course I am doing something wrong. I'd appreciate it very much if you could help me to understand my mistake.
You have two options which are equivalent.
pointer = &x[10];
pointer = x + 10;
Either will achieve the effect of making the pointer point at the 10th element of x.
pointer = x[10]; should be pointer = &x[10];.
You're setting pointer to the integer value x[10]. What you want to do is set pointer to the address of the last element in x.

How to determine number of elements that are in a array in C

i'm new learning the C Languange.
I want to know the number of elements that are in a array for example
int MyArray[80] = {50, 845, 584};
n = sizeof(MyArray)/sizeof(MyArray[0]); // This will give me 80.
But I only want the number of elements that are inside of {}, As i initialized above it has 3 elements (50, 845, 584), so how do i count them by code?
Another question:
How do i create an empty array so i can add elements by myself and print all elements with a for loop, I've tried this:
int i;
int MyArray[80] = {};
MyArray[0] = 50;
MyArray[1] = 584;
MyArray[2] = 784;
for(i=0; i<=sizeof(MyArray); i++){
printf("Array Element[%d] is: %d", i, MyArray[i]);
}
But this doesn't seem to work, any help? Thanks
EDIT: i fixed it by doing the following code found in another post:
#include <stdio.h>
#define NUM_ELEMS(a) (sizeof(a)/sizeof 0[a])
main() { int i; int numbers[] = {2, 3, 5, 7, 11, 13, 17, 19, 85};
int AllElements = NUM_ELEMS(numbers);
for(i=0; i<AllElements; i++){
printf("Element[%d] in array is: %d \n", i, numbers[i]);
}
}
If you initialize an array with fewer elements than the array is declared to hold, the remaining elements will be default-initialized. For integers, this means that they will be zeroed.
Assuming you have no zeroes in your initialization list, then, you can check how long the initialization list was by checking for the first zero in the array (up to the length of the array).
Alternately, if the array size should just be constant, you should specify the size as [], which makes it exactly as long as the initialization list and no longer.
I only want the number of elements that are inside of {}
Try
size_t n = sizeof (int[]){50, 845, 584} / sizeof (int);
An ugly way using the preprocessor:
#include <stdio.h>
#define NARGS_SEQ(_1,_2,_3,_4,_5,_6,_7,_8,N,...) N
#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1)
#define init_array(arr, ...) NARGS(__VA_ARGS__); arr = {__VA_ARGS__}
int main(void)
{
int n = init_array(int my_array[80], 50, 845, 584);
printf("%d\n", n);
return 0;
}
Is expanded to:
int main(void)
{
int n = 3; int my_array[80] = {50, 845, 584};
printf("%d\n", n);
return 0;
}
Output:
3
Note that this version is limited to N elements in the initializer.

Resources