Accessing my malloc'd 2d array with [x][y] - objective-c

I'm updating a class to use member variable instead of #defines to define the bounds of a 2d array. It used to look like:
#define kWidth 3
#define kHeight 100
NSUInteger fields[kWidth][kHeight];
Now kWidth and kHeight are iVars. I switched to malloc convention, because I see no other choice as the bounds can now change. The problem is I cannot access the array using two [] ([][]). See my inline comments. I am sure I've malloc'd correctly. I've done this many times before, and under iOS. Why can't I access this way?
self.kFieldsHeight = 100;
self.kFieldsWidth = 3;
NSUInteger** fields = (NSUInteger**)malloc(sizeof(NSUInteger) * self.kFieldsHeight * self.kFieldsWidth);
memset(fields, 0xFF, self.kFieldsWidth * self.kFieldsHeight * sizeof(NSUInteger));
//// Now with LLDB I can examine the array in one dimension
// p fields[0] // 0xFFFFFFFF
// p fields[299] // 0xFFFFFFFF
// p fields[300] // 0xGARBAGE
//// THIS fails with "error: Couldn't dematerialize struct : Couldn't read a composite type from the target: gdb remote returned an
error: E08"
// p fields[0][0]
// Thus this fails in my code
NSUInteger i = fields[0][0];
What's the deal?
Edit: (more detail)
I've also tried mallocing like this:
fields = (NSUInteger**)malloc(sizeof(NSUInteger*) * self.kFieldsHeight);
if(fields){
for(int i = 0; i < self.kFieldsHeight; i++){
fields[i] = (NSUInteger*)malloc(sizeof(NSUInteger) * self.kFieldsWidth);
}
}
Edit: (even more detail). I swapped the width and height with the same results:
fields = (NSUInteger**)malloc(sizeof(NSUInteger*) * self.kFieldsWidth);
if(fields){
for(int i = 0; i < self.kFieldsWidth; i++){
fields[i] = (NSUInteger*)malloc(sizeof(NSUInteger) * self.kFieldsHeight);
}
}

You need to do this:
NSUInteger **fields = malloc(self.kFieldsHeight * sizeof(NSUInteger*));
for (int i = 0; i < self.kFieldsHeight; i++) {
fields[i] = malloc(sizeof(NSUInteger) * self.kFieldsWidth);
memset(fields, 0xFF, self.kFieldsWidth * sizeof(NSUInteger));
}
But this is not the way most people do the job. Most developers use a big array instead of a 2d array and try to index it themselves. Like this:
NSUInteger *fields = malloc(self.kFieldsHeight * self.kFieldsHeight * sizeof(NSUInteger));
fields[h * width + w] = pixel_value;

try this
fields = (NSUInteger**)malloc(sizeof(NSUInteger*) * self.kFieldsWidth);
if(fields){
for(int i = 0; i < self.kFieldsWidth; i++){
fields+i = (NSUInteger*)malloc(sizeof(NSUInteger) * self.kFieldsHeight);
}
}
no real reason for doing it this way, just another way of saying a[i] is a+i
I am using my C knowledge here and not objective C hope I can help

Related

Making an incremental for loop end by a certain number in objective-c

I'm trying to find a solution to this coding problem:
Create a for loop that will begin with a value of 5 and end with a value of 25. In each iteration, add the incrementing value to mathTotal. (HINT: the last value used INSIDE the loop should be 25)
But the way I can think of doing it returns with a final number for mathTotal of 26. I'm not sure how to manipulate the code to stop at 25 without actually doing the math to figure out what number to make the condition for the program to stop running.
This is what I have:
int mathTotal;
for(int i = 5; mathTotal <=25; i++) {
mathTotal = mathTotal + i;
}
I know this is a simple problem, but I'm learning how to code and don't want to move on without fully understanding something.
Thank you!
There are two major issues:
mathTotal is not initialized. You have to set an initial value.
int mathTotal = 0;
The upper border (the second parameter of the for loop) is defined as mathTotal <= 25 – rather than i <= 25 – which will be reached when i is 8.
for (int i = 5; i <=25; i++) {
mathTotal = mathTotal + i;
}
The traditional for loop in Objective-C is inherited from standard C and takes the following form:
for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
// Do something.
}
For example, to print the numbers from 1 to 10, you could use the for loop:
for (int i = 1; i <= 10; i++)
{
NSLog(#"%d", i); //do something
}
This is logically equivilant to the following traditional for loop:
for (int i = 0; i < [yourArray count]; i++)
{
NSLog([myArrayOfStrings objectAtIndex:i]);
}
Your Doubt
int mathTotal = 0;
for (i = 5 = 0; i <=25 ; i++)
{
mathTotal = mathTotal + i;
}

Fast Fourier Transform in Objective-C doesn't work fine

I have a method in Objective-C that receives an array of doubles and then it uses the Fast Fourier Transform, however the exit of the FFT doesn't match to what I want.
Can someone help me, I don't know what I'm doing wrong?
This is my method where fftLength is 4096:
-(double(*)) doFFT:(double(*))data{
double (*fft) = malloc((fftLength * 2) * sizeof(double));
FFTSetupD fft_weights = vDSP_create_fftsetupD((log2((double)(fftLength))), kFFTRadix2);
DSPDoubleSplitComplex fftData;
//fftData.imagp = fftMagnitudes;
fftData.imagp = (double*)malloc(fftLength * sizeof(double));
fftData.realp = (double*)malloc(fftLength * sizeof(double));
for (int i=0; i< fftLength; i++) {
fftData.realp[i] = (double)data[i];
fftData.imagp[i] = (double)0.0;
}
vDSP_fft_zipD(fft_weights, &fftData, 1, log2((double)(fftLength)), FFT_FORWARD);
for(int i = 0;i<fftLength * 2;i++){
fft[i] = fftData.realp[i];
fft[i+1] = fftData.imagp[i];
}
return fft;
}
And this is part of my input data:
[0.0,2.092731423889438E-4, 8.858534436404497E-4,0.0013714427743574675,0.0012678166431137061,-9.650789019044481E-4,-0.002852548808273958,-0.005176802258252122,-0.007281581949909022,-0.00575977878132905,…]
And the result should be:
[21478.183372382526,0.0,-10190.412374839314,…]
But I'm not getting this.
This loop is wrong:
for(int i = 0;i<fftLength * 2;i++){
fft[i] = fftData.realp[i];
fft[i+1] = fftData.imagp[i];
}
Assuming you want interleaved real/complex output data then it should be:
for(int i = 0; i < fftLength; i++) {
fft[i * 2] = fftData.realp[i];
fft[i * 2 + 1] = fftData.imagp[i];
}

convert 16 bit Infrared data to meaningful data in C/Objective C

I have an API that returns the 16-bit Infrared data from a file.
The usage is like this:
UInt16 *irDataResult = IrbGetIrData16([self.path UTF8String]);
The length of the the data pointed by the pointer is : 1024x768x2.
I want to convert it in to an int 2 dimensional array so that I have individual pixels and then I can use one of the UIImage functions to create image out of my raw data.
The I way I'm doing is this:
int dataArray[width][height];
int *dataPointer = &dataArray[0][0];
int byteNum = 0;
for (int w = 0; w < width; w++) {
for (int h = 0; h < height; h++) {
dataArray[w][h] = irDataSource[byteNum] <<0 | irDataSource[byteNum] << 8; //Little endian
byteNum++;
}
}
The loop runs fine, but after a little while it gives my BAD_ACCESS error.
What am I doing wrong?
Also, is this the right approach?

elliptical fixture in box2d and cocos2d

I am trying to develop an iOS game in Cocos2d + Box2d. I want to use elliptical fixtures in Box2D. I tried using b2Capsule shape, but its not exactly what I want as the collision is not proper. Anyone has done this before?
For specific shapes in Box2D you will have to triangulate you original polygon (in your case an ellipse in which you keep a certain number of vertices).
For this, you can use the poly2tri excellent constrained Delaunay triangulation at http://code.google.com/p/poly2tri/
It is very simple. Here is the way I get my triangles :
- (NSArray*) triangulate:(NSArray*)verticesArray
{
NSMutableArray* outputTriangles = [[[NSMutableArray alloc] init] autorelease];
p2t::CDT* triangulationContainer;
vector<p2t::Triangle*> p2tTriangles;
vector< vector<p2t::Point*> > polylines;
vector<p2t::Point*> polyline;
for (hOzPoint2D *point in verticesArray) {
polyline.push_back(new p2t::Point([point x], [point y]));
}
polylines.push_back(polyline);
triangulationContainer = new p2t::CDT(polyline);
triangulationContainer->Triangulate();
p2tTriangles = triangulationContainer->GetTriangles();
for (int i = 0; i < p2tTriangles.size(); i++) {
p2t::Triangle& t = *p2tTriangles[i];
p2t::Point& a = *t.GetPoint(0);
p2t::Point& b = *t.GetPoint(1);
p2t::Point& c = *t.GetPoint(2);
[outputTriangles addObject:[NSArray arrayWithObjects:
[hOzPoint2D point2DWithDoubleX:a.x doubleY:a.y],
[hOzPoint2D point2DWithDoubleX:b.x doubleY:b.y],
[hOzPoint2D point2DWithDoubleX:c.x doubleY:c.y], nil]];
}
delete triangulationContainer;
for(int i = 0; i < polylines.size(); i++) {
vector<p2t::Point*> poly = polylines[i];
FreeClear(poly);
}
return [outputTriangles copy];
}
hOzPoint2D here is my custom point class, but you can pass any couple of coordinates. You don't even have to output a NSArray : you can insert this method in your body creation one.
Be careful that poly2tri has some restrictions :
you can't have twice the same point in your polygon ;
the polygon must not be self-intersecting ;
...
Read the poly2tri page to know more.
The resulting array contains triangles that you attach as fixtures to the same body.
I have used approximation as well. This has some performance drawbacks, but nothing major I guess. Code (Flash ActionScript 3, but you should be able to port that easily):
var vertices:Vector.<b2Vec2> = new Vector.<b2Vec2>();
var a:Number = _image.width / 2 / PhysicsVals.RATIO;
var b:Number = _image.height / 2 / PhysicsVals.RATIO;
var segments:int = ellipse_approximation_vertices_count; (the more the more precise shape is, but the more time it takes to do collision detection)
var segment:Number = 2 * Math.PI / segments;
for (var i:int = 0; i < segments; i++)
{
vertices.push(new b2Vec2(a * Math.cos(segment * i), b * Math.sin(segment * i)));
}
var shape:b2PolygonShape = new b2PolygonShape();
shape.SetAsVector(vertices, vertices.length);
var fixtureDef:b2FixtureDef = new b2FixtureDef();
fixtureDef.shape = shape;

Visual C++ Statement + Vars

How Can I bind for example int value to the statement below?
System::String^ Content = "just example";
int iAValue = 5;
lblOutput_{iValue}->Text = Content;
You don't; you use an array or collection of some sort. This sort of thing is often attempted by beginners. It is not possible, nor is it a good idea to tie your program logic to the names of your variables.
auto labels = gcnew List<Label>();
labels->Add(lblOutput1);
labels->Add(lblOutput2);
labels->Add(lblOutput3);
labels->Add(lblOutput4);
labels->Add(lblOutput5);
// ...
String^ Content = "just example";
int iAValue = 4;
labels[iAValue].Text = Content;
And then later you can iterate over all of them easily:
for(int i = 0; i < labels->Count; ++i) {
// i is the label "number"
// labels[i] is the label
}