char *ptr ---> New to C - char-pointer

Declared char array (read-only):
const char alpha [] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Given a char pointer called ptr and the alpha array declared above, how would I make ptr point to the letter 'D'?
I think its ---> char *alpha[3]; because its pointing to the third index of the array.

Here you go
D is 3 index away from starting address of alpha that is A.
So your pointer should be initialized like this
char *ptr = alpha + 3;

Related

store string in char array assignment makes integer from pointer without a cast

#include <stdio.h>
int main(void){
char c[8];
*c = "hello";
printf("%s\n",*c);
return 0;
}
I am learning pointers recently. above code gives me an error - assignment makes integer from pointer without a cast [enabled by default].
I read few post on SO about this error but was not able to fix my code.
i declared c as any array of 8 char, c has address of first element. so if i do *c = "hello", it will store one char in one byte and use as many consequent bytes as needed for other characters in "hello".
Please someone help me identify the issue and help me fix it.
mark
i declared c as any array of 8 char, c has address of first element. - Yes
so if i do *c = "hello", it will store one char in one byte and use as many consequent bytes as needed for other characters in "hello". - No. Value of "hello" (pointer pointing to some static string "hello") will be assigned to *c(1byte). Value of "hello" is a pointer to string, not a string itself.
You need to use strcpy to copy an array of characters to another array of characters.
const char* hellostring = "hello";
char c[8];
*c = hellostring; //Cannot assign pointer to char
c[0] = hellostring; // Same as above
strcpy(c, hellostring); // OK
#include <stdio.h>
int main(void){
char c[8];//creating an array of char
/*
*c stores the address of index 0 i.e. c[0].
Now, the next statement (*c = "hello";)
is trying to assign a string to a char.
actually if you'll read *c as "value at c"(with index 0),
it will be more clearer to you.
to store "hello" to c, simply declare the char c[8] to char *c[8];
i.e. you have to make array of pointers
*/
*c = "hello";
printf("%s\n",*c);
return 0;
}
hope it'll help..:)

Mex files: how to return an already allocated matlab array

I have found a really tricky problem, which I can not seem to fix easily. In short, I would like to return from a mex file an array, which has been passed as mex function input. You could trivially do this:
void mexFunction(int nargout, mxArray *pargout [ ], int nargin, const mxArray *pargin[])
{
pargout[0] = pargin[0];
}
But this is not what I need. I would like to get the raw pointer from pargin[0], process it internally, and return a freshly created mex array by setting the corresponding data pointer. Like that:
#include <mex.h>
void mexFunction(int nargout, mxArray *pargout [ ], int nargin, const mxArray *pargin[])
{
mxArray *outp;
double *data;
int m, n;
/* get input array */
data = mxGetData(pargin[0]);
m = mxGetM(pargin[0]);
n = mxGetN(pargin[0]);
/* copy pointer to output array */
outp = mxCreateNumericMatrix(0,0,mxDOUBLE_CLASS,mxREAL);
mxSetM(outp, m);
mxSetN(outp, n);
mxSetData(outp, data);
/* segfaults with or without the below line */
mexMakeMemoryPersistent(data);
pargout[0] = outp;
}
It doesn't work. I get a segfault, if not immediately, then after a few calls. I believe nothing is said about such scenario in the documentation. The only requirement is hat the data pointer has been allocated using mxCalloc, which it obviously has. Hence, I would assume this code is legal.
I need to do this, because I am parsing a complicated MATLAB structure into my internal C data structures. I process the data, some of the data gets re-allocated, some doesn't. I would like to transparently return the output structure, without thinking when I have to simply copy an mxArray (first code snippet), and when I actually have to create it.
Please help!
EDIT
After further looking and discussing with Amro, it seems that even my first code snippet is unsupported and can cause MATLAB crashes in certain situations, e.g., when passing structure fields or cell elements to such mex function:
>> a.field = [1 2 3];
>> b = pargin_to_pargout(a.field); % ok - works and assigns [1 2 3] to b
>> pargin_to_pargout(a.field); % bad - segfault
It seems I will have to go down the 'undocumented MATLAB' road and use mxCreateSharedDataCopy and mxUnshareArray.
You should use mxDuplicateArray, thats the documented way:
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
plhs[0] = mxDuplicateArray(prhs[0]);
}
While undocumented, the MEX API function mxCreateSharedDataCopy iswas given as a solution by MathWorks, now apparently disavowed, for creating a shared-data copy of an mxArray. MathWorks even provides an example in their solution, mxsharedcopy.c.
As described in that removed MathWorks Solution (1-6NU359), the function can be used to clone the mxArray header. However, the difference between doing plhs[0] = prhs[0]; and plhs[0] = mxCreateSharedDataCopy(prhs[0]); is that the first version just copies the mxArray* (a pointer) and hence does not create a new mxArray container (at least not until the mexFunction returns and MATLAB works it's magic), which would increment the data's reference count in both mxArrays.
Why might this be a problem? If you use plhs[0] = prhs[0]; and make no further modification to plhs[0] before returning from mexFunction, all is well and you will have a shared data copy thanks to MATLAB. However, if after the above assignment you modify plhs[0] in the MEX function, the change be seen in prhs[0] as well since it refers to the same data buffer. On the other hand, when explicitly generating a shared copy (with mxCreateSharedDataCopy) there are two different mxArray objects and a change to one array's data will trigger a copy operation resulting in two completely independent arrays. Also, direct assignment can cause segmentation faults in some cases.
Modified MathWorks Example
Start with an example using a modified mxsharedcopy.c from the MathWorks solution referenced above. The first important step is to provide the prototype for the mxCreateSharedDataCopy function:
/* Add this declaration because it does not exist in the "mex.h" header */
extern mxArray *mxCreateSharedDataCopy(const mxArray *pr);
As the comment states, this is not in mex.h, so you have to declare this yourself.
The next part of the mxsharedcopy.c creates new mxArrays in the following ways:
A deep copy via mxDuplicateArray:
copy1 = mxDuplicateArray(prhs[0]);
A shared copy via mxCreateSharedDataCopy:
copy2 = mxCreateSharedDataCopy(copy1);
Direct copy of the mxArray*, added by me:
copy0 = prhs[0]; // OK, but don't modify copy0 inside mexFunction!
Then it prints the address of the data buffer (pr) for each mxArray and their first values. Here is the output of the modified mxsharedcopy(x) for x=ones(1e3);:
prhs[0] = 72145590, mxGetPr = 18F90060, value = 1.000000
copy0 = 72145590, mxGetPr = 18F90060, value = 1.000000
copy1 = 721BF120, mxGetPr = 19740060, value = 1.000000
copy2 = 721BD4B0, mxGetPr = 19740060, value = 1.000000
What happened:
As expected, comparing prhs[0] and copy0 we have not created anything new except another pointer to the same mxArray.
Comparing prhs[0] and copy1, notice that mxDuplicateArray created a new mxArray at address 721BF120, and copied the data into a new buffer at 19740060.
copy2 has a different address (mxArray*) from copy1, meaning it is also a different mxArray not just the same one pointed to by different variables, but they both share the same data at address 19740060.
The question reduces to: Is it safe to return in plhs[0] either of copy0 or copy2 (from simple pointer copy or mxCreateSharedDataCopy, respectively) or is it necessary to use mxDuplicateArray, which actually copies the data? We can show that mxCreateSharedDataCopy would work by destroying copy1 and verifying that copy2 is still valid:
mxDestroyArray(copy1);
copy2val0 = *mxGetPr(copy2); % no crash!
Applying Shared-Data Copy to Input
Back to the question. Take this a step further than the MathWorks example and return a share-data copy of the input. Just do:
if (nlhs>0) plhs[0] = mxCreateSharedDataCopy(prhs[0]);
Hold your breath!
>> format debug
>> x=ones(1,2)
x =
Structure address = 9aff820 % mxArray*
m = 1
n = 2
pr = 2bcc8500 % double*
pi = 0
1 1
>> xDup = mxsharedcopy(x)
xDup =
Structure address = 9afe2b0 % mxArray* (different)
m = 1
n = 2
pr = 2bcc8500 % double* (same)
pi = 0
1 1
>> clear x
>> xDup % hold your breath!
xDup =
Structure address = 9afe2b0
m = 1
n = 2
pr = 2bcc8500 % double* (still same!)
pi = 0
1 1
Now for a temporary input (without format debug):
>> tempDup = mxsharedcopy(2*ones(1e3));
>> tempDup(1)
ans =
2
Interestingly, if I test without mxCreateSharedDataCopy (i.e. with just plhs[0] = prhs[0];), MATLAB doesn't crash but the output variable never materializes:
>> tempDup = mxsharedcopy(2*ones(1e3)) % no semi-colon
>> whos tempDup
>> tempDup(1)
Undefined function 'tempDup' for input arguments of type 'double'.
R2013b, Windows, 64-bit.
mxsharedcopy.cpp (modified C++ version):
#include "mex.h"
/* Add this declaration because it does not exist in the "mex.h" header */
extern "C" mxArray *mxCreateSharedDataCopy(const mxArray *pr);
bool mxUnshareArray(const mxArray *pr, const bool noDeepCopy); // true if not successful
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
mxArray *copy1(NULL), *copy2(NULL), *copy0(NULL);
//(void) plhs; /* Unused parameter */
/* Check for proper number of input and output arguments */
if (nrhs != 1)
mexErrMsgTxt("One input argument required.");
if (nlhs > 1)
mexErrMsgTxt("Too many output arguments.");
copy0 = const_cast<mxArray*>(prhs[0]); // ADDED
/* First make a regular deep copy of the input array */
copy1 = mxDuplicateArray(prhs[0]);
/* Then make a shared copy of the new array */
copy2 = mxCreateSharedDataCopy(copy1);
/* Print some information about the arrays */
// mexPrintf("Created shared data copy, and regular deep copy\n");
mexPrintf("prhs[0] = %X, mxGetPr = %X, value = %lf\n",prhs[0],mxGetPr(prhs[0]),*mxGetPr(prhs[0]));
mexPrintf("copy0 = %X, mxGetPr = %X, value = %lf\n",copy0,mxGetPr(copy0),*mxGetPr(copy0));
mexPrintf("copy1 = %X, mxGetPr = %X, value = %lf\n",copy1,mxGetPr(copy1),*mxGetPr(copy1));
mexPrintf("copy2 = %X, mxGetPr = %X, value = %lf\n",copy2,mxGetPr(copy2),*mxGetPr(copy2));
/* TEST: Destroy the first copy */
//mxDestroyArray(copy1);
//copy1 = NULL;
//mexPrintf("\nFreed copy1\n");
/* RESULT: copy2 will still be valid */
//mexPrintf("copy2 = %X, mxGetPr = %X, value = %lf\n",copy2,mxGetPr(copy2),*mxGetPr(copy2));
if (nlhs>0) plhs[0] = mxCreateSharedDataCopy(prhs[0]);
//if (nlhs>0) plhs[0] = const_cast<mxArray*>(prhs[0]);
}

declaring and passing char array of different sizes correctly

I like to define a method that receives a char array of variable size.
This is my current definition:
+(int) findStartIndex: (NSData*)buffer searchPattern: (char*) searchPattern;
And this is where I call it:
const char a[] = {'a','b','c'};
startIndex = [self findStartIndex:buffer searchPattern: a];
and like this
const char b[] = {'1','2'};
startIndex = [self findStartIndex:buffer searchPattern: b];
But I keep getting the compiler warning:
Sending 'const char[3]' to parameter of type 'char *' discards qualifiers
and
Sending 'const char[2]' to parameter of type 'char *' discards qualifiers
respectively.
How to do this correctly?
Because the parameter you declared as char *, but const char [] is passed. It's a have a potential risk. you should the following changes. Do not have a warning when I tested.
+(int) findStartIndex: (NSData*)buffer searchPattern: (const char*) searchPattern
Qualifiers in C apply to the keyword on the left first, then fallback to the right next. const char arr[] is not a constant reference to a char array, it's always of type char. But, when you pass it to a method that takes a pointer to char, then you lose the const'ness of the type, and you get a warning. (Hooray for obscure C stuff!)

COnverting Char Array to Long int

How to convert Char array to long in obj c
unsigned char *composite[4];
composite[0]=spIndex;
composite[1]= minor;
composite[2]=shortss[0];
composite[3]=shortss[1];
i need to convert this to Long int..Anyone please help
If you are looking at converting what is essentially already a binary number then a simple type cast would suffice but you would need to reverse the indexes to get the same result as you would in Java: long value = *((long*)composite);
You might also consider this if you have many such scenarios:
union {
unsigned char asChars[4];
long asLong;
} value;
value.asChar[3] = 1;
value.asChar[2] = 9;
value.asChar[1] = 0;
value.asChar[0] = 10;
// Outputs 17367050
NSLog(#"Value as long %ld",value.asLong);

matlab mex: Access data

Hey there,
I don't really understand how to access data passed via arguments in matlab to a mex-function. Assuming I have the 'default' gateway function
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
And now I get the pointer to the 1. input argument:
double* data_in;
data_in = mxGetPr(prhs[0]);
Both the following lines EACH seperatly make my matlab crash:
mexPrintf("%d", *data_in);
mexPrintf("%d", data_in[1]);
But why can't I access the data like that when data_in obvisously is a pointer to the first argument?
When do I need to declare the pointer as double* and when as mxArray*? Sometimes I see something like that: mxArray *arr = mxCreateDoubleMatrix(n,m,mxREAL);!?
Thanks a lot in advance!
data_in is a pointer to double so you need something like
mexPrintf("%f", data_in[0]);
This assumes the caller passed a vector or matrix of size > 0.
More generally, you can
int n = mxGetN(array);
int m = mxGetM(array);
To get the number of rows and columns of the matrix/vector passed to the mex function.
Regarding mxArray:
Matlab packs its matrices (complex and real) in an mxArray structure. mxCreateDoubleMatrix returns a pointer to such structure. To actually access that data you need to use mxGetPr() for the real part and mxGetPi() for the imaginary parts.
These return pointers to the allocated double[] arrays, which you can use to access (read and write) the elements of the matrix.
A very convenient way of handling dimensions of mxArrays is to introduce a function like the following.
#include <cstddef>
#include <cstdarg>
#include "mex.h"
bool mxCheckDimensions(const mxArray* mx_array, size_t n_dim,...) {
va_list ap; /* varargs list traverser */
size_t *dims; /* dimension list */
size_t i;
size_t dim;
bool retval = true;
va_start(ap,n_dim);
dims = (size_t *) malloc(n_dim*sizeof(size_t));
for(i=0;i<n_dim;i++) {
dims[i] = va_arg(ap,size_t);
dim = mxGetDimensions(mx_array)[i];
if (dim != dims[i])
retval = false;
}
va_end(ap);
free(dims);
return retval;
}
In this way you check an array mxArray* p is a double array of size say 1,3 using
double* pDouble = NULL;
if (mxIsDouble(p)) {
if (mxCheckDimensions(p, 2, 1, 3)) {
pDouble = (double*) GetData(p);
// Do whatever
}
}`