Dynamic jump to label in C - c

I would like to display the output - numbers 1 to 5, followed by 4-5 infinitely. Is there any way i can pass the value of i(4) instead of the character i in goto1. Or is there any other efficient way of realizing this without illustrating all the options as in switch(i.e case 1: goto1(c1) ,etc..).
The main aim is to jump to a statement whose label is computed within the program.
#define goto1(i) \
goto c##i
int main(){
c1 : printf(" num is 1 \n");
c2 : printf(" num is 2 \n");
c3 : printf(" num is 3 \n");
c4 : printf(" num is 4 \n");
c5 : printf(" num is 5 \n");
int i=4;
goto1(i);
}

If you are ... adventurous (or do I mean silly?), you can use a GCC extension Labels as Values.
6.3 Labels as Values
You can get the address of a label defined in the current function (or a containing function) with the unary operator ‘&&’. The value has type void *. This value is a constant and can be used wherever a constant of that type is valid. For example:
void *ptr;
/* ... */
ptr = &&foo;
To use these values, you need to be able to jump to one. This is done with the computed goto statement1, goto *exp;. For example,
goto *ptr;
Any expression of type void * is allowed.
One way of using these constants is in initializing a static array that serves as a jump table:
static void *array[] = { &&foo, &&bar, &&hack };
Then you can select a label with indexing, like this:
goto *array[i];
Note that this does not check whether the subscript is in bounds—array indexing in C never does that.
Such an array of label values serves a purpose much like that of the switch statement. The switch statement is cleaner, so use that rather than an array unless the problem does not fit a switch statement very well.
Another use of label values is in an interpreter for threaded code. The labels within the interpreter function can be stored in the threaded code for super-fast dispatching.
You may not use this mechanism to jump to code in a different function. If you do that, totally unpredictable things happen. The best way to avoid this is to store the label address only in automatic variables and never pass it as an argument.
An alternate way to write the above example is
static const int array[] = { &&foo - &&foo, &&bar - &&foo,
&&hack - &&foo };
goto *(&&foo + array[i]);
This is more friendly to code living in shared libraries, as it reduces the number of dynamic relocations that are needed, and by consequence, allows the data to be read-only.
The &&foo expressions for the same label might have different values if the containing function is inlined or cloned. If a program relies on them being always the same, __attribute__((__noinline__, __noclone__)) should be used to prevent inlining and cloning. If &&foo is used in a static variable initializer, inlining and cloning is forbidden.
Footnotes
[1] The analogous feature in Fortran is called an assigned goto, but that name seems inappropriate in C, where one can do more than simply store label addresses in label variables.
Under no circumstances should this be taken as a recommendation to use the feature. The computed goto was eventually removed from Fortran; it is best left in the dustbin of history.

Are you asking for a jump table? If you are using gcc: It has a jump table mechanism.
#include <stdio.h>
int main()
{
unsigned char data[] = { 1,2,3,4,5,4,5,0 };
// data to "iterate" over, must be 0-terminated in this example
void *jump_table[] = { &&L00, &&L01, &&L02, &&L03, &&L04, &&L05 };
// you should fill this with all 256 possible values when using bytes as p-code
unsigned char *p = data;
begin:
goto *jump_table[ *p ];
L00:
return 0; // end app
L01:
printf("num %i\n", (int)*p);
goto next;
L02:
printf("num %i\n", (int)*p);
goto next;
L03:
printf("num %i\n", (int)*p);
goto next;
L04:
printf("num %i\n", (int)*p);
goto next;
L05:
printf("num %i\n", (int)*p);
goto next;
L06:
L07:
// ...
LFF:
goto next;
next:
++p; // advance the data pointer to the next byte
goto begin; // start over
return 0;
}
The pro about this method is that you spare the large switch statement.

Since you want to do this the wrong (aka. creative) way, have you considered trampolining?
#include <stdio.h>
typedef void (*generic)(void);
typedef generic (*continuation)(void);
generic first(void);
generic second(void);
int main(void) {
continuation fubar = first;
for (;;) {
fubar = (continuation) fubar();
}
}
generic first(void) {
printf(" num is 1 \n"
" num is 2 \n"
" num is 3 \n");
return (generic) second;
}
generic second(void) {
printf(" num is 4 \n"
" num is 5 \n");
return (generic) second;
}
Continuing on from the idea of using function pointers (see what I did there? Giggity!), you could use an array of function pointers:
#include <stdio.h>
typedef size_t (*function)(size_t);
size_t first(size_t);
size_t second(size_t);
int main(void) {
function function[] = { first, first, first, first, second };
size_t index = 0;
for (;;) {
index = function[index](index);
}
}
size_t first(size_t index) {
printf(" num is %d \n", ++index);
return index;
}
size_t second(size_t index) {
printf(" num is %d \n", index+1);
return index-1;
}

Why not do it like this?
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf(" num is 1 \n");
printf(" num is 2 \n");
printf(" num is 3 \n");
for (;;){
printf(" num is 4 \n");
printf(" num is 5 \n");
}
/* Not reachable, but will silence any compiler warnings about main
* not returning a value. */
return EXIT_SUCCESS;
}

Wouldn't a switch accomplish the same thing?
int main()
{
int i = 1;
while (1)
{
switch (i)
{
case 1:
printf(" num is 1 \n");
case 2:
printf(" num is 2 \n");
case 3:
printf(" num is 3 \n");
case 4:
printf(" num is 4 \n");
case 5:
printf(" num is 5 \n");
default:
break;
}
// code to calculate i
i = 4;
// end code to calculate i
}
return 0;
}

Related

How to determine a list of number is increasing, decreasing or unordered just by using simple operator instead of array, map or other function?

Below is the code that I used to determined the list of number order(increase, decrease or unordered).
Or is there any other simpler mathematical way to determine that a list of number is unordered instead of using 3 variables?
Edit : 1. The list might have duplicated number(So ya I need to have a comparison for equal state too. Thanks to those who point it out).
#include <stdio.h>
int main()
{
int num, counter, a, b, c, pattern, unordered_flag;
printf("How many number u want to enter? ");
scanf("%d", &num);
counter = 0; b = 0; c = 0;
while(counter < num){
printf("Enter number [%d] : ",counter+1);
scanf("%d", &a);
printf("a=%d b=%d c=%d pattern=%d\n",a,b,c,pattern); //I used this to check the value of a,b,c and pattern
if(a>b>c){
pattern = 99; //i use 99 to represent increasing order
}
else if(a<b<c){
pattern = 11; //i use 11 to represent decreasing order
}
else{
pattern = 55; //i use 55 to represent unordered order
unordered_flag = 404;
}
c = b;
b = a;
counter = counter + 1;
}
if (unordered_flag == 404){
printf("\nThe pattern is : Unordered");
}
else if(pattern == 99){
printf("\nThe pattern is : Increasing");
}
else if(pattern == 11)
printf("\nThe pattern is : Decreasing");
return 0;
}
This is the concept of monotonicity. In a finite strongly-ordered list, you could use a finite-state machine.
With, (1): a variable to hold 8 states, (practically could be an enum or function pointer,) and (2): memory of the last element, one can completely determine, on-line, the next state. A distance of three transitions is the minimum it takes to cover the vertices.
*Edit: A weaker version of this can be made by collapsing the states outlined in blue.
For example, this (very incomplete) state machine might be how one would do it with an enum. This is preferable to using integer magic values for readability and debugging.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
/* X-Macro; just lazy. */
#define STATES X(EMPTY), X(ONE), X(STRICT_INCREASE), X(STRICT_DECREASE), \
X(EQUAL), X(INCREASE), X(DECREASE), X(UNORDERED)
int main(int argc, const char **argv) {
struct {
#define X(x) x
enum { STATES } state;
#undef X
int prev;
} sm = { EMPTY, 0 };
#define X(x) #x
static char *names[] = { STATES };
#undef X
int success = EXIT_FAILURE;
(void)argc; /* Unused; `argv` is null-terminated. */
errno = 0; /* `strtol` on POSIX-compliant systems gives more info. */
while(*(++argv)) {
/* Read a parameter from the command line. */
char *end;
int num;
long temp = strtol(argv[0], &end, 0);
if(errno) goto catch;
if(temp < INT_MIN || temp > INT_MAX)
{ errno = ERANGE; goto catch; }
if(*end != '\0')
{ errno = EILSEQ; goto catch; }
num = (int)temp;
/* Plug the parameter into the state machine. */
switch(sm.state) {
case EMPTY:
sm.state = ONE; break;
case ONE:
if(sm.prev < num) sm.state = STRICT_INCREASE;
else if(num < sm.prev) sm.state = STRICT_DECREASE;
else sm.state = EQUAL;
break;
case STRICT_INCREASE: /**** TODO! ****/
case STRICT_DECREASE:
case EQUAL:
case INCREASE:
case DECREASE:
sm.state = UNORDERED; break;
case UNORDERED:
break;
}
sm.prev = num;
}
printf("This is %s.\n", names[sm.state]);
{ success = EXIT_SUCCESS; goto finally; }
catch:
perror("list-of-ints");
finally:
return success;
}

Problems with passing arrays as parameters

I am a novice programmer in C and am running into an issue that is almost painfully simple. I am writing a basic program that creates two arrays, one of student names and one of student ID numbers, then sorts them and prints them in various ways, and finally allows the user to search the arrays by ID number. Here is the code:
#include <stdio.h>
#include <string.h>
#define ARRAY_SIZE 3
#define MAX_NAME_LENGTH 32
int main()
{
// Student info arrays
char NAME[ARRAY_SIZE][MAX_NAME_LENGTH];
int ID[ARRAY_SIZE];
// Array for student IDs, shifted twice to the right
int shiftedID[ARRAY_SIZE];
// Boolean value to keep while loop running and
// the ID search prompt repeating
int loop = 1;
// Counter variable for the for loop
int counter;
// Gets input values for the student info arrays
for (counter = 0; counter < ARRAY_SIZE; counter++)
{
printf("Input student name: ");
scanf("%s", NAME[counter]);
printf("Input student ID: ");
scanf("%d", &ID[counter]);
}
// Sorts the arrays
sort(NAME, ID);
// Prints the arrays
print_array(&NAME, ID);
// Shifts the ID value two bits to the right
shiftright(ID, shiftedID);
print_array(NAME, shiftedID);
// Repeatedely prompts the user for an ID to
// search for
while(loop == 1)
{
search_id(NAME, ID);
}
}
And here are the function definitions:
#define ARRAY_SIZE 3
#define MAX_NAME_LENGTH 32
// Sorts the two arrays by student ID. (Bubble sort)
void sort(char **nameArray, int idArray[])
{
// Counter variables for the for loop
int firstCounter = 0;
int secondCounter = 0;
for(firstCounter = 0; firstCounter < ARRAY_SIZE; firstCounter++)
{
for(secondCounter = 0; secondCounter < ARRAY_SIZE - 1;
secondCounter++)
{
if(idArray[secondCounter] > idArray[secondCounter + 1])
{
// Temporary variables for the sort algorithm
int tempInt = 0;
char tempName[32];
tempInt = idArray[secondCounter + 1];
idArray[secondCounter + 1] = idArray[secondCounter];
idArray[secondCounter] = tempInt;
strcpy(tempName, nameArray[secondCounter + 1]);
strcpy(nameArray[secondCounter + 1],
nameArray[secondCounter]);
strcpy(nameArray[secondCounter], tempName);
}
}
}
}
// Searches the ID array for a user input student
// ID and prints the corresponding student's info.
void search_id(char **nameArray, int idArray[])
{
// A boolean value representing whether or not
// the input ID value was found
int isFound = 0;
// The input ID the user is searching for
int searchID = 0;
printf("Input student ID to search for: ");
scanf("%d", &searchID);
// Counter variable for the for loop
int counter = 0;
while (counter < ARRAY_SIZE && isFound == 0)
{
counter++;
if (idArray[counter] == searchID)
{
// Prints the name associated with the input ID
isFound = 1;
printf("%s", nameArray[counter]);
}
}
// If the input ID is not found, prints a failure message.
if (isFound == 0)
{
printf("ID not found.\n");
}
}
// Prints the name and ID of each student.
void print_array(char **nameArray, int idArray[])
{
// Counter variable for the for loop
int counter = 0;
printf("Student Name & Student ID: \n");
for (counter = 0; counter < ARRAY_SIZE; counter++)
{
printf("%s --- %d\n", nameArray[counter], idArray[counter]);
}
}
// Shifts the ID value to the right by two bits
void shiftright(int idArray[], int shiftedID[])
{
// Counter variable for the for loop
int counter = 0;
for (counter = 0; counter < ARRAY_SIZE; counter++)
{
shiftedID[counter] = idArray[counter] >> 2;
}
}
I am aware that this program is fairly basic in nature, and more than anything it is an exercise to get me more well versed in a language such as C. I've been working on it for some time, and have worked through several problems, but seem to be stuck on three issues:
If the input ID numbers are not input already in order, a segmentation fault results. If the ID numbers are input already in order, the sort function never passes through the if statement, and no problems arise.
When passing the arrays of names/IDs to the print_array function, the IDs are printed just fine, but the names will be printed either entirely blank or as a series of strange characters.
When searching by ID at the end of the program, the ID number that was entered first (so, the number in ID[0]) displays an ID not found message, where all numbers at index 1 or greater will work fine - aside from the corresponding names that should be printed being printed as blank, as mentioned in the second issue.
Any advice that I can get would be greatly appreciated! I find the power behind the fine details needed in C to be both really interesting but also very confusing, intimidatingly so, and that means any help I can get makes a big difference.
The problem is that you are assuming that char [ARRAY_SIZE][MAX_NAME_LENGTH] and char ** are interchangeable
void sort(char **nameArray, int idArray[])
should be
void sort(char nameArray[][MAX_NAME_LENGTH], int idArray[])
or
void sort(char (*nameArray)[MAX_NAME_LENGTH], int idArray[])
in order to use a pointer to an array of MAX_NAME_LENGTH chars, same for your search_id function.
Take a look to question 6.13 of C-FAQ
I would advise you to restructure your program. Rather than storing two independent arrays for names and IDs, you can store one array of structs which contain all the necessary data:
typedef struct student
{
int id;
char name[MAX_NAME_LENGTH];
} student_t;
student_t students[ARRAY_SIZE];
Now you have a single array which can never become "mismatched" by sorting the IDs without the names, etc.
You can sort an array in C using the standard library function qsort():
qsort(students, ARRAY_SIZE, sizeof(student_t), comparator);
This requires you define a comparator, which is fairly simple. One example would be:
int comparator(const void *lhs, const void *rhs)
{
const student_t *s1 = lhs, *s2 = rhs;
return s1->id - s2->id;
}
You can use the same comparator with another standard library function bsearch() to search the array of students after it is sorted:
student_t key = { 42 }; // name doesn't matter, search by ID
student_t* result = bsearch(&key, students, ARRAY_SIZE, sizeof(student_t), comparator);
These standard functions are more efficient than what you had, and require you to write much less code, with fewer chances for mistakes.

Defining Command Line Arguments w/ functions

The following code:
#include<stdio.h>
void main(int argc, char * argv[]) {
int i, n, sum = 0;
if (argc == 1) {
printf("You have forgot to type numbers.");
exit(1);
}
printf("The sum is: ");
///for (i = 1; i < argc; i++)
///sum = sum + atoi(argv[i]);
for(i = 0; i < argc; i++)
{
n = atoi(argv[i]);
sum += n;
}
printf("%d", sum);
}
gives me the sum in the command line, so for example if at the prompt I type, "program.exe 23 23 32", the output will be "The sum is: 68".
I would like to separate the sum logic so that it's its very own function, and then at the prompt I would like to be able to type, "program.exe -sum 23 23 32" to get the same result.
I found this and this. The latter contained some useful code, doing almost exactly what you want. Their example requires knowing how many arguments are being taken (the for loop in the sum function contains i < 5), but there could be a way of working around that.
man 3 stdarg should be helpful aswell.
It seems to me that you don't really need the - in front of sum; the first argument should be a simple string:
program.exe sum 1 3 5 9
Whether you keep the dash or not, you can simply arrange to pass a pointer to the remainder of the argument list to a function which expects that:
int sum(int numc, char **numv)
which returns the sum of the numc numbers represented as strings in the number vector numv. You can call that easily enough:
int rv = sum(argc - 2, argv + 2);
after you've established that sum is the function to call. And you can have a collection of such functions.
If you've encountered function pointers, you could create yourself an array of names (that the user will type on the command line) and function pointers (which point to the corresponding function). Then you simply have to look up the name the user typed in the array and call the appropriate function. That's probably still for the future for you, though.
In a lot of C code, we take shortcuts to make parsing easier. For example, let's say we know that we only have 2 choices of operator: sum or product. We then know that the first argument must be either -sum or -product. We can simplify the parsing by just checking for - followed by either s or p.
As for abstracting the actual operator, in this case it's probably more efficient to just check which operator was chosen on the command line, and then either apply += or *= based on that.
Here is some working code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[]) {
int n;
int result;
int i = 1;
char operator;
// parse -sum or -product
if (argv[i] && argv[i][0] == '-') {
// we take a shortcut and just look at the first letter
char firstLetter = argv[i][1];
if (firstLetter == 's') {
// using sum
operator = '+';
result = 0; // additive identity
}
else if (firstLetter == 'p') {
// using product
operator = '*';
result = 1; // multiplicative identity;
}
else {
printf("Unknown option: %s\n", argv[i]);
exit(1);
}
// move on to the next argument
i++;
}
else {
printf("Please specify an operation (-sum or -product)\n");
exit(1);
}
if (!argv[i]) {
printf("You have forgot to type numbers.\n");
exit(1);
}
for(; argv[i]; i++) {
n = atoi(argv[i]);
if (operator == '+') {
result += n;
}
else { // if (operator == '*')
result *= n;
}
}
printf("The result is: %d\n", result);
return 0;
}
Notice that the initial value of result is different depending on which operation was chosen.
Rather than using argc, the code above takes advantage of the fact that the argv array is null-terminated. In other words, if you had 3 arguments (or argc=4), then argv[3] will be NULL (which is equivalent to 0 or false).
Note that if you turn on optimizations, then any decent C compiler will move the test outside the loop, so it only actually checks which operator was chosen once. (This is easily verifiable by looking at the produced assembly code.)

In C, are variables declared within a loop, local?

#include <stdio.h>
int a;
void myproc()
{
int a = 2;
while (a == 2)
{
int a = 3;
printf("a = %d\t", a);
break;
}
printf("a = %d\t", a);
}
int main()
{
a = 1;
myproc();
printf("a = %d\t", a);
return (0);
}
I expected the above code to print: a = 3 a = 3 a = 1
However, it prints: a = 3 a = 2 a = 1 Can someone please provide a valid explanation?
Here is an explanation -- see the commentary below.
#include <stdio.h>
int a;
void myproc()
{
int a = 2; // (1) a = 2
while (a == 2) // true
{
int a = 3; // (2) new scope, new a = 3
printf("a = %d\t", a); // (X) prints 3 as it gets the 'nearest a' in the scope
break;
} // throws away a=3 from (2)
printf("a = %d\t", a); // (Y) Uses (1) i.e. 2 and print it
}
int main()
{
a = 1;
myproc();
printf("a = %d\t", a); // (Z) Just prints 1 as the scope is not effected by myproc
return (0);
}
So this will print (X) (Y) and (Z)
i.e. 3 2 1
Yes, they are local automatic variables and are pushed on and popped off the stack when you enter and exit a given scope unless the compiler decides to make certain optimizations (such as storing them in registers, etc.) But for a given variable, the most locally scoped version of that variable is used when accessing it. For instance, in C89 should you decide to declare your loop counters within a for-loop declaration, the following typically produces a compiler error:
for (int i=0; i < N; i++)
for (int i=0; i < J; i++)
printf("%d", i);
The value of i printed will always be the value of i declared in the inner for-loop, since that is the most locally scoped version of i.
"Within a loop"?
The question you are asking has absolutely no relation to any loops at all. There's no difference between what you have in your code and the ordinary
int a;
void myproc()
{
int a = 2;
{
int a = 3;
printf("a = %d\t", a);
}
printf("a = %d\t", a);
}
Each nested block has it own variables. That's all there is to it. And it has nothing to do with any loops.
The declaration that is really related to the loop would be the declaration made in the header of the loop, as in
int a = 3;
for (int a = 0; a < 10; ++a)
{
...
}
printf("a = %d\n", a); // <- prints `3`
That a declared in the for header is still local to the loop.
The { } variables declare scope. As when you declare a variable between those braces it is only available in those braces. If you have nested variables (like in myproc you declare a = 2 and then inside the loop a=3) then the variable declared closet to the current scope is the one referenced (in the example, a = 3).
Since your print statements are nested in the {} only the most recently declared variable a is printed, getting your results.
Whenever you declaring a variable inside a loop, which is not available outside (out of scope for that variable ). So in your code
void myproc()
{
int a = 2;
while (a == 2)
{
int a = 3;// This is not accessable to outside while loop.
printf("a = %d\t", a);
break;
}
printf("a = %d\t", a);
}
If you want to print 3, 3, 1 remove int inside while loop :)
Actually, the loop is a significantly convenient obfuscator here.
Consider the while loop's test. This test is run twice during the execution of the program, and the first time the test succeeds, as the a it is examining has the value 2. The second time it is run, the test fails, because the a it is testing is a different a, which hold the value 3! This is very surprising.
Given my colleagues explanations, the three declarations of a exist in only their enclosing '{' and '}' delimited scopes (or the world scope for the first one). If this were literally true, then the while (a == 2) test should pass forever, as the interior a declaration assigned to the value 3 is completely hidden from it by the '{' and '}'
int a = 1; // world scope - a is 1
myproc()
{ // New scope; can define names inside here
int a = 2; // Redefine a to be 2
while ( a == 2 ) // We test whether a is 2
{ // New scope; can define names inside here
int a = 3; // Redefine a to be 3
} // end of scope, the a = 3 disappears; also branch back to top of loop
} // end of myprog scope, so the a=2 disappears
The way to understand this is to realize that the while (test) { statements; } is actually implemented as:
if ( test ) { // T1
L1: {
statements;
if ( test ) // T2
goto L1;
}
}
and so in truth, the test statement is replicated, and the first one 'T1' is executed in the scope outside of the '{' and '}' and gets the a that is 2, and passes; and the second one 'T2' is executed inside the scope of the '{' and '}' and gets the a that is 3 and the test fails.
Given your statements, the second test uses its locally scoped definition of a which is 3, so the loop is exited after one pass.

Indexing with pointer C/C++

Hey I'm trying to write a program to carry out newtons method and find the roots of the equation exp(-x)-(x^2)+3. It works in so far as finding the root, but I also want it to print out the root after each iteration but I can't get it to work, Could anyone point out my mistake I think its something to do with my indexing?
Thanks a million :)
#include <stdio.h>
#include <math.h>
#include <malloc.h>
//Define Functions:
double evalf(double x)
{
double answer=exp(-x)-(x*x)+3;
return(answer);
}
double evalfprime(double x)
{
double answer=-exp(-x)-2*x;
return(answer);
}
double *newton(double initialrt,double accuracy,double *data)
{
double root[102];
data=root;
int maxit = 0;
root[0] = initialrt;
for (int i=1;i<102;i++)
{
*(data+i)=*(data+i-1)-evalf(*(data+i-1))/evalfprime(*(data+i-1));
if(fabs(*(data+i)-*(data+i-1))<accuracy)
{
maxit=i;
break;
}
maxit=i;
}
if((maxit+1==102)&&(fabs(*(data+maxit)-*(data+maxit-1))>accuracy))
{
printf("\nMax iteration reached, method terminated");
}
else
{
printf("\nMethod successful");
printf("\nNumber of iterations: %d\nRoot Estimate: %lf\n",maxit+1,*(data+maxit));
}
return(data);
}
int main()
{
double root,accuracy;
double *data=(double*)malloc(sizeof(double)*102);
printf("NEWTONS METHOD PROGRAMME:\nEquation: f(x)=exp(-x)-x^2+3=0\nMax No iterations=100\n\nEnter initial root estimate\n>> ");
scanf("%lf",&root);
_flushall();
printf("\nEnter accuracy required:\n>>");
scanf("%lf",&accuracy);
*data= *newton(root,accuracy,data);
printf("Iteration Root Error\n ");
printf("%d %lf \n", 0,*(data));
for(int i=1;i<102;i++)
{
printf("%d %5.5lf %5.5lf\n", i,*(data+i),*(data+i)-*(data+i-1));
if(*(data+i*sizeof(double))-*(data+i*sizeof(double)-1)==0)
{
break;
}
}
getchar();
getchar();
free(data);
return(0);
}
No offenses, but your question is highly seductive to downvoting. Unrelated question title, ridiculous coding style (I mean tabulation).
Also within your newton function there's no actual need to store all the intermediate results, the Newton-Raphson should not use extra memory (i.e. it's O(1)).
Just add printf within your newton inside the iteration loop. Is this a problem?
In newton, you are returning the address of a local variable that doesn't exist anymore after the function returns. Accessing it afterwards is undefined behaviour.
In main you have
if(*(data+i*sizeof(double))-*(data+i*sizeof(double)-1)==0)
data is a double*, so data + i addresses the i-th double from the start. By multiplying the offset with sizeof(double), you access beyond the end of the array if i > number_of_elements/sizeof(double), yet more undefined behaviour.
And, thanks to JeremyP for finding it, in main you call newton
*data= *newton(root,accuracy,data);
which dereferences the pointer returned by newton (undefined behaviour, but at that point likely to do what you want) and stores that value in the first slot of the data allocated in main. Sot that probably gives you the initial element of the root array from newton, but doesn't change anything else in the memory block allocated to data in main.
void newton(double initialrt,double accuracy,double *data)
{
double root[102];
data=root;
// at this moment the values in the original argument data[]
// are no longer accessible to this function.
int maxit = 0;
root[0] = initialrt;
for (int i=1; i < 102; i++)
{
data[i] = data[i-1]
- evalf(data[i-1]) / evalfprime( data[i-1] );
if ( fabs(data[i] - data[i-1]) < accuracy )
{
maxit=i;
break;
}
maxit=i;
}
if ( maxit+1 == 102 && fabs(data[maxit] - data[maxit-1] ) > accuracy )
{
printf("\nMax iteration reached, method terminated");
}
else
{
printf("\nMethod successful");
printf("\nNumber of iterations: %d\nRoot Estimate: %lf\n",maxit+1
,data[maxit);
}
return;
}
(this is merely a stylistic comment, since the real issues have already been addressed)
pointer dereferencing and array indexing are equivalent in C. Your *(data+i) = ... is equivalent to data[i] = ...
the return value is useless, the function could return instead something usefull (eg accuracy)
return is not a function. No need to return(something); just return something; will do.
you return a pointer to the local array root, which is out of scope when the caller sees it.
whitespace makes a difference in reading experience
UPDATE: on second thought, I think in the inner loop the OP intended something like:
root[i] = root[i-1]
- evalf(data[i-1]) / evalfprime( data[i-1] );
if ( fabs(data[i] - data[i-1]) < accuracy )
{
maxit=i;
break;
}
maxit=i;

Resources