#include <string.h>
#include <stdio.h>
int calc_slope(int input1,int input2)
{
int sum=0;
int start=input1;
int end=input2;
int curr=start;
//some validation:
if (input1>input2)
return -1;
while(curr<=end)
{
if (curr>100)
{
char *s="";
int length;
int left;
int right;
int cent;
sprintf(s,"%d",curr);
length=strlen(s);
s++;
do
{
//printf("curr=%d char=%c pointer=%d length=%d \n",curr,*s,s,length);
left = *(s-1) - '0';
cent = *s - '0';
right = *(s+1) - '0';
//printf("curr=%d l=%d c=%d r=%d\n",curr,left,cent,right);
if ( (cent>left && cent>right) || (cent<left && cent<right) )
{
sum+=1; //we have either a maxima or a minima.
}
s++;
} while (*(s+1)!='\0');
}
curr++;
}
return sum;
}
int main()
{
printf("%d",calc_slope(1,150));
return 0;
}
are invalid . First of all any pointer to a string literal may not be changed. And secondly it occupies usually on 32-bit platforms only 4 bytes. Instead of the pointer you should use a character array with appropriate size.
It is undefined behavior. It could works at one moment, then you chanhe some unrelevent part of program, everything crashes and you cannot find why, you never thought on that part and spent all week in debugging...
In the ling you provided they working with allocated character.
You made s points somewhere random in the memory, and accesing area around it.
Okies. Since C++ is not a child's play and I'm quite new to it, can you please show me how do I go about correcting this?
As you must have known by reading this code, all it does is calculate the Slope of each number in a loop. For example, consider the number:
"1324"
Lets ignore the first and last chars i.e. 1 & 4. In case of 3, it is greater than the left ("1") and also the right ("2"). Hence, its a maxima. The string pointer s is supposed to contain the string "1324", and inside the loop, I'm calculating the sum of all maxima and minima.