I am having an issue with double arguments for a probability function in C.
I have a function that takes a double as an argument:
int binomrand(double p, int n)
{
int i;
int numevents = 0;
for(i = 0; i < n; i++)
{
numevents += bernoullirand(p);
}
return numevents;
}
I pass .85:
int numcoach = binomrand(.85,COACH_SEATS);
but the minute I step into this function, Xcode shows p as such:
p double 5.2511106800094658E-315
Which is off by a factor of at least 10^314. This occurs even before calling bernoullirand, so I haven't included that code here.
E:
Since it was relevant, here was the .h declaration of binomrand:
int binomrand(float p, int n);
This was clearly wrong, but I didn't think to look at it. Note that's "float" and not "double".
When I updated the function from float to double in its .c file, I neglected to do so in its .h file. Multiple answerers realized this quickly.
This can happen if you have not declared the function binomrand before first use or declared it incorrectly. Declare the function on the top of file where you actually use it or use proper header files.
int binomrand(double p, int n); /* Declaration */
Related
I wrote a simple method to calculate an arithmetic mean like so:
float arithmetic_mean(int a[], int n)
{
float sum = 0;
int i;
for (i = 0; i < n; i++)
{
sum += a[i];
}
sum = sum / (float)n;
return sum;
}
I wanted to check it in main:
int main()
{
int a[] = { 1,3,5,1,6,7 };
float check = arithmetic_mean(a, 6);
printf("%f", check);
return 0;
}
even though the value the method returns is correct (=3.833333 as checked by printing it before returning it), when I try to print it in main I get 9 as the output.
I'm really new to C language and stuff like this always seems to happen with floats - I'll write a method that works and return a float - and the returned value would be something seemingly random. What am I missing here? What am I doing wrong?
The problem (which I can reproduce with MSVC) is that you are calling the arithmetic_mean function (from main) before you have defined it. Thus, the compiler uses a default definition of the function, which is that it returns an int type ... and the actual (float) value returned just happens to have a bit pattern that represents 9 when interpreted as an int.
You can leave the definition of the function where it is (after main) so long as you provide a forward declaration of the function, so that the compiler knows what the return type is:
float arithmetic_mean(int a[], int n); // Forward declaration of the function!
int main()
{
int a[] = { 1,3,5,1,6,7 };
float check = arithmetic_mean(a, 6);
printf("%f\n", check);
return 0;
}
// The actual DEFINITION (including the body) of the function can follow...
Turning on compiler warnings would have helped you spot this! For example, without the forward declaration, MSVC gives this:
warning C4013: 'arithmetic_mean' undefined; assuming extern returning
int
I was going through Dennis Ritchie's book, The C programming language. In it, he says:
In certain circumstances, the extern declaration can be omitted. If the definition of the
external variable occurs in the source file before its use in a particular function, then there is no
need for an extern declaration in the function.
I tried quick code as follows:
#include "stdio.h"
int n = 0;
int nn = 111;
int main(int argc, char **argv) {
int n = 1;
printf("n from main(): %d\n", n);
function1();
function2();
}
void function1()
{
extern int n;
int nn; //declaring without extern keyword, this should point to global nn as per Dennis, but that does not seem to happen
int nnn; //declaring without extern keyword
printf("n from function1(): %d\n", n);
printf("nn from function1(): %d\n", nn);
printf("nnn from function1(): %d\n", nnn);
n = 10;
}
void function2()
{
extern int n;
int nn; //declaring without extern keyword, this should point to global nn as per Dennis, but that does not seem to happen
int nnn; //declaring without extern keyword
printf("n from function2(): %d\n", n);
printf("nn from function2(): %d\n", nn);
printf("nnn from function2(): %d\n", nnn);
}
int nnn = 222 ;
Below is sample output:
n from main(): 1
n from function1(): 0
nn from function1(): 1955388784
nnn from function1(): 6422476
n from function2(): 10
nn from function2(): 1955388784
nnn from function2(): 6422476
Notice what both functions function1() and function2() printed above. I guess, as per Dennis' statement, both should have referred global nn and should have printed 111. But that did not happen.
(You can try running code here)
Is it because the version about which Dennis is talking differs from the one using?
Am on MinGW.org GCC-8.2.0-5.
, then there is no need for an extern declaration in the function.
Here what Dennis Ritchie saying is that, If definition of nn varibale is already occured in source file then now in function1() and funcation2() you do not need to declare variable as extern again, like (extern int nn;) you can directly use them.
But by doing int nn; in your funcation1() you are defining one another local variable. Which is complete different variable.
The keyword extern is used with objects to reference objects that have file scope.
This declaration in your functions
int nn; //declaring without extern keyword, this should point to global nn as per Dennis, but that does not seem to happen
has a block scope. So it is a definition of a local variable.. It does not have linkage.
The quote you provided means that if there is a definition of a file scope variable then it has external or internal linkage. So there is no need to use the keyword extern
For example
//…
int n = 10; // definition of a variable with external linkage
void f()
{
printf( "n = %d\n", n );
}
//...
You're completely misunderstanding Mr. Richie. He's saying that this:
int n;
void foo()
{
n = 42;
}
requires no extern because the referenced variable n is defined before the function, foo, that uses it.
Were the code like this:
void foo()
{
n = 42;
}
int n;
the compiler now has no idea what you're talking about when using n in the body of foo. There is no n until later, but the compiler has no idea that there ever will be.
You can address this by:
extern int n;
void foo()
{
n = 42;
}
int n;
Now, when compiling foo, the compiler knows there is some int called n ... somewhere. Doesn't know where yet, and frankly doesn't care. Likewise, this will also work:
void foo()
{
extern int n;
n = 42;
}
int n;
That's all he's trying to say. Your code and comments seem to think that by doing this:
void foo()
{
int n;
n = 42;
}
int n;
the n in foo will magically resolve to the outer n. That isn't how the language works. All this does is make the code compile because now the compiler sees an n that fulfills usage for n = 42. It's an automatic variable (lifetime to the { scope } in which it is declared). It has absolutely nothing to do with the int n; outside that scope (but can easily shadow (hide) the name n if you're not careful. That is exactly what is happening in your code.
You seem to be misinterpreting the last part of the statement that "there is no need for an extern declaration in the function" to mean "there is no need for an extern keyword in the function."
What Dennis is saying is that extern int n; in your functions is equivalent to not declaring n at all. extern int n; is not equivalent to int n;, e.g. in main.
I just wanted to know whether it should print 111 as per the author. Now I realized, author is saying "...before its use..." and by "use", he meant "use without (re)definition inside function".
If we define variable again inside function without extern, it will create local variable for function.
(Dont know if I should answer my own question, may be others will correct me if am wrong in this understanding again.)
I defined as a global variable in int main() a matrix a[][], i didn't initialised the variable.
Then I used some function:
The first one: receives as argument the matrix a and then defines a[i][j] as a certain value (random), this for all i and j in the appropriate range. The function simply returns 1;
The second one: receives as argument the matrix a and simply prints it. Also this function simply returns 1;
The last one: receives as argument the matrix a and then determines the maximum of its values and return that values
I thought, naively, that writing plainly the code without defining some pointer to the matrix, to make the variable of the matrix global and sharable from all the functions, the code simply wouldn't have worked. But it worked.
I thought that it wouldn't have worked because i didn't defined the matrix in a global way, but it is defined only in a function and then (to me:)pretends to pass to the other functions.
So my question is: why it worked?
The code:
int matrix_definition(int a[][], int dim);
int matrix_print(int a[][], int dim);
int max_matrix(int a[][],int dim);
int main()
{
int a[][], dim;
matrix_definition(a,dim);
matrix_print(a,dim);
printf("%d", max_matrix(a,dim));
return 0;
}
The full code including main() and matrix_definition is this:
#include<stdio.h>
#define SIZE 100
int matrix_definition(int a[SIZE][SIZE], int dim);
int matrix_print(int a[SIZE][SIZE], int dim);
int max_matrix(int a[SIZE][SIZE],int dim);
int main()
{
int a[SIZE][SIZE], dim;
matrix_definition(a,dim);
matrix_print(a,dim);
printf("%d", max_matrix(a,dim));
return 0;
}
int matrix_definition(int a[SIZE][SIZE],int dim)
{
int i,j;
srand(time(NULL));
for(i=0;i<dim;i++)
{
for(j=0;j<dim;j++)
{
a[i][j]=rand()%2;
}
}
return 1;
}
The updated code you posted is very different from what you originally posted. Yes, that code is valid with regard to how a is defined and how it is passed to various functions.
In each of your function declarations you declare a parameter:
int a[SIZE][SIZE]
Since arrays as parameters are converted to pointers, this is equivalent to:
int (*a)[SIZE]
This is compatible with the variable defined in main:
int a[SIZE][SIZE];
When passing an array to a function, it decays to a pointer to the first element. So this function call:
matrix_definition(a,dim);
is the same as:
matrix_definition(&a[0],dim);
The expression a[0] has type int [SIZE], so the expression &a[0] has type int (*)[SIZE]. This is the same as the function's parameter.
I'm trying to use FFTPACK converted from Fortran to C that I downloaded from Netlib (http://www.netlib.org/fftpack/). Unfortunately it seems to not really documented, and very cryptic (as I imagine most FFT codes are). Apparently it should follow a similar structure to the original Fortran code, so that's what I tried.
Here's what I have so far:
void main()
{
int n = 10;
float* wsave;
forward_transform(function1, wsave, n);
}
void forward_transform(float (*f)(float), float* wsave, int n)
{
int *ifac;
int i;
float r[n];
for (i = 0; i< n; i++)//set function values
{
r[i] = f((float)(-M_PI + i*2*M_PI/(n-1)));
}
__ogg_fdrffti(n, *wsave, *ifac);//initialize
__ogg_fdrfftf(n, *r, *wsave, *ifac);//forward transform
}
This code manages to compile, but gives a segfault when I call __ogg_fdrffti. I tried entering via gbd into fft.c to see exactly where the error is, but I can't seem to do that (the code still segfaults at the same line in my forward_transform function) leading me to believe that I'm somehow making an error in how I'm passing the various arrays.
Does anyone have any experience with or examples of the C version of FFTPACK?
The variables initialized in these functions have to exist somewhere in memory. You are passing pointers instead.
Try
void main()
{
int n = 10;
float wsave;
forward_transform(function1, wsave, n);
}
void forward_transform(float (*f)(float), float wsave, int n)
{
int ifac;
int i;
float r[n];
for (i = 0; i< n; i++)//set function values
{
r[i] = f((float)(-M_PI + i*2*M_PI/(n-1)));
}
__ogg_fdrffti(n, &wsave, &ifac);//initialize
__ogg_fdrfftf(n, r, &wsave, &ifac);//forward transform
}
Notice that the pointers are created using the address operator & on actual variables.
I have this:
long int addsquares(int n, ...)
How can I access the parameters?
I can't use va_start and va_arg...
Implementation dependent...
pre test
long int addsquares(int n, int d1, ...){
printf("%p,%p\n", &n, &d1);
return 0L;
}
result :
windows 64bit system, vc10 (sizeof int:4)
003DFD54,003DFD58
windows 64bit system, gcc 4.4.3 (sizeof int:4)
000000000022FE60,000000000022FE68
for vc10:
long int addsquares(int n, ...){
int i, *p = &n;
long sum = 0L;
for(i=1;i<=n;++i)
sum += p[i]*p[i];
return sum;
}
for gcc:
long int addsquares(int n, ...){
int i, *p = &n;
long sum = 0L;
for(i=1;i<=n;++i)
sum += p[i*2]*p[i*2];
return sum;
}
If you are saying that you have a variadic function, and you're not allowed to use the variable argument macros (va_xxx) then you'd have to rewrite the content of those macro's yourself.
Unless you can change the function prototype, but I'm guessing that's now allowed either.
Use Arrays and store each parameter in one "cell" of the array.
long int addsquares(int[] parameters)
{
for (int i = 0; i < parameters.length(); i++)
{
//Use current parameter: parameters[i]
}
}
It's c# code, but i thinkit will work for c as well.
Check out the discussion in this thread... How does the C compiler implement functions with Variable numbers of arguments?
I think you'll find it gets you going in the right direction. Pay particular attention to the discussion on the need to use one of the arguments as a means to sort out what and where the other arguments are.