Decrementing an array from last element in C - 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.

Related

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 - Int Array to Integer with Mixed Digit Numbers

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

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.

array pointer (declare and defined in same line gives garbage value while in different line works perfectly fine)

I am using turbo c
when I declare and define the pointer k diffrently it gives the warning "nonportable pointer conversion " and the outcome for *k shows as garbage
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,*k;//declaration
int a[3][5] = {
{ 1, 2, 3, 4, 5 },
{6, 7, 8, 9, 10 },
{ 11, 12, 13, 14, 15 }
}; *k = &a ; //defination
clrscr();
printf("%d\n",*k);//garbage value
printf("%d\n",*(k+2));//garbage value
printf("%d\n",*(k+3)+1);//garbage value
printf("%d\n",*(k+5)+1);//garbage value
printf("%d\n",++*k);//garbage value
getch();
}
where as when define and declare pointer k in same line it gives the result
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
int a[3][5] = {
{ 1, 2, 3, 4, 5 },
{ 6, 7, 8, 9, 10 },
{ 11, 12, 13, 14, 15 }
}, *k = &a ;
clrscr();
printf("%d\n",*k); //1
printf("%d\n",*(k+2)); //3
printf("%d\n",*(k+3)+1); //5
printf("%d\n",*(k+5)+1); //7
printf("%d\n",++*k); //2
getch();
}
this problem is taken from "letusC".
Your response will be greatly appreciated!!
In first code, after declaration:
*k = &a ; //defination
Causes undefined behavior because k is uninitialized, pointing to a garbage location.
You should correct it as k = *a;
Whereas in second code you assign address at the time of declaration.
First, the type of &a is int(*)[3][5] and type of a is int(*)[5]. Type of *a is int[5] that can easily decays int int*
Second, the type of kis int* (and *k type is int) For expression *k = &a you may getting warning in both codes.
To assign address of first element in 2-D array; check following:
First-Code:
int *k;
int a[3][5] = {..........};
k = *a;
Check working code #codepade
Second-Code:
int a[3][5] = {.........}, *k = *a;
Check working code #codepade
To understand it read:
What does sizeof(&array) return? and
What does the 'array name' mean in case of array of char pointers?
int *k = &a; is the same as int *k; k = &a;, not int *k; *k = &a;.

Modifying an integer in an array of integers

If I have a an array of ints, how could I directly edit each int?
int i = arr + 1; // Getting the integer in pos 1
i is just a copy, correct? If I set i = 4, then arr + 1 would still be 1.
Would this work?
int *i = &(arr + 1);
*i = 4;
You should use the array operators:
int i = arr[1];
arr[1] = 4;
Change your code to this:
int *i = arr + 1;
*i = 4;
and it will work. Arrays in C are just pointers to first element in the array.
So this arr + 0 will give address of first element in array and this arr + 1 is an address of second element.
You've got:
int arr[4] = {0, 1, 2, 3};
Want to edit it further?
arr[0] = 42;
// arr[] = {42, 1, 2, 3};
Want to change all of them at once? There's:
for(int i = 0; i < 4; ++i)
arr[i] = i * 2;
// arr[] = {0, 2, 4, 6};
And don't forget memset()!
memset(arr, 42, 4);
// arr[] = {42, 42, 42, 42};
Want to change everything but the first element to 7?
memset(&arr[1], 7, 4 - 1);
// arr[] = {42, 7, 7, 7};
Would you like to know somethin' about pointers? (Here's a more useful link.)
See this? (If you can't, please stop reading this. Thanks!)
int *ptr = &arr[1];
It's equivalent to:
int *ptr = arr + 1;
Which is also equivalent to:
int *ptr = arr;
ptr = ptr + 1;
OK, now that we've got that down, let's show you a more efficient for-loop than the one I did above:
int *ptr = arr;
for(int i = 0; i < 4; ++i)
{
*ptr = i << 2;
// i * 2 == i << 2
++ptr;
}
// arr[] = {0, 2, 4, 6};
Not that you should code like that; the compiler will handle it for you, most likely.
Would you like another answer in the form of a series of questions?
Array indexing operators can do what you need.
arr[3] = 101; //assignment to array
int x = arr[37]; //get value from array
etc.
No need for for that memory arithmetic here..

Resources