Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Phenomenon: Since Fabi is passed through the pointer parameter, the address of Fabi enters the function normally for the first time. The second time Fabi becomes an inaccessible address 0x384(Watcher), but it has not been changed by itself and passed to the function as const.
The fibonacci_search function uses the global variable Fabi instead of the Fabi parameter, so there is no problem.
It is precisely because the inaccessible address is accessed, a Segmentation fault is reported, and the program terminates.
#include <stdio.h>
#include <stdlib.h>
int fibonacci_search( const int* const F,int* a,int n,int val){
int low = 0, high=n-1,maxn = n-1;
int mid;
int k = 0;
while(maxn>F[k]-1)
k++;
for(int i=maxn;i<F[k]-1;i++)
a[i]=a[maxn];
int i=1;
while(low <= high){
mid = low + F[k-1] - 1; //mid = low + F[k] - 1;
printf("The %dth search value is:%d\n",i++,a[mid]);
if( val < a[mid]){
high = mid-1;
k = k-1;
}else if( val > a[mid]){
low = mid + 1;
k = k-2;
}else{
if(mid<=n)
return mid;
else
return maxn;
}
}
return -1;
}
int main(void){
int biarr[] = {0,1,16,24,35,47,59,62,73,88,99,102,304,758,777,801,900};
int amount = 15;
int* Fabi= (int*) malloc(sizeof(int)*amount);
Fabi[0]=0;Fabi[1]=1;
for(int i=2;i<amount;i++){
Fabi[i]=Fabi[i-1]+Fabi[i-2];
}
for(int i =5;i<17;i++){
int result = fibonacci_search(Fabi,biarr,17,biarr[i]);
if(result == -1)
printf("Can not find the result.\n");
else
printf("Find the Value,the Index is:%d\n",result);
}
return 0;
}
The picture
You have a (possible) overflow here:
for(int i=maxn;i<F[k]-1;i++)
a[i]=a[maxn];
How could you be sure that F[k]-1 is a valid bound for your array a?
OMG.
when change
int biarr[] = {0,1,16,24,35,47,59,62,73,88,99,102,304,758,777,801,900};
to
int biarr[50] = {0,1,16,24,35,47,59,62,73,88,99,102,304,758,777,801,900};
Its right.
Thanks to: When you debug, have you made sure that there's no out-of-bounds writes to any of the arrays? Some programmer dude's remind.
Its really a peculiar phenomenon!!!
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I was given code and I don't understand why the function returns -1. I feel that it is a typo. The code is given below:
int equilibrium(int array[], int size)
{
int sum = 0;
int left_sum = 0;
int i;
for (i = 0; i < size; i++) {
sum += array[i];
}
for (i = 0; i < size; i++) {
if (array[i] == sum - 2 * left_sum) {
return i;
}
left_sum += array[i];
}
return -1;
}
It looks like it uses -1 to mean "not found", it looks like a search function trying to find an index i where the condition in the innermost if is true.
equilibrium returns the equilibrium point of an array as an index in the array. When the array doesn't have an equilibrium point, the function returns -1 instead. It is used as followed:
int equilibrium_idx = equilibrium(somearrayvalue, somesize);
if( equilibrium_idx == -1 )
printf("It isn't balanced\n");
else
printf("The equilibrium index is %d\n", equilibrium_idx);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have tried to write a sorting function sort(int *buffer, int array[], int size) which works in a way similar to the insertion sort - it takes the first element from the array, sets it as the first element of the buffer and then checks whether or not the next value showing up in the array is greater than the last value stored in the buffer. If yes, it keeps swapping the two elements until everything is in its place. This is my minimal working example:
#include <stdio.h>
void sort(int *buffer, int array[], int size) {
for(int i = 0; i < size; i++) {
buffer[i] = array[i];
while(i >= 1 && buffer[i] < buffer[i-1]) {
int tmp = buffer[i-1];
buffer[i-1] = buffer[i];
buffer[i] = tmp;
printf("i = %d i: %d, i -1 : %d \n",i, buffer[i], buffer[i-1]);
i--;
}
}
}
int main(void) {
int array[3] = {4,3,2};
int buffer[3];
sort(buffer, array, 3);
for(int i = 0; i < 3; i++) {
printf("%d", buffer[i]);
}
}
However, the output of this program is 222
To be honest, I don't see how it's even possible that three identical elements got placed in the buffer.
What can have gone wrong?
You are using the same variable for the inner while cycle and for the outer for loop. Use a different variable and copy the value of i to it in each iteration of the for.
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 5 years ago.
Improve this question
When I'm running the program, the 2nd and the 3rd values being printed are garbage values, and I don't know why. I think it should be the numbers I've entered.
The code:
int main()
{
int a = 0, b = 0;
int * students = NULL;
int * size = &a;
int * studentscount = &b;
func1(students, size, studentscount);
return 0;
}
#include "Source.h"
int checkAllocation(void * ptr)
{
if (ptr == NULL)
return 1;
return 0;
}
int * doubleArr(int *arr, int size)
{
int * newArr = (int*)malloc(size * sizeof(int));
checkAllocation(newArr);
for (int i = 0; i < size; i++)
newArr[i] = arr[i];
size *= 2;
newArr = (int*)realloc(newArr, size);
checkAllocation(newArr);
free(arr);
return (newArr);
}
void func1(int *students, int *size, int *studentscount)
{
int num;
students = (int *)malloc(sizeof(int) * 2);
checkAllocation(students);
*(studentscount) = 0;
*(size) = 2;
printf("Enter students, to end enter a negative number.\n");
do
{
printf("Enter student number %d: ", *(studentscount)+1);
scanf("%d", &num);
if (num >= 0)
{
*(students + *(studentscount)) = num;
*(studentscount) += 1;
}
if (*(studentscount) == (*size))
{
students = doubleArr(students, *(size));
*(size) *= 2;
}
} while (num >= 0);
printf("******************\nArray size: %d\nNumber of students: %d\n******************\n", *(size), *(studentscount));
for (int i = 0; i < *(studentscount); i++)
printf("student #%d: %d\n", i + 1, *(students + i));
free(students);
}
Any suggestions to make the code print the values I entered and not the garbage values?
There are some issues you should probably work on, but the reason for garbage is very likely statement realloc(newArr, size), which considers only the count but not the size of datatype int. Hence, instead of doubling the array size, you are actually decreasing it; Consequently, realloc might give you back a different memory block where only portions of the previous one has been taken over; or some parts of the memory you have written values to have gone invalid. Anyway, you have a good chance here to loose your entered values. So - as pointed out by bluepixy, statement realloc(newArr, size*sizeof(int)) should solve the main problem.
Note further that statement realloc, when allocating memory at a different place, takes over the content of the former memory block and (in this case) frees the former block (cf. cppreference of realloc). So there is no need to transfer the data manually, there is particularly no need to first malloc and then realloc, and there is consequently no need for a separate free at the end. So the code of doubleArr could actually look like the following.
int * doubleArr(int *arr, int size) {
return realloc(arr,size*2*sizeof(int));
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have to write a C code that finds the smallest value in an array using recursion. I've already done it using the for loop, but recursion is trickier . Can someone help me??
The minimum of a single item array is that single item (base case or the termination condition).
The min of an array is the minimum of [the first item, the minimum from the rest (excluding the first item)]
Here is simple code for finding minimum value using recursion,
int rec(int a[],int n)
{
int min;
if(n==1)
return a[0];
else {
min=rec(a,n-1);
if(min<a[n-1])
return min;
else
return a[n-1];
}
}
void main()
{
int i,j,n,a[20];
printf("enter n :");
scanf("%d",&n);
printf("enter values : ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n%d",rec(a,n));
getch();
}
#include <stdio.h>
int minimum(int *a_s, int *a_e, int candidate){
if(a_s == a_e)
return candidate;
return minimum(a_s+1, a_e, *a_s < candidate ? *a_s : candidate);
}
int main(void){
int array[] = { 1,3,-2,0,-1};
printf("%d ", minimum(array+1, &array[sizeof(array)/sizeof(*array)], *array));
return 0;
}
After accept answer.
Below is a recursive solution that does not chew up the stack. Estimate max stack depth at O(ln2(n)). Other solutions look like the maximum stack depth is O(n).
int ArrayMin(const int a[], size_t n) {
if (n <= 1) {
if (n < 0) return 0; // Handle degenerate ArrayMin( ,0)
return a[0];
}
size_t nhalf = n / 2;
int left = ArrayMin(a, nhalf);
int right = ArrayMin(&a[nhalf], n - nhalf);
return left < right ? left : right;
}
Answered after 9 hours, we can assume homework due date is past.
Consider first element of the array is minimum.
Call the function by passing base address of the array and number of elements.
Check for any other number is less then the minimum value, if yes assign that value to minimum.
For every iteration increment the array address and decrement the no of elements!
Try this code-
#include<stdio.h>
int min;
int arrfun(int *arr,int n)
{
if(n){
if(*arr < min) // check any no is less than minimum.
min = *arr; // if yes assign it
}
else
return min; // when n becomes 0 it returns the minimum element
arrfun(++arr,--n); // recursive call
}
int main()
{
int arr[]={7,3,9,2,1,6};
min = arr[0]; // Taking first element is minimum
printf("minimum is: %d\n",arrfun(arr,6)); // call the function by passing address and no of elements in array
return 0;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm having trouble with arrays. I copied this code from a book:
#include <stdio.h>
#include <stdbool.h>
int main (void)
{
int p, i, primes[50], primeIndex = 2;
bool isPrime;
primes[0] = 2;
primes[1] = 3;
for (p = 5; p <= 50; p = p + 2) {
isPrime = true;
for (i = 1; isPrime && p / primes[i] >= primes[i]; ++i)
if (p % primes[i] == 0)
isPrime = false;
if (isPrime == true) {
primes[primeIndex] = p;
++primeIndex;
}
}
for (i = 0; i < primeIndex; ++i)
printf ("%i ", primes[i]);
printf ("\n");
return 0;
}
In particular, I'm having trouble understanding the difference between the primeIndex and the i variables. The primeIndex refers to the array number and i refers to the number placed into the array. Right?
primeIndex is the place where the next found prime is written in the prime array, and also the number of primes known so far. i is the index of the prime used for trial division. For each candidate, i loops from 1 (we don't need to try out primes[0] = 2 because only odd numbers are checked) to the index of the first prime larger than the square root of the candidate.