Memory can't be read when shortest function is run - c

I had a bunch of problems with this program but looks like this might be inches away from completion and I was hoping someone could tell me what the hell's wrong with the blasted thing!
#include <stdio.h>
#include <string.h>
#define SIZE_OF_STRING 21
void displayMenu(void);
void readArray(char [][SIZE_OF_STRING], int);
void printArray(char [][SIZE_OF_STRING], int);
int shortestArray(char [][SIZE_OF_STRING], int);
int smallestArray(char [][SIZE_OF_STRING], int);
void sortArray(char [][SIZE_OF_STRING], int);
int main(void)
{
int position, n = 0; /* all local to main */
char select[10]; /* select is a string */
char array[1000][SIZE_OF_STRING];
displayMenu();
scanf("%s", select); /* read first selection */
while (strcmp(select, "exit") != 0) /* while not exit */
{
if (strcmp(select, "read") == 0)
{
printf("How many names?");
scanf("%d", &n);
n++;
printf("Enter %d names", n - 1);
readArray(array, n);
}
else if (strcmp(select, "display") == 0)
{
printArray(array, n);
}
else if (strcmp(select, "shortest") == 0)
{
position = shortestArray(array, n);
printf("Shortest name is %s in position %d\n", array[position], position + 1);
}
else if (strcmp(select, "lowest") == 0)
{
position = smallestArray(array, n);
printf("Lowest name is %s in position %d\n",
array[position], position + 1);
}
else if (strcmp(select, "sort") == 0)
{
sortArray(array, n);
}
else
{
printf("INVALID SELECTION");
}
displayMenu();
scanf("%s", select); /* read next selection */
} /* end while */
}/* end main */
void displayMenu(void)
{
puts("Menu selection");
puts("Enter read to read names");
puts("Enter display to display names");
puts("Enter shortest for shortest name");
puts("Enter lowest for lowest names");
puts("Enter sort to sort names");
puts("Enter exit to exit\n");
}
void readArray(char a[][SIZE_OF_STRING], int n)
{
int i;
printf("\ntype one string per line\n");
for (i=0; i<n; i++)
{
gets(a[i]);
}
}
void printArray(char a[][SIZE_OF_STRING], int n)
{
int i;
printf("\ntype one string per line\n");
for (i=0; i<n; i++)
{
puts(a[i]);
}
}
int shortestArray(char a[][SIZE_OF_STRING], int n)
{
int i;
int chag = 0;
int position;
while (a[i] != '\0')
{
if (strlen(a[i]) < strlen(a[i-1]))
{
position = i;
chag = 1;
}
else
{
if (chag = 0)
{
position = 1;
}
else
{
printf("");
}
}
}
return position;
}
int smallestArray(char a[][SIZE_OF_STRING], int n)
{
puts("Not yet implemented\n");
return 0;
}
void sortArray(char a[][SIZE_OF_STRING], int n)
{
puts("Not yet implemented\n");
}
only worried about "shortest" function at the moment all others run okay.
I also know there are better ways of doing the search but I keep getting "declaration creates integer from pointer without cast" errors when I change to a more standard search with a default smallest etc.
chag is to say whether or not number one in a[] is the smallest as it never gets checked, going to change this as soon as I get it working as I can see a more effective way of doing it.
[edit]
My bad, the error that appears is an application error when "smallest" is selected.
the following appears
"the instruction at "0x77c478c0" referenced memory at "0xd2fd82e0". the memory could not be "read".
ok to terminate program, cancel to debug.
changed the shortest function to the following and still get a similar memory message;
int shortestArray(char a[][SIZE_OF_STRING], int n)
{
int i = 1;
int position = 1;
while (a[i] != '\0')
{
if (strlen(a[i + 1]) < strlen(a[i]))
{
position = i + 1;
i++;
}
else
{
i++;
}
}
return position;
}

There's a clbuttic typo in shortestArray():
if (chag = 0) {
position = 1;
}
// ...
This will always evaluate to false, so the else block is run.
Here, zero is assigned to chag which makes the expression evaluate to zero (false). Use the comparision operator == instead. You might want to crank up warning levels as I'm sure, any C compiler has an appropriate message for this.

One big and obvious problem is that in the function you use the variable i without initializing it.
Another problem is this expression: strlen(a[i-1]). If i is 0 then this will access memory before the array.

In addition to the other answers so far:
You don't increment i either.
If I imagine all the trivial fixes applied (correct iteration, comparison instead of assignment in the condition), the function is going to return position of last local minimum of length. I.e. having list of strings like
"a", "bbbb", "ccc", "dd"
it will return 3, but shortest string is at position 0!
You do remember array indices in C start from 0, right (in position = 1)?

you have to know the number of strings entered in the array to avoid unknown behavior.
a way to do this : in main, just after declaration of array, put :
strcpy(array[0], ""); // to indicate that the array is empty.
in the end of readArray() :
strcpy(a[n] , ""); // there is n strings written bythe user (a[0] to a[n-1]).
and finally :
in shortestArray(), the stop condition of the loop must be changed to :
while (strcmp(a[i],"") != 0 ) //a[i] == '\0' is not correct because a[i] is string and '\0' is char.
here is the entire code with the changes i made :
#include <stdio.h>
#include <string.h>
#define SIZE_OF_STRING 21
#define SIZE_OF_ARRAY 1000
void displayMenu(void);
void readArray(char [][SIZE_OF_STRING], int);
void printArray(char [][SIZE_OF_STRING]);
int shortestArray(char [][SIZE_OF_STRING]);
int smallestArray(char [][SIZE_OF_STRING], int);
void sortArray(char [][SIZE_OF_STRING], int);
int main(void)
{
int position, n = 0; /* all local to main */
char select[10]; /* select is a string */
char array[SIZE_OF_ARRAY][SIZE_OF_STRING]; //change here !
strcpy(array[0] , ""); //instruction added : means array is empty
displayMenu();
scanf("%s", select); /* read first selection */
while (strcmp(select, "exit") != 0) /* while not exit */
{
if (strcmp(select, "read") == 0)
{
printf("How many names?");
scanf("%d", &n);
while (n >= SIZE_OF_ARRAY)
{
printf("the number you entered is bigger than the maximum number of strings, please enter a number smaller than %d\n", SIZE_OF_ARRAY);
}
printf("Enter %d names", n);
readArray(array, n);
}
else if (strcmp(select, "display") == 0)
{
printArray(array);
}
else if (strcmp(select, "shortest") == 0)
{
position = shortestArray(array);
if (position == -1)
printf("there is no string entered !\n");
else
printf("Shortest name is %s in position %d\n", array[position-1], position );
}
else if (strcmp(select, "lowest") == 0)
{
position = smallestArray(array, n);
printf("Lowest name is %s in position %d\n",
array[position], position + 1);
}
else if (strcmp(select, "sort") == 0)
{
sortArray(array, n);
}
else
{
printf("INVALID SELECTION");
}
displayMenu();
scanf("%s", select); /* read next selection */
} /* end while */
}/* end main */
void displayMenu(void)
{
puts("Menu selection");
puts("Enter read to read names");
puts("Enter display to display names");
puts("Enter shortest for shortest name");
puts("Enter lowest for lowest names");
puts("Enter sort to sort names");
puts("Enter exit to exit\n");
}
void readArray(char a[][SIZE_OF_STRING], int n)
{
int i;
printf("\ntype one string per line\n");
for (i=0; i<n; i++)
{
scanf("%s",a[i]);
}
strcpy(a[n] , "");
}
void printArray(char a[][SIZE_OF_STRING])
{
int i;
for (i=0; i< SIZE_OF_ARRAY; i++)
{
if (strcmp(a[i] , "") == 0) // a[i-1] is last string entered
break; // this avoid printing non initialized string causing unknown behaviour.
printf("%s\n",a[i]);
}
}
int shortestArray(char a[][SIZE_OF_STRING])
{
int i = 0;
int position = 1;
if(strcmp (a[i] , "\0") == 0)
return position = -1; // there no string entered.
while (strcmp (a[i+1] , "\0") != 0)
{
if (strlen(a[i+1]) < strlen(a[i]))
{
position = i+2 ;
i++;
}
else
{
i++;
}
}
return position;
}
int smallestArray(char a[][SIZE_OF_STRING], int n)
{
puts("Not yet implemented\n");
return 0;
}
void sortArray(char a[][SIZE_OF_STRING], int n)
{
puts("Not yet implemented\n");
}

Related

Check if the user input matches one of the elements in the array

If the user inputs a value that matches with an int in the array continue the program else quit the program.
My issue is that the function loops the whole array and if it finds one of the values doesnt match it will quit.
//Check if the user input matches with one of the ints in the array
void check(int num, int arr[]) {
for (int i = 0; i < 3; i++) {
if (arr[i] != num) {
printf("Invalid input");
exit(0);
}
}
}
void main() {
int arr[3] = { 1, 2, 3 };
int num = 0;
for (int i = 0; i < 3; i++) {
printf("%d ", arr[i]);
}
printf("\nPLease enter a value which matches with the array %d", num);
scanf("%d", &num);
check(num, arr);
}
void check(int num, int arr[]) {
for (int i = 0; i < 3; i++) {
if (arr[i] == num) {
return;
}
}
printf("Invalid input");
exit(0);
}
Your issue is that checks a single element and judges the input on that specific value. If it has run through each value and the function has still not returned, there is not match and we can exit the program.
You have a logic flaw in the check function: you should output the message and quit if none of the values match the input. You instead do this if one of the values does not match. The check always fails.
Here is a modified version:
#include <stdio.h>
//Check if the user input matches with one of the ints in the array
void check(int num, const int arr[], size_t len) {
for (size_t i = 0; i < len; i++) {
if (arr[i] == num) {
// value found, just return to the caller
return;
}
}
// if we get here, none of the values in the array match num
printf("Invalid input: %d\n", num);
exit(1);
}
int main() {
int arr[3] = { 1, 2, 3 };
size_t len = sizeof(arr) / sizeof(*arr); // length of the array
int num;
for (size_t i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
printf("\n");
printf("Please enter a value which matches with the array: ");
if (scanf("%d", &num) == 1) {
check(num, arr, len);
} else {
// input missing or not a number
printf("Invalid input\n");
}
return 0;
}
You are right, you do exit once arr[i] != num (When the value is not the same as the i:th element in the array).
So, you could change it to: arr[i] == num. If it is the same, perhaps print "You got it!", and a return afterwards.

How to use a code with arrays and strings?

Here are the instructions I was given:
If the command word is find, read an additional integer and search the data set for that integer.
If the command word is print, print the array
Any other command word is an error.
No command word will be longer than 20 characters.
After reading the n+1 values, there will be one more integer (k) read from the keyboard.
Search the array for the value k. If found, print the location where k was found. (1 = data value, n = last data value).
If k is not found, print not found. This is not an error.
If there are more than one value k in the data, only print the location of the first one.
#include <stdio.h>
int main (void) {
int n;
scanf ("%d", &n);
if (n < 1) {
printf ("Error: one or more values must be provided.\n");
return 1;
}
int x [n];
int a;
a = 0;
while (a < n) {
scanf ("%d", x [a]);
a = a + 1;
}
int k;
scanf ("%d", &k);
int i;
i = 0;
while (i <= n-1) {
if (x[i] == k) {
break;
}
i = i + 1;
}
if (i < n) {
printf ("%d\n", k+1);
} else {
printf ("not found\n");
}
printf ("Error: invalid command\n");
return 0;
}
Suggested Strategy:
After reading the array data, read a string.
If the string is find, read integer k and perform a search.
If the string is print, do not read k, just print the data in the array.
If the string is not find or print, handle the error.
Shai'Tavia, I hope my answer will help you see how you may make your code work. You've got the first part down, but you will need to compare the command string given by the user to then make a decision on what to do next.
#include <stdio.h>
#include <string.h>
#define ARRAYLENGTH 8
void printArray(int *array, int length)
{
for (int i = 0; i < length; i++)
printf("%d ", array[i]);
printf("\n");
}
void search(int *array, int key)
{
int flag = 0;
for (int i = 0; i < ARRAYLENGTH; i++)
{
if (array[i] == key && flag == 0)
{
printf("found %d at index: %d\n", key, i);
flag = 1;
}
}
if (flag == 0)
printf("not found\n");
}
int main(void)
{
char command[20];
int indx = 0;
int array[] = {1, 4, 6, 8, 43, 61, 34, 2};
int n, flag = 0;
printf("How many times will we run?");
scanf("%d", &n);
if (n < 1)
{
printf("Error: one or more values must be provided.\n");
return 1;
}
do
{
printf("Enter the command word:");
scanf("%s", command);
if (strcmp(command, "find") == 0)
{
scanf("%d", &n);
search(array, n);
}
else if (strcmp(command, "print") == 0)
printArray(array, ARRAYLENGTH);
else
printf("Command not found\n");
} while (--n > 0);
printf("What is your final interger?");
scanf("%d", &n);
search(array, n);
return 0;
}

How to remove the last comma in comma separated prime numbers within a range?

I have the code for finding prime numbers within a range.
The problem is to remove the last comma.
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
}
}
if(f==0)
printf("%d,",x);
}
}
But the output contains an extra comma in the last.
For example
2,3,5,7,
whereas the expected output is
2,3,5,7
Instead of flag you can decide directly what you want to print between numbers
And note that you can break out of the internal loop as soon as f is set to 1
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
const char* delim = "";
scanf("%d%d",&a,&b);
for(x=a; x<=b; (x++,f=0))
{
for(i=2; i<x; i++)
{
if(x%i==0)
{
f=1;
break; //no need to continue the checking
}
}
if(f==0) {
printf("%s%d",delim,x);
delim = ", ";
}
}
putchar('\n');
}
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
char backspace = 8;
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
}
}
if(f==0)
printf("%d,",x);
}
printf("\b"); // or printf("%c", backspace);
}
Add another flag, just a simple counter that tells you if you are printing the first time then check the flag to decide what to print, e.g.
#include<stdio.h>
int main()
{
int a,b,i,x,c,first=0,f=1;
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
}
}
if(f==0)
{
if(first==0){
printf("%d",x);
}else{
printf(",%d",x);
}
first++
}
}
}
Use a flag to detect the first occurrence of printf() and print the first number as such without any ,. For consecutive number printing precede with ,
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1,flag=0;//Flag to mark first occurrence
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
break;// Once the condition fails can break of the for loop as it fails for the prime number condition at the first case itself
}
}
if(f==0)
{
if(flag==0)
{//Check if it is first time
printf("%d",x);
flag = 1;//If so print without ',' and set the flag
}
else
printf(",%d",x);// On next consecutive prints it prints using ','
}
}
}
This method also avoids the , when only one number is printed.
Eg: When input is 2 and 4. It prints just 3 and not 3,
Simply you need odd number best practice for minimum loop is given below;
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
scanf("%d%d",&a,&b);
while (a < b)
{
if ( (a%2) == 1) {
printf("%d", a);
if ( (a + 1) < b && (a + 2) < b)
printf(",");
}
a = a + 1;
}
}
please check from the site
http://rextester.com/MWNVE38245
Store the result into a buffer and when done print the buffer:
#include <stdio.h>
#include <errno.h>
#define RESULT_MAX (42)
size_t get_primes(int * result, size_t result_size, int a, int b)
{
int i, x, f = 1;
size_t result_index = 0;
if (NULL == result) || (0 == result_size) || ((size_t) -1 == result_size))
{
errno = EINVAL;
return (size_t) -1;
}
for (x = a; x <= b; (x++, f = 0))
{
for (i = 2; i < x; i++)
{
if (x % i == 0)
{
f = 1;
break;
}
}
if (f == 0)
{
result[result_index] = x;
++result_index;
if (result_size <= result_index)
{
fprintf(stderr, "Result buffer full. Aborting ...\n");
break;
}
}
}
return result_index;
}
int main(void)
{
int a = 0, b = 0;
int result[RESULT_MAX];
scanf("%d%d", &a, &b);
{
size_t result_index = get_primes(result, RESULT_MAX, a, b);
if ((size_t) -1 == result_index)
{
perror("get_primes() failed");
}
else if (0 == result_index)
{
fprintf(stderr, "No primes found.\n");
}
else
{
printf("%d", result[0]);
for (size_t i = 1; i < result_index; ++i)
{
printf(", %d", result[i]);
}
}
}
return 0;
}
This example uses a simple fixed-size buffer, if this does not suite your needs replace it by a dynamic one.
This is more of a "language-agnostic" problem: "How do I output a comma-separated list without a final comma?" It is not specifically about prime numbers.
You seem to be thinking of you list as a series of [prime comma] units. It isn't. A better way to think of it is as a single prime as the head of the list, followed by a tail of repeated [comma prime] units.
Some pseudocode to illustrate the general idea:
outputList(theList)
separator = ", "
output(theList.firstItem())
while (theList.hasMoreItems())
output(separator)
output(theList.nextItem())
endwhile
return
/* this is just logic */
for(i=2;i<=n;i++)
{
k=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
k=1;
}
if(k==0)
{
c++;
c++;
}
}
System.out.println(c);
for(i=2;i<=n;i++)
{
k=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
k=1;
}
if(k==0)
{
System.out.print(i);
b++;
if(b!=c-1)
{
System.out.print(",");
b++;
}
}
}
}
}
//comma separated values
#include <bits/stdc++.h>
using namespace std;
int Prime(int a, int n){
bool prime[n+1];
memset(prime,true,sizeof(prime));
for(int p=2;p*p<=n;p++){
if(prime[p]==true){
for(int i=p*p ; i<=n; i+=p ){
prime[i] = false;
}
}
}
for(int i = 2;i<= n;i++){
if(i==2) cout<<i; // here is the logic first print 2 then for other numbers first print the comma then the values
else if(prime[i]) cout<<","<<i;
}
}
int main(){
int a =2 ;
int n = 30;
Prime(a , n);
}
#include <stdio.h>
int main()
{
int i, j, n, count;
scanf("%d", &n);
for(i=2; i<n; i++)
{
count=0;
for(j=2; j<n; j++)
{
if(i%j==0)
count++;
}
if(count==1)
printf("%d," i);
}
printf("\b \b");
}
\b is a nondestructive backspace. It moves the cursor backward, but doesn't erase what's there, it replaces it. For a a destructive backspace,
use "\b \b" i.e. a backspace, a space, and another backspace.
This Program prints all the prime number up to given number with comma separated

Displaying content of an array + taking input

What in the world, is the matter here:
#include <stdio.h>
int main(int argc, char const *argv[])
{
int array[20];
int *pArray = array;
int count;
int i = 0;
while(1)
{
scanf("%d", array+i );
if(*(pArray+i) == -1) break;
i++;
}
printf("Contents: ");
while(1){
if (*(pArray + i) != -1)
{
printf("%d ", *(pArray + i) );
i++;
}
}
return 0;
}
Thank you. I am trying to take input from the user and then display the contents of the array. I was going to arrange them in order too using pointers, but I'll wait till someone replies.
Here is my rewrite attempt:
#include <stdio.h>
int main(void)
{
int array[20];
int i = 0;
while(1)
{
scanf("%d", &array[i] );
if(array[i] == -1) break;
i++;
}
printf("Contents: ");
i = 0; // RESET the counter back to ZERO.
while(1)
{
if (array[i] != -1)
{
printf("%d ", array[i] );
i++;
}
}
return 0;
}
You may be facing the error of stack around the variable array is corrupted. The reason is that you are first taking an input and then terminating the loop if the given input was -1.
scanf("%d", array+i );
if(*(pArray+i) == -1) break;
Now assume that i=20 what will happen???
Of course your code will crash on the scanf statement because it will try to access array+20 (the 20th index) which will not be allowed.
You also need to initialize the array first because when you declare an array, it contains junk values perhaps initializing the last index with zero will do the job. You can use the following code:
#include <stdio.h>
int main(void)
{
int array[20];
/*INITIALIZE THE LAST INDEX WITH -1 TO APPLY THE TERMINATING CONDITION*/
array[19] = -1;
int i = 0;
while(1)
{
scanf("%d", array+i );
i++; //INCREMENT HERE TO CHECK THE NEXT INDEX INSTEAD OF CHECKING THIS ONE
if(array+i == -1)
{
scanf("%d", array+i ); //TAKE THE INPUT FOR THE LAST INDEX
break; //TERMINATE THE LOOP
}
}
printf("Contents: ");
i = 0; // RESET the counter back to ZERO.
while(i != 20)
{
printf("%d ", array[i] );
i++;
}
return 0;
}
It seems like you are using pArray without any reason. array can also do exactly what you are trying to do with pArray. For arranging the order, you have to apply any sorting algorithm. Hope this helps.

Palindrome using recurison

The following code needs to check for palindromes and write the user input backwards using recursion, and then find the Greatest Common Denominator using the same method. The code section that finds the gcd and tells whether or not it is a palindrome works, but it crashes every time it gets the the part where it reverses the code. Why is it crashing every time.
#include <stdio.h>
#include <stdlib.h>
/*Delare the prototypes*/
char palindromes(char[], int);
char backwards(char[], int, int);
int gcdfunc(int, int);
int findgcd(int, int);
int main ()
{
char userinput[10];/*Declares the character array for the input*/
int index= 0;/*Index for the counting loop*/
int counter= 0;/*Counts number of elements entered in the array*/
int printindex= 0;/*Index to print the values on the screen*/
int gcd= 0;/*Sets a value for the GCD*/
int palcheck = 0;
int value1= 0;/*User value 1*/
int value2= 0;/*User value 2*/
int flipindex=0;/*Sets an index for the gcd function*/
printf("Please enter a series of nine or less characters to test for a palindrome.\n");
scanf(" %9s%n", &userinput, &counter);
printf("\n");
palcheck = palindromes(userinput, counter-1);
if(palcheck == 0)
{
printf("Your input was not a palindrome \n");
}/*End of if statement*/
else
{
printf("Your input was a palindrome \n");
}/*End of else statement*/
backwards(userinput, counter-1, flipindex);
printf("Your input backwards is: ");
for(printindex; printindex <= counter; printindex++)
{
printf("%c", userinput[printindex]);
}/*End of printing backwards loop*/
printf("\n");
printf("\nEnter two numbers: ");
scanf("%d %d",&value1,&value2);
gcd=gcdfunc(value1, value2);
printf("The GCD of %d and %d is: %d",value1,value2,gcd);
system("pause");
}/*End of main function*/
char palindromes(char userinput[], int counter)
{
int palindex= 0;/*Declares the index to check for a palindrome*/
int palendinx= counter;
int modulus = counter%2;
if(modulus = 0)
{
if(userinput[palindex]==userinput[palendinx])
{
palindex++;
palendinx--;
if(palindex==(counter/2) && userinput[palindex]==userinput[palendinx])
return 1;
palindromes(userinput, counter);
}
else
{
return 0;
}
}
else
{
if(userinput[palindex]==userinput[palendinx])
{
palindex++;
palendinx--;
if(palindex==(counter/2) && userinput[palindex]==userinput[palendinx])
return 1;
palindromes(userinput, counter);
}
else
{
return 0;
}
}
}/*End of palidrome function*/
char backwards(char userinput[], int counter, int flipindex)
{
while(flipindex<(counter/2))
{
char temp;/*Sets a temporary value to swap the two values*/
temp = userinput[flipindex];
userinput[flipindex] = userinput[counter-flipindex];
userinput[counter-flipindex] = temp;
backwards(userinput, counter, flipindex++);
}
}/*End of reverse function*/
int gcdfunc(int value1, int value2)
{
int gcd;
gcd=findgcd(value1,value2);
return gcd;
}
int findgcd(int value1,int value2)
{
while(value1!=value2)
{
if(value1>value2)
return findgcd(value1-value2,value2);
else
return findgcd(value1,value2-value1);
}
return value1;
}
in your function there is no pass for the variables and it stays in the same cycle over and over and in recursion the same function does not share the same variables it create new one and if you modify one it does not affect the others variables.
char palindromes(char userinput[], int counter)
{
int palindex= 0;/*Declares the index to check for a palindrome*/
int palendinx= counter;
int modulus = counter%2;
if(modulus = 0)
{
if(userinput[palindex]==userinput[palendinx])
{
palindex++;
palendinx--;
if(palindex==(counter/2) && userinput[palindex]==userinput[palendinx])
return 1;
palindromes(userinput, counter);
}
else
{
return 0;
}
}
else
{
if(userinput[palindex]==userinput[palendinx])
{
palindex++;
palendinx--;
if(palindex==(counter/2) && userinput[palindex]==userinput[palendinx])
return 1;
palindromes(userinput, counter);
}
else
{
return 0;
}
}
}/*End of palidrome function*/
So here is the code i did
int palindromes(char userinput[], int counter,int index , int palendex)
{
if(userinput[palendex] == userinput[index])
{
if(counter%2 == 0 && ( index - palendex) == 1)
return 0;
if( index == palendex )
return 0;
else
return palindromes(userinput, counter , index-1 ,palendex+1 );
}
else
return 1;
return 1;
}
In your backward function is that it never leaves the cycle while and do a lot of instances that the memory available runs out. so I changed it to an if statement and it looks like this (and a few changes)
int backwards(char userinput[], int counter, int flipindex)
{
if(flipindex<(counter/2))
{
char temp;/*Sets a temporary value to swap the two values*/
temp = userinput[flipindex];
userinput[flipindex] = userinput[counter-flipindex-1];
userinput[counter-flipindex-1] = temp;
backwards(userinput, counter, flipindex+1);
}
return 1;
}
It looks like you go past the end of the buffer with this code:
for(printindex; printindex <= counter; printindex++)
{
printf("%c", userinput[printindex]);
}/*End of printing backwards loop*/
because printindex == counter and userinput[counter] is out of bounds. Try this for-statement instead:
for(printindex; printindex < counter; printindex++)
if(palindex==(counter/2) && userinput[palindex]==userinput[palendinx])
return 1;
palindromes(userinput, counter);
It call recursively condition in the if statement is not satisfied. but It will stack overflow repeated calls indefinitely because there is no change in the situation.

Resources