Filling an array with a pointer to the array - c

#include <stdio.h>
#include <time.h>
#define SIZE 20
#define MIN 0
#define MAX 100
void FillArray(int *array, int size);
void PrintArray(int *array, int size);
void BubbleSort(int *array, int size);
void SelectionSort(int *array, int size);
void Swap(int *x, int *y);
int main() {
int NumList[SIZE];
int *array;
array = NumList;
FillArray(array, SIZE);
PrintArray(array, SIZE);
}
void FillArray(int *array, int size) {
int i;
srand(time(NULL));
for (i = 0; i < size; i++); //<--- the K&R brace style would make this bug obvious!
{
*(array+i) = MIN + rand() % (MAX - MIN + 1);
}
}
void PrintArray(int *array, int size) {
int i;
for (i = 0; i < size; i++) {
printf ("%d\n", array);
array++;
}
}
This program seems to be outputting random integers (not withing min and max) in increasing order, and I want to know why it's not random all the way through.
Specifically in the FillArray function. It seems to not be filling correctly.

You have no body to this loop
for (i=0; i<size; i++);
When it ends, the next line
*(array+i) = MIN + rand() % (MAX - MIN + 1);
writes outside the bounds of the array.
Remove that semicolon...
for (i=0; i<size; i++) // ---> ;
There is also the matter of
printf ("%d\n", array);
which should be
printf ("%d\n", *array);

Related

Can't seem to understand why this array won't reverse in C

I'm having trouble understanding why my reverseArray function won't properly swap the values at the indices.
What I was going for was the last value just swaps with the first value all the way until i deprecates to 0. I believe something is wrong with the [(SIZE - i) - 1] but I can't seem to wrap around my head why.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MIN 0
#define MAX 100
#define SIZE 40
void fillArray(int arr[]);
int findWithRange(int arr[], int low, int high);
int findMaxInArray(int arr[], size_t arr_size);
void printArray(int arr[], size_t arr_size);
void reverseArray(int arr[]);
int main(void){
srand((unsigned)time(NULL));
int arr[SIZE], low, high;
fillArray(arr);
printArray(arr, SIZE);
puts("\n");
puts("\n");
reverseArray(arr);
printArray(arr, SIZE);
puts("\n");
}
void fillArray(int arr[]){
for (int i = 0; i < SIZE; i++){
arr[i] = rand() % (MAX + 1) + MIN;
}
}
void reverseArray(int arr[]){
int temp;
for (int i = SIZE - 1; i > 0; i--){
temp = arr[i];
arr[i] = arr[(SIZE - i) - 1];
arr[(SIZE - i) - 1] = temp;
}
}
Output (Bottom is "Reversed" Array):
Expected Output (similar):
The first clue I got was the output you got, you'll notice that only the first and last number got swapped but not the middle numbers. In your for loop of the reverse function you went too far. What you need to do is run half the for loop because the middle is where you start swapping the number back to their original places. So:
void reverseArray(int arr[]){
int temp;
for (int i = SIZE - 1; i > SIZE/2; i--){ // Changed code here
temp = arr[i];
arr[i] = arr[(SIZE - i) - 1];
arr[(SIZE - i) - 1] = temp;
}
}

Trying to write a program to fill an array with random numbers in C

My issue is that I am getting segmentation fault (core dumped) each time I try, I have yet to clean up my code, but I am stumped.
I must enter the values in with the compiler e.g "./filename 0 100" whereby 0 is min and 100 is max.
It must then fill the array of 10 elements with random numbers (0-100). I am so close, just can't fathom the main function.
Also, how can I print the array {0,1,2,3} in format "[0,1,2,3]" including the commas, without it looking like "[0,1,2,3, ]"
#include <stdlib.h>
#include <stdio.h>
int getRandom(int min, int max);
void fillArray(int data[], int size, int min, int max);
void printArray(int data[], int size);
int main(int argc, char *argv[]) {
int a;
int b;
if (argc>=3){
a = atoi(argv[1]);
b = atoi(argv[2]);
int arr[10];
printf("\t An array with random values from 0 to 100 \n");
fillArray(arr,10 ,a, b);
printArray(arr, 10);
} else {
printf("Incorrect number of arguments - please call with assignment min max\n");
}
return 0;
}
int getRandom(int min, int max) {
int result = 0;
int low = 0;
int high = 0;
if (min<max) {
low = min;
high = max+1;
} else {
low = max + 1;
high = min;
}
result = (rand() % (high-low)) + low;
return result;
}
void fillArray(int data[], int size, int min, int max){
int i;
for(i=min ; i < max+1; i++){
data[i] = getRandom(min,max);
}
}
void printArray(int data[], int size){
int i;
printf("[");
for(i=0; i<size; i++){
printf("%d,", data[i]);
}
printf("]");
}
I agree with #Steve Friedl that the main problem with your program lies in the fillArray function. There i should run from 0 to size.
As for your second question, testing whether you're printing the last number helps to suppress the unwanted comma:
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
printf("%d", data[i]);
if (i < size - 1)
printf(",");
}
printf("]");
}
If you prefer a more compact solution (although with an optimizing compiler there's not really a difference), you could write it as:
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
printf("%d%c", data[i], i < size-1 ? ',' : ']');
}
}
Also, in your main function, you should include a and b in your printing:
printf("\t An array with random values from %d to %d \n", a, b);
I believe this is blowing things up for you:
void fillArray(int data[], int size, int min, int max){
int i;
for(i=min ; i < max+1; i++){ // <-- HERE
data[i] = getRandom(min,max);
}
}
The calling function allocates 10 items in the arr array, and that's passed as the size parameter, but you're not using that parameter to limit filling up the array. If the max value is 100, then it's trying to fill one hundred slots instead of just ten.
for (i = 0; i < size; i++)
data[i] = getRandom(min,max);
should fix at least this issue.
EDIT: The comma thing, I prefer to add commas before the items unless this is the first. In this case it doesn't matter much, but it's more general, especially for variable-length lists where you don't know you're at the end until you get there. Augmenting the helpful response from #JohanC :
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
if (i > 0) printf(",");
printf("%d", data[i]);
}
printf("]");
}

C malloc, realloc. How to remove single element from array.

I've got a homework to create 2 functions add which adds element to dynamic array (what i've done) and remove which removes indicated element from that array. I have a problem with that 2nd function. I have no clue how to code it.
PS. I can't use memmove().
#include <stdlib.h>
#include <stdio.h>
void print_array(int *tab, int n);
void add(int x, int y, int *tab, int idx);
void remove_element(int *tab, int idx, int array_length);
int main() {
int *tab = malloc(24*sizeof(*tab));
int idx = 0;
tab[idx++] = 44;
tab[idx++] = 82;
tab[idx++] = 57;
tab[idx++] = 77;
printf("Before insert\n");
print_array(tab, idx);
idx++;
add(7, 0, tab, idx);
printf("After insert\n");
print_array(tab, idx);
free(tab);
idx--;
printf("After delete\n");
remove_element(tab, 3, idx);
print_array(tab, idx);
free(tab);
return(0);
}
void print_array(int *tab, int n) {
int i;
for (i = 0; i < n; i++) {
printf("t[%d] = %d\n", i, tab[i]);
}
}
void add(int x, int y, int *tab, int idx) {
int i;
for (i = idx; i > y; i--) {
tab[i] = tab[i-1];
}
tab[y] = x;
}
void remove_element(int *tab, int idx, int array_length) {
void *tmp = realloc(tab, (array_length - 1) * sizeof(int) );
array_length = array_length - 1;
tab = tmp;
}
About your array you can keep information about its size (eg iSize) and the number of elements in use (eg iUse). iUse<=isize, of course.
When you need to add an element but the array is too small (iUse==iSize), you increase its size, add the element and increment iUse.
When you remove an element, you just decrement iUse and, if you can't use memmov, make a loop to move al higher elements down.

C: Printing out the value and memory location of each element of an array using pointers?

I have generated a random array inside the main function, How can I properly print it out using a separate function and inside the function print out the value and memory location of each element of that array using pointers. Here is my code so far:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void printArray(int *pointertoArray, int *Size);
int main (void)
{
srand(time(NULL));
int array[10];
int *pointer = NULL;
for(int i = 0; i < size; i++)
{
array[i] = rand();
*pointer = array[i];
printArray(*pointer,size);
}
}
void printArray(int *pointerToArray, int *size)
{
int i = 0;
do
{
printf("\nValue %d = %p ",i,*pointerToArray);
i++;
}
while(i < size);
}
Here is what I am trying to achieve:
value 1 = 0x7fff0815c0e0
.....
value 10 = 0x7fff0815c0ec
int *size should be int size. You don't pass a pointer, and you don't need a pointer.
Actually, size_t size would be more appropriate.
The call to printArray should be located after the loop. You only want to print the array once.
printArray(*pointer, size); should be printArray(array, size);.
pointerToArray should be named array or pointerToInts.
The value of the element is pointerToArray[i], not i.
The address of the element is pointerToArray+i, not *pointerToArray.
The loop in printArray should be top-tested. (No reason for it to be bottom tested, so play it safe.)
main is declared to return an int, but doesn't.
We get,
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void printArray(int *array, size_t size);
int main() {
srand(time(NULL));
int array[10];
for (int i = 0; i < size; ++i) {
array[i] = rand() % 1000;
}
printArray(array, sizeof(array)/sizeof(array[0]));
return 0;
}
void printArray(int *array, size_t size) {
for (int i = 0; i < size; ++i) {
printf("Value # %p = %d\n", array+i, array[i]);
}
}
Alternative:
void printArray(int *pointerToInt, size_t size) {
for (; size--; ++pointerToInt) {
printf("Value # %p = %d\n", pointerToInt, *pointerToInt);
}
}

Segmentation Fault return in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Program compiles fine, but returns 'segmentation fault' when ran. Please help. thanks. Ignore the other three functions. The program should Fill an array and the print the value in the array, using pointers and pointer arithmetic
#include <stdio.h>
void FillArray ( int *array, int size );
void PrintArray ( int *array, int size );
//void BubbleSort ( int *array, int size );
//void SelectionSort ( int *array, int size );
//void Swap ( int *x, int *y );
#define SIZE 20
int main (void)
{
int NumList [SIZE];
FillArray(NumList, SIZE);
PrintArray (NumList, SIZE);
}
void PrintArray (int *array, int size)
{
int i;
for (i=0; i<100; i++)
{
printf("%d \t", *(array+i));
}
}
void FillArray(int *array, int size)
{
int i;
srand(time(NULL));
for (i=0; i<100; i++)
{
*(array+i)= rand()%101;
}
return;
}
Your array contain only 20 entries but you tried to access invalid entries whose indexes were from 20 to 99.
You are trying accesing out-of-bound elements. Here is a quick fix:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 100
void FillArray ( int *array, int size );
void PrintArray ( int *array, int size );
int main (void)
{
int NumList [SIZE];
FillArray(NumList, SIZE);
PrintArray (NumList, SIZE);
}
void PrintArray (int *array, int size)
{
int i;
for (i=0; i<100; i++)
{
printf("%d \t", array[i]);
}
}
void FillArray(int *array, int size)
{
int i;
srand(time(NULL));
for (i=0; i<100; i++)
{
array[i] = rand() % 101;
}
}
You are trying to access out-of-bound elements. Here is the right way to do it.
Although you pass size of array as another argument, instead of using it, you're using a larger size of 100 which is hard coded.
#include <stdio.h>
void FillArray ( int *array, int size );
void PrintArray ( int *array, int size );
#define SIZE 20
int main (void)
{
int NumList [SIZE];
FillArray(NumList, SIZE);
PrintArray (NumList, SIZE);
}
void PrintArray (int *array, int size)
{
int i;
for (i=0; i < size; i++)
{
printf("%d \t", *(array+i));
}
}
void FillArray(int *array, int size)
{
int i;
srand(time(NULL));
for (i=0; i < size; i++)
{
*(array+i)= rand()%101;
}
return;
}

Resources