C programming with pointers - arrays

Write a program that creates a random array of 20 integers with a pointer that initially points to the first element of the array. The program will have a while loop that allows the user to do any of the following:
print the array of numbers with the pointed to number highlighted in some way
move the pointer left or right a certain number of items in the array
change the value of the pointed to number
quit the program
All the changes to the list of numbers must be done with pointers (not by referencing the array index),
I have this to start off which is just setting up the array
#include <stdio.h>
#include <stdlib.h>
int main{
int array[20];
for(int i=0; I<20;i++){
array[I]=rand() % 100;
}
int pointer=&array[0];
int i=0;
return 0;
}
I would really appreciate the help

"with a pointer that points to the first element of the array"
Basically means you need to dynamically allocate memory. A memory block that is allocated always return a pointer to the first element of the array:
int* array = calloc(sizeof(int)*20);
// Allocate memory for 20 integers ^
Now you have an array of 20 integers and array points to it's first element. Then, if we don't actually want to reference the index.
*(arr+1)
Will give you the value of the second element since it evaluates to arr[1].
To print them using a while loop, use an integer to keep track of the current index and while(array+index) print it and increment index.
This is so because memory of a computer is like a street with different houses with an integral number along it.

Related

How do you get the ending address of an array in memory? C programming

If I have an address in memory for the start of an integer array, how do I figure out the end address of the array?
For example, if an array started at 0xFF000000 how would you return the address where the array ends?
given an address for an array of integers, you need to know how many are in the array since an integer can be zero. in other words without a delimiter indicated the end of the array, there is no way to know how many values were ACTUALLY stored in the array.
a basic heap array should at least have a second variable storing the number of elements. how else was it allocated right?
int nElements = 10;
int *pInts = (int*)malloc(nElements * sizeof(int));
int *pEndOfArrayAddress = pInts + (nElements-1);

How does for loop assignment work with the initializer variable in C?

So from what I know in C, anything that is referenced must be stored in memory somewhere.
Variables stored in the heap can surpass its lifetime past its function call.
But here is a trivial example of an integer defined within a for loop, whose values are referenced at some point by an array outside of it.
If we printed out the array, we would get 0,1,2...7.
Where are these individual integers being stored? If every array index was referencing
the same "int i", then they would all be the same number. But if each int was it's own
individual memory cell, this would imply all the ints are saved onto memory at some point?
int main(){
int arr[8];
for (int i = 0; i<8; i++){
arr[i] = i;
}
return 0;
}
The values are stored into the array arr.
In the line int arr[8] you are saying "Reserve enough memory to store eight integers". Then when you enter the loop, you are assigning the value from the loop counter i into each of those locations. After this assignment operation it doesn't matter what the value is i is, because the value is already in the arr array. In the example you posted, nothing is accessing the value i outside the scope of the loop.

Print Array from pointer

Hello guys I have a question,
I have an array with 10 elements and a function which returns me a pointer to a randomly chosen element in the array. Now I want to print the array from this element the pointer points to, how can I do that.
Example:
Array: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Pointer points to Element 6.
I want to print: 6, 7, 8, 9, 10
Code looks like this in C:
int* randomElement(int* array, int size) {
int* pointer = NULL;
int randomNumber = 0;
randomNumber = rand() % size;
*pointer = *(array + randomNumber);
return pointer;
}
int main(void) {
int size = 10;
int array[size];
int* pointer = NULL;
srand(time(NULL));
pointer = randomElement(array, size);
/* Want to print the array from this element here */
return EXIT_SUCCESS;
}
You can't.
By only knowing a random element in an array (i.e. having a pointer to one element), you can't print the entire array using that pointer.
You need at least two other data:
1) Length of the array (which you seem to indicate always 10.)
2) The position of the element within the array for which you have a pointer. So that you can calculate, from that position, how many elements before and after are available. (Basically determining array boundaries).
After you edit, the answer remains the same. But your code has problems:
1) You are not filling the array with values. So their values are indeterminate and accssing them is undefined behaviour.
2) You never set pointer to point to an element of the array in randomElement() and the function returns NULL. you are dereferencing NULL (pointer). Again, this will lead to undefined behaviour.
3) You should use size_t for representing array size instead of int.
I will not comment on your code, that is already done. I'll anwer the original question instead. Blue Moon says "You can't", but you can if you wish. You can always do a sequential lookup in any table, if your list of values is terminated with what is called a sentinel value. That is a special value which is known in advance not to belong to the collection of normal data, and thus can be used to flag the end of the sequence, for instance a negative value if all normal data are known to be positive.
For a sequence of n non-negative integers stored in an array of n+1 elements, we can store array[n]= -1 as a sentinel after populating the first n elements with normal data. Then start at a random position in the data sequence and read until the end, with something like
// -- we assume pointer p is an initialized int* that
// satisfies the condition array <= p < array + n
// AND that array[n] is negative.
for( ; *p >= 0; ++p ){
// do something useful with *p
}
Terminating a sequence with a sentinel is a well known general technique and you'll find it in any book on algorithms. You can use it with arrays and with linked lists. In your case you must make sure that the element following the last element you wish to access in the array is a sentinel and that the random choice has not selected the sentinel (if n is the length of the sequence, then rand() % n will give you a correct offset; pointing to a sentinel would not harm, but the for loop would terminate immediately). The size of the allocated array has to be at least n+1, that is the maximum number of data elements you need, plus one for the sentinel.
By the way, in C the last element of an array is not array[size] but array[size-1]. There is no bounds checking on array access when bumping a pointer in C, that's up to you, as you will learn sooner or later from crashing programs. To get rid of confusion between pointers and referenced values you can read the instructive answers to "What exactly is a C pointer if not a memory address?", here at Stackoverflow.
The usual way to use a pointer to iterate over an array where you know the size is:
for (p = array; p != array + size; ++p)
In your case you are initializing p differently but the rest of the loop can stay the same:
for ( ; pointer != array + size; ++pointer )
{
printf("%d\n", *pointer);
}
Of course it is also possible to use an integer index instead of a pointer (where you find the initial index by doing pointer - array).
Note that your randomElement function is currently implemented wrongly. It writes through a null pointer. Instead, what you want to do is to form a pointer to a randomly-selected element and return that pointer, without dereferencing. (i.e. take the *'s out of the line before the return).

Why my 2D array is not functioning right?

I am newbie in C programming.I want to print 2 as my first element is 2 in the 2D array.But as i knew that n holds the first address of the array so *n should print the first element that is 2.My code
‪#‎include‬ <stdio.h>
int main()
{
int n[3][3]={2,4,3,6,8,5,3,5,1};
printf("%d\n",*n);
return 0;
}
why it is printing an address.Can anyone explain it to me??
A 2d array is just an array of arrays, so *n is actually the first subarray, to print the first element of the first subarray:
printf("%d\n", **n);
Or this is simpler and more clear:
printf("%d\n", n[0][0]);
You need to declare your array like this:
int n[3][3]={{2,4,3},{6,8,5},{3,5,1}};
Note that the first [3] isn't necessary (but there's nothing wrong with specifying it). By the way, if you enable warnings, e.g. with gcc -Wall, the compiler will warn that there are missing braces in your initialiser.
Then to print the first value you can use:
printf("%d\n",n[0][0]);
Or, if you prefer:
printf("%d\n",*n[0]);
You have an array or arrays, so this takes the zeroth element (which is an array), then dereferences it to get the zeroth value.
I think that you got some warning on %d because you are not tried to print the value - just the address only.
For a 2D array, to get any value, you need to dereference twice. i.e **n.
*n is also suitable, but for a 1D array.
Here you can use either **n, *n[0] or n[0][0] instead of *n.
If n would have been an array of integers, *n would have printed the first integer, as you are expecting.
But n is not that. Is a 2-dimensional array. One way of looking at it would be: an array of arrays. So in fact *n is an array.
If you have an 1D array-
int n[9]={2,4,3,6,8,5,3,5,1};
printf("%d\n",*n);
Because If you dereference the 1D array it will fetch the element. Now It will print 2.
But
int n[3][3]={2,4,3,6,8,5,3,5,1};
It is a 2D array so you need to dererence two times. If you dererence one time it will fetch the address of the array only. n, n[0], *n, &n, &n[0] all will represent the starting address of it.
Try -
printf("%d\n",**n);
or
printf("%d\n",n[0][0]);

dreferencing 2 d array

Please look at this peice of code :-
#include<stdio.h>
int main()
{
int arr[2][2]={1,2,3,4};
printf("%d %u %u",**arr,*arr,arr);
return 0;
}
When i compiled and executed this program i got same value for arr and *arr which is the starting address of the 2 d array.
For example:- 1 3214506 3214506
My question is why does dereferencing arr ( *arr ) does not print the value stored at the address contained in arr ?
*arr is type integer array of length 2, so it shares the same address as arr. They both point to the beginning of their arrays, which is the same location.
in C, a 2d array is not represented in memory as an array of arrays; rather, it is a regular 1d array, in which the first given dimension is needed in order to calculate the right offset within the array at execution time. This is why in a multi-dimensional array you always need to specify all the dimensions except the last one (which is not required); for example, if you declare an array like
int a[2][3][4];
the array would be represented in memory as a single array of 2*3*4 elements in total. Trying to access the element at position (i,j,k), will actually be translated into accessing the element 3*i+4*j+k in the plain array. In some sense, the initial dimensions are needed to know where to put "row breaks" in the 1d array.

Resources