Strange Errors in a For Loop - objective-c

Hello there fellow coders.
I have been learning my way around GLKit over the past few weeks. I found this very helpful series of tutorials on how to set-up a basic 2D graphics engine found here.
When I followed the first chunk of 'Iteration 5' code something strange happened. The for loop in the updateVertices method comes up with compiler errors. Those errors are shown here.
Here's the class code in it's entirety.
//
// Elipse.m
// EmptyGLKit
//
// Created by C-R on 8/6/13.
// Copyright (c) 2013 C-R. All rights reserved.
//
#import "Ellipse.h"
#define ELLIPSE_RESOLUTION 64;
#define M_TAU (2*M_PI)
#implementation Ellipse
-(int)numVertices {
return ELLIPSE_RESOLUTION;
}
-(void)updateVertices {
for (int i = 0; i < ELLIPSE_RESOLUTION; i++) {
float theta = ((float)i) / ELLIPSE_RESOLUTION * M_TAU;
self.vertices[i] = GLKVector2Make(cos(theta)*radiusX, sin(theta)*radiusY);
}
}
-(float)radiusX {
return radiusX;
}
-(void)setRadiusX:(float)_radiusX {
radiusX = _radiusX;
[self updateVertices];
}
-(float)radiusY {
return radiusY;
}
-(void)setRadiusY:(float)_radiusY {
radiusY = _radiusY;
[self updateVertices];
}
#end
I've tried closing and reopening the project, cleaning the code, rebooting Xcode, all without success.
To my knowledge that for loop is completely acceptable and has been in several other projects of mine.

Your #define line has a ; at the end. This isn't correct and should be removed. The #define is basically substituted into the code for compilation so the end result is an if statement with too many ; characters in it.

Related

Null pointer Exception at the end of draw processing3

I get a Null Pointer Exception, and the trace tells me it is inside a function that I have. This function runs every frame and does some calculations and stuff. Anyway, the problem is that when I go to debug, stepping through each line, the function runs fine, and the error only comes up at the end of the draw loop.
This error only recently came up, and the changes I made don't have much to do with the function in question so...
The function mentioned in the trace detects if the object touches something, and acts on it.
Also, the trace gives a line number that does not exist, I'm guessing that's because of the Processing compiling.
I am using Processing 4 if that matters.
Here's the trace:
java.lang.NullPointerException
at ants$Ant.sense(ants.java:190)
at ants$Ant.go(ants.java:220)
at ants.draw(ants.java:44)
at processing.core.PApplet.handleDraw(PApplet.java:2201)
at processing.awt.PSurfaceAWT$10.callDraw(PSurfaceAWT.java:1422)
at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:354)
Thanks!
Edit:
More info: This is an ant simulator, and it crashes at food pickup. This used to work and broke while adding (seemingly) unrelated stuff. It crashes at food pickup, which is managed by the sense() function. The Food class only has a position and a render function.
Here is some code:
void sense() { // The problematic function
if (!detectFood && !carryFood) {
float closest = viewRadius;
Food selected = null;
for (Food fd : foods){
float foodDist = position.dist(fd.position);
if(foodDist <= viewRadius) {
if(foodDist < closest) {
selected = fd;
closest = foodDist;
}
}
}
if (selected != null){
detectFood = true;
foodFocused = selected;
}
} else {
if(position.dist(foodFocused.position) < 2*r) {
takeFood();
detectFood = false;
}
}
}
void draw() { // draw loop
background(51);
for (Food food : foods) {
food.render();
}
for (Ant ant : ants) {
ant.go();
}
for (int i=0; i < trails.size(); i++) {
Trail trail = trails.get(i);
if (trail.strenght <= 0)
trails.remove(trail);
else
trail.go();
}
}
The problem is not the trail, as it still crashes without it,

Storing int values in an uint8_t array in code composer studio vs 5.4

I have a string in a uint8_t str[] array and I am trying to store the positions of characters within the str in another variable called uint8_t pos[]. The code is written in Code Composer Studio vs 5.4
I tried using sprintf(), type casting as well as changing the type of uint8_t pos[] to int pos[] as well as unsigned int pos[]. None of these work.
The code breaks at the sprintf statement and comes to a halt by reaching an undefined memory location. When I run in assembly after reaching sprintf statement, it gives an error saying that a source code for sprint.c cannot be found in location.
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "tm4c123gh6pm.h"
#include <stdio.h>
void initHw()
{
.
.
}
int main(void)
{
// Initialize hardware
initHw();
char strRx[80];
int count =0;
int count_enter=0;
uint8_t posStr[80];
uint8_t typeStr[80];
int pos=0;
int len;
unsigned int j=0, argCount=0;
while(1)
{
if(count == 0)
{
putsUart0("Enter characters for the string\r\n");
}
if(count <= 80)
{
char c = getcUart0();
if(c=='\b')
if(count>0)
count--;
else
break;
if(c>=' ')
{
strRx[count]=c;
count++;
}
if(count==80 || c==13)//'\r')
{
count_enter++;
if(count_enter==1) //count==80 before carriage return
{
len = count;
strRx[count]='\0';
while(count!=80)
strRx[count++]='\0';
count_enter=0;
putsUart0("\r\nEntered string is:\r\n");
putsUart0(strRx);
putsUart0("\r\n");
}
j=0;
//char a[10];
for(pos=0; pos!=len; pos++)// strRx[pos]!='\0'; pos++)
{
char a[80];
if((strRx[pos]>='A' && strRx[pos]<='Z') || (strRx[pos]>='a' && strRx[pos]<='z'))
{
typeStr[j]='a';
//posStr[j]=pos;
a[j]=pos;
sprintf(a,"%u",pos); //source not found
//a[j]=pos;
//posStr[j]=sprintf("%c",a);
//posStr[j]=(uint8_t)a;//a;
while(strRx[pos]!='\0'&&((strRx[pos]>='A' && strRx[pos]<='Z') || (strRx[pos]>='a' && strRx[pos]<='z')))
{
pos++;
}
pos--;
j++;
}
else if(strRx[pos]>='0' && strRx[pos]<='9')
{
typeStr[j]='n';
a[j]=pos;
sprintf(a,"%u",pos);
//posStr[j]=pos;//a;
while(strRx[pos]!='\0'&&((strRx[pos]>='0' && strRx[pos]<='9')))
{
pos++;
}
pos--;
j++;
}
else
{
while(strRx[pos]!='\0'&&((strRx[pos]<'A' && strRx[pos]>'Z') && (strRx[pos]<'a' && strRx[pos]>'z') && (strRx[pos+1]<'0' && strRx[pos+1]>'9')))
pos++;
}
}
argCount=j;
while(j!=80)
{
typeStr[j++]='\0';
posStr[j++]='\0';
}
count = 0;
}//if(count==80 || c==13)//'\r')
}//if count<=80
}//while(1)
}//main
The "unable to locate sprintf.c" error probably just means that the debugger cannot locate the source file, which means it cannot show the source code in the debugger window. It's possible that you don't have the source code for sprintf.c and all you have is the precompiled library. Or maybe you do have the source code and the debugger is simply looking in the wrong path. If you have the source code then there may be a way to tell the debugger which path to find it.
But that is just a debugger display issue -- It is not what is causing your program to crash. The problem may be in your code but you'd have to share your code for us to identify that. Or the problem may be a couple other issues that can occur with the printf related routines.
1) printf routines can use a relatively large amount of stack space. So check for a stack overflow and increase the stack size if necessary.
2) Some embedded libraries provide multiple implementations of the printf routines such as "small", "no-float", and "full". The limited implementations use less code space but don't support all of the format specifiers. So make sure the implementation of sprintf that you've linked with supports all the format specifiers that you're actually using. Look through the project settings under linker or libraries for an option to select which version of printf is used.

PHP Extension return structure

I am working on a PHP extension and wants to let PHP returns a structure. But it always cause core dump. My step is:
./ext_skel --extname=test
./configure --enable-test
in php_test.h, add:
typedef struct mydata {
int m_id;
int m_age;
}MYDATA;
PHP_FUNCTION(wrap_getMydata);`
In test.c, add:
#define MY_RES_NAME "my_resource";
static int my_resource_descriptor;
PHP_FE(wrap_getMydata, NULL)
...
ZEND_MINIT_FUNCTION(test)
{
/* If you have INI entries, uncomment these lines
REGISTER_INI_ENTRIES();
*/
resid = zend_register_list_destructors_ex(NULL, NULL, MY_RES_NAME, module_number);
return SUCCESS;
}
PHP_FUNCTION(test_getMydata)
{
zval* res;
long int a, b;
long int result;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &a, &b) == FAILURE) {
return;
}
MYDATA objData;
objData.m_id = a;
objData.m_age = b;
ZEND_REGISTER_RESOURCE(res, &objData, resid);
RETURN_RESOURCE(res);
}
add: var_dump(test_getMydata(3,4)) in test.php
then make; make install; ./php test.php, it prints:
Functions available in the test extension:
confirm_wrap_compiled
test_getMydata
Congratulations! You have successfully modified ext/wrap/config.m4. Module wrap is now compiled into PHP.
Segmentation fault (core dumped)
$ gdb ../../bin/php core.23310
Loaded symbols for /home/user1/php/php-5.2.17/lib/php/extensions/no-debug-non-zts-20060613/test.so
#0 0x00000000006388ad in execute (op_array=0x2a9569bd68) at /home/user1/php/php-5.2.17/Zend/zend_vm_execute.h:92
92 if (EX(opline)->handler(&execute_data TSRMLS_CC) > 0) {`
Can someone give some help?
sorry for the bad formatting in the comment - here is my final answer:
i had to rename the extension from test enter code hereto hjtest - everthing else should be pretty much in line with your posted sample.
tl;dr - the problem - and SIGSEGV in your sample is that you are registering a resource to a local variable objData - wich at the end of the function is not reachable anymore - you need to use emalloc to get a piece of dynamic memory - wich holds your MYDATA
as from there you have a resource - bound to some piece of dyn. memory, you need to register a dtor function - so you can release/efree your registered memory.
hope that helps.
to solve the above issue - modifie your resource registration like this:
MYDATA * objData=emalloc(sizeof(MYDATA));
objData->m_id = a;
objData->m_age = b;
ZEND_REGISTER_RESOURCE(return_value, objData, resid);
and add a dtor:
... MINIT
resid = zend_register_list_destructors_ex(resdtor, NULL, MY_RES_NAME, module_number);
and
static void resdtor(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
MYDATA *res = (MYDATA*)rsrc->ptr;
if (res) {
efree(res);
}
}
for full sample see this GIST: https://gist.github.com/hjanuschka/3ed54e66f017a379cf25

Swift: Trouble Using Enums Declared in Objective-C, In Swift

OK. Looked at the various answers when I typed out the question, and don't see the answer listed.
This seems such a basic, fundamental issue that I MUST be doing something wrong, but I am being driven crazy (actually, not much of a "drive." More of a short putt) trying to figure out what I am getting wrong.
I have created a test project that can be downloaded here (small project).
In any case, I encountered this, when working on importing a large Objective-C SDK that I wrote into Swift.
Everything works great. Until... I try to do comparisons on enums declared in C.
Obviously, C enums are not turned into Swift enums, but I am having trouble figuring out how to use them.
Here's a sample of what you will see in the test project;
I have a couple of C files that declare enums:
#import <Foundation/Foundation.h>
typedef enum
{
StandardEnumType_Undef = 0xFF,
StandardEnumType_Value0 = 0x00,
StandardEnumType_Value1 = 0x01,
StandardEnumType_Value2 = 0x02
} StandardEnumType;
typedef NS_ENUM ( unsigned char, AppleEnumType )
{
AppleEnumType_Undef = 0xFF,
AppleEnumType_Value0 = 0x00,
AppleEnumType_Value1 = 0x01,
AppleEnumType_Value2 = 0x02
};
StandardEnumType translateIntToEnumValue ( int inIntValue );
int translateEnumValueToInt ( StandardEnumType inValue );
AppleEnumType translateIntToAppleEnumValue ( int inIntValue );
int translateAppleEnumValueToInt ( AppleEnumType inValue );
The functions mentioned do pretty much what it says on the tin. I won't include them.
I did the bridging header and all that.
I am trying to use them in the initial load of the Swift app:
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool
{
let testStandardConst:StandardEnumType = translateIntToEnumValue ( 0 )
// Nope.
// if ( testStandardConst.toRaw() == 0 )
// {
//
// }
// This don't work.
// if ( testStandardConst == StandardEnumType_Value0 )
// {
//
// }
// Neither does this.
// if ( testStandardConst == StandardEnumType_Value0.toRaw() )
// {
//
// }
// Not this one, either.
// if ( testStandardConst.toRaw() == StandardEnumType_Value0 )
// {
//
// }
let testAppleConst:AppleEnumType = translateIntToAppleEnumValue ( 0 )
// This don't work.
// if ( testAppleConst == AppleEnumType.AppleEnumType_Value0 )
// {
//
// }
// Neither does this.
// if ( testAppleConst == AppleEnumType.AppleEnumType_Value0.toRaw() )
// {
//
// }
// Nor this.
// if ( testAppleConst == .AppleEnumType_Value0 )
// {
//
// }
return true
}
I can't seem to get the $##!! enums to compare to either ints or anything else.
I am often humbled by the stupid errors I make, and sometimes need them pointed out to me, so please humble me.
Thanks!
When working with typedef NS_ENUM enums in swift you should omit enum name in comparison and assignment, here how you can compare it:
if ( testAppleConst == .Value0 ) { ... }
You can read more about this in Apple do s for Swift here.

XCode - Redefine macro

Small problem I'm having where I have an amount of objects (enemies) on the screen at one particular time and cannot redefine their value. I set my enemies to begin with 3 on the screen.
My objective is to change the amount of enemies based on the current score.
I've attached snippets of the code below.
#define kEnemies 3
- (void) EnemyIncrease
{
if (self.score>=100) {
#define kEnemies 4
}
}
// I've also tried amongst other things
#define kEnemies 3
- (void) EnemyIncrease
{
if (self.score >=100) {
#undef kEnemies
#define kEnemies 6
}
}
Would really appreciate some assistance.
I have now changed my code to the following
int numberOfEnemies;
if (self.score>=0) {
numberOfEnemies = 3
}
else if (self.score>=100) {
numberOfEnemies = 4
}
however the issue now is that the array does not update the numberOfEnemies when the score meets the new condition.
for(int i = 0; i < numberOfEnemies; i++)
Apologies I'm still new to coding and trying to modify existing code
Macros are preprocessed, that means that they are processed before the rest of your code is even compiled.
Taking out your code, that means the preprocessor sees this (using your second example). Ultimately, the value of kEnemies is 6:
#define kEnemies 3
#undef kEnemies
#define kEnemies 6
It's not really viable to use #defines for variables, I only use them for constants.
You could use a member variable:
int numberOfEnemies;
...
if (self.score >=100)
{
numberOfEnemies = 6
}
(I removed the k prefix as this style is intended for constants)