How can I manipulate an Array? - c

I have an array
arr[]={7,5,-8,3,4};
And I have to update the same array to
arr[]={7,12,4,7,11};
my code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int sumArr(int *arr, int size);
void main()
{
int arr[] = { 7,5,-8,3,4 };
int i, size, res = 0;
printf("Enter Size Of The Array:");
scanf("%d", &size);
res = sumArr(arr, size);
for (i = 0; i < size; i++)
{
printf("%d\n", res);
}
}
int sumArr(int *arr, int size)
{
int i;
for (i = 0; i < size; i++)
{
arr[i+1]+= arr[i];
printf(" %d \n", arr[i + 1]);
}
return arr[i+1];
}
The output should be: 7,12,4,7,11
But in my code, the output is: 12,4,7,11,-858993449,58196502,58196502,58196502,58196502,58196502
Any hints?
I can use auxiliary functions for input and output arrays, will it help?

You have several mistakes in your code:
You need to stop the summing loop once i+1 reaches the end of the array
Your code knows the size; there is no need to read it from end-user
You need to print the value of res once, rather than printing it in a loop
You should consider moving the printing portion of the program into main from sumArray.
The modifications are very straightforward:
int sumArr(int *arr, int size) {
// Stop when i+1 reaches size; no printing
for (int i = 0; i+1 < size; i++) {
arr[i+1]+= arr[i];
}
return arr[size-1];
}
Printing in the main:
printf("sum=%d\n", res);
for (int i = 0; i < size; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
Demo.

Related

C array vs pointer in these examples

This question doesn't require any initial explanation, other that to show the examples.
Why does this work (prints the contents of array a):
#include <stdio.h>
int a[100];
void check(int **b)
{
int i;
for (i = 0; i < 100; i++)
printf("%d ", b[0][i]);
}
int main()
{
int *arr = a;
int i;
for (i = 0; i < 100; i++)
{
a[i] = i;
}
check(&arr);
return 0;
}
and this doesn't (compiles with onlinegdb c compiler, but prints nothing)?
#include <stdio.h>
int a[100];
void check(int **c)
{
int i;
for (i = 0; i < 100; i++)
printf("%d ", c[0][i]);
}
int main()
{
int i;
for (i = 0; i < 100; i++)
{
a[i] = i;
}
check((int**)&a);
return 0;
}
I understand that array is a special data type in C, but shouldn't casting it to a pointer type or assigning it to one be the same? Is there a way to make the second example work without the additional pointer?

"assignment makes integer from pointer without a cast"?

I'm really new to this. I've never done anything like this so I'm having issues with this code. I was given a template to write my code in separate functions like this, although I added the findPos one myself. I'm getting the "assignment makes integer from pointer without a cast" warning and also my max, min, sum, avg, and position of max and min are obviously not coming out to the right numbers. I was just wondering if anyone can lead me in the right direction.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int findMin(int arr[], int size);
int findMax(int arr[], int size);
int findSum(int arr[], int size);
int findPos(int arr[], int size);
int size;
int i;
int max;
int min;
int avg;
int sum;
int pos;
int main()
{
srand(time(0));
printf("Enter an integer: ");
scanf("%d", &size);
int arr[size];
max = findMax;
min = findMin;
pos = findPos;
sum = findSum;
avg = sum / size;
printf("max:%7d\tpos:%d\t\n", max, pos);
printf("min:%7d\tpos:%d\t\n", min, pos);
printf("avg:%7d\n", avg);
printf("sum:%7d\n", sum);
printf("\n");
printf(" Pos : Val\n");
printf("-------------\n");
for (i = 0; i < size; i++) {
arr[i] = (rand() % 1001);
printf("%4d :%6d\n", i, arr[i]);
}
return 0;
}
int findMin(int arr[], int size)
{
min = arr[0];
for (i = 0; i < size; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
int findMax(int arr[], int size)
{
max = arr[0];
for (i = 0; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int findSum(int arr[], int size)
{
sum = 0;
for (i = 0; i < size; i++) {
sum = sum + arr[i];
}
return sum;
}
int findPos(int arr[], int size)
{
for (i = 0; i < size; i++) {
pos = i;
}
return pos;
}
max = findMax;
min = findMin;
pos = findPos;
sum = findSum;
You're assigning function pointer, not return value, to integer variable. You have to do something like max = findMax(arr, size). Also in that case, you should assign values to arr before calling it.
There are a couple of issues with the code. Let me iterate through the same
Populating Data in Created Array
Since the data has to present the created array before performing any operations,
printf("\n");
printf(" Pos : Val\n");
printf("-------------\n");
for (i = 0; i < size; i++) {
arr[i] = (rand() % 1001);
printf("%4d :%6d\n", i, arr[i]);
}
this snippet should be reordered and moved above the function calls and just after the int arr[size];
Function Calls
All your functions, namely findMax,findMin,findPos,findSum is expecting two parameters
arr - array you have created
size - the size value read from scanf()
Assuming you want to store the return value from the function in the main int variables max,min,pos,sum,avg
the statements
max = findMax;
min = findMin;
pos = findPos;
sum = findSum;
should be replaced with function calls like
max = findMax(arr, size);
min = findMin(arr, size);
pos = findPos(arr, size);
sum = findSum(arr, size);
The Final Main code will be
int main()
{
srand(time(0));
printf("Enter an integer: ");
scanf("%d", &size);
int arr[size];
printf("\n");
printf(" Pos : Val\n");
printf("-------------\n");
for (i = 0; i < size; i++) {
arr[i] = (rand() % 1001);
printf("%4d :%6d\n", i, arr[i]);
}
max = findMax(arr, size);
min = findMin(arr, size);
pos = findPos(arr, size);
sum = findSum(arr, size);
avg = sum / size;
printf("max:%7d\tpos:%d\t\n", max, pos);
printf("min:%7d\tpos:%d\t\n", min, pos);
printf("avg:%7d\n", avg);
printf("sum:%7d\n", sum);
return 0;
}

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("]");
}

Function pointer in argument in C

I have to do an exercise where I have a certain numbers of functions and every function do a different thing like sort all the negative numbers from the array.
Moreover I have to create a function display with 3 argument pointers to an array, size of it and a name of a function which receives int and that the issue is int (Function pointer). I try to do this but this don't work and I don't know what to do in order to do correctly this exercise with a function pointer, because I don't understand that.
This is my code
int main (int argc, char **argv)
{
srand (time (NULL));
int arr[MAX_SIZE], second_arr[MAX_SIZE], i;
random_arr (arr);
display (arr, 20, negative_number (arr, second_arr));
system ("PAUSE");
return 0;
}
void random_arr (int *my_arr)
{
int i;
for (i = 0; i < MAX_SIZE; i++) {
*(my_arr + i) = i - 10;
}
}
int negative_number (int *arr, int *sort_arr)
{
int i;
for (i = 0; i < 20; i++) {
if (arr[i] < 0) {
sort_arr[i] = arr[i];
}
}
return sort_arr;
}
void diplay (int *arr, int size, int (*a_function) (int, int))
{
int i = 0;
for (i = 0; i < size; i++) {
printf ("%d\n", a_function);
}
}
It might be different from your intentions because your intentions is not clear.
but I think this would be helpful
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_SIZE 20
void random_arr (int size, int *my_arr);
int negative_number (int size, int *arr, int *sort_arr);
void display (int *arr, int size, int (*filter_function) (int in_size, int *in_array, int *out_array));
int main (void){
int arr[MAX_SIZE], second_arr[MAX_SIZE], i;
srand(time(NULL));
random_arr(MAX_SIZE, arr);
for(i = 0; i < MAX_SIZE; ++i)
printf("%d ", arr[i]);
puts("");
display (arr, MAX_SIZE, negative_number);
system ("PAUSE");
return 0;
}
void random_arr (int size, int *my_arr){
int i;
for (i = 0; i < size; i++) {
my_arr[i] = rand()%MAX_SIZE - MAX_SIZE/2;
}
}
int negative_number (int size, int *arr, int *sort_arr){
int i, j = 0;
for (i = 0; i < size; i++) {
if (arr[i] < 0) {
sort_arr[j++] = arr[i];
}
}
return j;//new array size
}
void display (int *arr, int size, int (*filter)(int in_size, int *in_array, int *out_array)){
int i = 0;
int *out = malloc(size * sizeof(*out));
int out_size = filter(size, arr, out);
for (i = 0; i < out_size; i++) {
printf ("%d\n", out[i]);
}
free(out);
}

crash on trying to reallocate a pointer using pointer to this pointer

I have a pointer to a pointer ("paths") and I want to reallocate each pointer (each "path"). But I get a crash. Generally I am trying to find all possible powers of a number, which one can compute for some amount of operations (e.g for two operations we can get power of three and four (one operation for square of a number, then another one either for power of three or four)). I figured out how to do it on paper, now I am trying to implement it in code. Here is my try:
#include <stdio.h>
#include <stdlib.h>
void print_path(const int *path, int path_length);
int main(void)
{
fputs("Enter number of operations? ", stdout);
int operations;
scanf("%i", &operations);
int **paths, *path, npaths, npath;
npaths = npath = 2;
path = (int*)malloc(npath * sizeof(int));
paths = (int**)malloc(npaths * sizeof(path));
int i;
for (i = 0; i < npaths; ++i) // paths initialization
{
int j;
for (j = 0; j < npath; ++j)
paths[i][j] = j+1;
}
for (i = 0; i < npaths; ++i) // prints the paths, all of them are displayed correctly
print_path(paths[i], npath);
for (i = 1; i < operations; ++i)
{
int j;
for (j = 0; j < npaths; ++j) // here I am trying to do it
{
puts("trying to reallocate");
int *ptemp = (int*)realloc(paths[j], (npath + 1) * sizeof(int));
puts("reallocated"); // tried to write paths[j] = (int*)realloc...
paths[j] = ptemp; // then tried to make it with temp pointer
}
puts("memory reallocated");
++npath;
npaths *= npath; // not sure about the end of the loop
paths = (int**)realloc(paths, npaths * sizeof(path));
for (j = 0; j < npaths; ++j)
paths[j][npath-1] = paths[j][npath-2] + paths[j][j];
for (j = 0; j < npaths; ++j)
print_path(paths[j], npath);
puts("\n");
}
int c;
puts("Enter e to continue");
while ((c = getchar()) != 'e');
return 0;
}
void print_path(const int *p, int pl)
{
int i;
for (i = 0; i < pl; ++i)
printf(" A^%i -> ", p[i]);
puts(" over");
}
I am not sure the problem resides with the call to realloc(), rather you are attempting to write to locations for which you have not created space...
Although you create memory for the pointers, no space is created (allocate memory) for the actual storage locations.
Here is an example of a function to allocate memory for a 2D array of int:
int ** Create2D(int **arr, int cols, int rows)
{
int space = cols*rows;
int y;
arr = calloc(space, sizeof(int));
for(y=0;y<cols;y++)
{
arr[y] = calloc(rows, sizeof(int));
}
return arr;
}
void free2DInt(int **arr, int cols)
{
int i;
for(i=0;i<cols; i++)
if(arr[i]) free(arr[i]);
free(arr);
}
Use example:
#include <ansi_c.h>
int main(void)
{
int **array=0, i, j;
array = Create2D(array, 5, 4);
for(i=0;i<5;i++)
for(j=0;j<4;j++)
array[i][j]=i*j; //example values for illustration
free2DInt(array, 5);
return 0;
}
Another point here is that it is rarely a good idea to cast the return of [m][c][re]alloc() functions
EDIT
This illustration shows my run of your code, just as you have presented it:
At the time of error, i==0 & j==0. The pointer at location paths[0][0] is uninitialized.
EDIT 2
To reallocate a 2 dimension array of int, you could use something like:
int ** Realloc2D(int **arr, int cols, int rows)
{
int space = cols*rows;
int y;
arr = realloc(arr, space*sizeof(int));
for(y=0;y<cols;y++)
{
arr[y] = calloc(rows, sizeof(int));
}
return arr;
}
And here is a test function demonstrating how it works:
#include <stdio.h>
#include <stdlib.h>
int ** Create2D(int **arr, int cols, int rows);
void free2DInt(int **arr, int cols);
int ** Realloc2D(int **arr, int cols, int rows);
int main(void)
{
int **paths = {0};
int i, j;
int col = 5;
int row = 8;
paths = Create2D(paths, col, row);
for(i=0;i<5;i++)
{
for(j=0;j<8;j++)
{
paths[i][j]=i*j;
}
}
j=0;
for(i=0;i<5;i++)
{
for(j=0;j<8;j++)
{
printf("%d ", paths[i][j]);
}
printf("\n");
}
//reallocation:
col = 20;
row = 25;
paths = Realloc2D(paths, col, row);
for(i=0;i<20;i++)
{
for(j=0;j<25;j++)
{
paths[i][j]=i*j;
}
}
j=0;
for(i=0;i<20;i++)
{
for(j=0;j<25;j++)
{
printf("%d ", paths[i][j]);
}
printf("\n");
}
free2DInt(paths, col);
getchar();
return 0;
}
The realloc() does not fail. What fails is that you haven't allocated memory for the new pointers between paths[previous_npaths] and paths[new_npaths-1], before writing to these arrays in the loop for (j = 0; j < npaths; ++j).

Resources