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 */

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

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

% File: t2.m
function t2()

a = zeros(2,1);
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);
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;


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: Logo

You are commenting using your 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


Blog Stats

  • 249,812 hits

%d bloggers like this: