'C programming with pointers

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



Solution 1:[1]

"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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 marc_s