Call by value or call by reference?

In C, if you pass in a pointer to a function, the content of the involved variable may be changed. In Matlab, however, if you pass in an array as an argument, the content of the array will never be changed after the function call, even if the variable with the same name is modified within the function, unless the variable is also output. Ok, now comes the question: What if the function called by Matlab is written in C as a mex function? Haha, have fun with the following three tests, t1, t2, and t3.

/* File: t1.c */
#include

void foo(double *a)
{
a[0] = 1;
}

void main(void)
{
double a[2] = {0};
foo(a);
printf("first element of array a = %g\n", a[0]);
}

% File: t2.m
function t2()

a = zeros(2,1);
foo(a);
fprintf(1, 'first element of array a = %g\n', a(1));

function foo(a)

a(1) = 1;

% File: t3.m
function t3()

a = zeros(2,1);
foo_mex(a);
fprintf(1, 'first element of array a = %g\n', a(1));

/* File: foo_mex.c */
#include "mex.h"

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
double *a = mxGetPr(prhs[0]);
a[0] = 1;
}

Advertisements

0 Responses to “Call by value or call by reference?”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




Categories

Blog Stats

  • 246,614 hits

%d bloggers like this: