question
stringlengths
25
894
answer
stringlengths
4
863
I read it on several sites that precompiled headers and address space layout randomization is incompatible. What makes them incompatible? What would it take to fix it? My question is OS independent I heard this is a problem on linux with grsecurity and on newer windows versions. (And I don't know what else has ASLR.)...
Precompiled headers are not incompatible with ASLR. The particular technique used to implement precompiled headers that was used by older versions of the Visual C++ compiler was broken by ASLR. There isan article on the Visual C++ Team Blogwith details on the problem and an explanation of how it was fixed. There is...
I am going through a windows device driver and I saw struct code like this: ``` struct driver1 { UINT64 Readable : 1; UINT64 Writable : 1; UINT64 Executable : 1; UINT64 Control : 3; UINT64 Status : 1; UINT64 Reserved : 51; UINT64 Availabl...
This means thatReadable,WritableandExecutableeach take up a bit,Controltakes 3,Reserved51 and so on. Refer tohttp://publications.gbdirect.co.uk/c_book/chapter6/bitfields.htmlfor more info. The UINT64 simply means that the entire bitfield will be inside a 64 bit unsigned integer.
``` unsigned char x = 93; unsigned char a = x << 4; printf("a = %d\n", a); ``` I do understand how bit operators work but I don't understand the binary representation of x. How is a = 208?
``` 93 = 01011101 ``` Shift that left 4 bits and it leaves the following (only 8 bits in your result): ``` 11010000 = 208 ```
I need to create a shared vector, with the same size as the block. ``` __global__ func() { const int size = blockDim.x; __shared__ float* Vec[size]; .. } ``` I get this error ``` error : expression must have a constant value ``` I cannot understand where the problem is, sinceblockDim.xis "constant" for ...
If you look at the section about__shared__of theCUDA C++ Programming Guide, there's some text on how to specify a size for anexterndeclared shared array. Although it's a bit more complicated, this is the syntax on how to specify execution-time sized shared arrays. The way you're doing it won't work.
I'm compiling several C/C++ packages from source on Ubuntu. I compare the results from my build to running with the debian install, and find that my executables are slower. I usedreadelf -ato compare the two executables. Things like the relocation section for '.rela.dyn' are substantially different, but I'm not sure ...
Well, as it is open source, you should get the compile flags they use to generate the executables :) my2c
I want to learn OpenGL ES, but so far I don't know anything about it and I was wondering if there is a tutorial which stars from 0 knowledge. Remember that I don't know anything about graphics, drawing, etc.
This is a great start since it's specific to iPhone: OpenGL ES from the Ground Up: Table of Contents
I'm writing a program in C on Debian Linux x64. In part of the code, I have the following if statement: ``` if (*all_drops >= (npes * 128)) { break; } ``` all_dropsis anint*which has been assigned anint's worth of memory, whilenpesis anintwith the value 2. Therefore, the if statement should be true when ...
This works as intented:http://ideone.com/DjHGI I guess the problem can be in the way you're initializing*all_drops
Is there a c atoi() equivalent for wide chars on Linux? I can find something for MS (wtoi) but I can find anything in a standard Linux lib.
You can usewcstolto convert from wide strings to integer values.
So, my basic problem is that I'm trying to write a program for a small project I'm working on for fun. Basically, my issue is this: I need to take user input, as an int, say 15, then manipulate the number so that it returns the result of 1 + 5, being 6. Or for another example say the number is 29, will give you 2 + 9...
This is not a particularly good job for a regex. The usual way would be to get individual digits as the remainder after dividing by 10.
Hi does anyone know a way to send signal SIGUSR1/2 without loss to another pid ? the problem is when i put kill(pid, SIGUSR1) in a while loop, my other program recieve only few of them, its seems there is a loss and i have to wait between two calls to kill(). Im actually forced to used usleep() in my loop in order to...
You need to usesigaction()rather thansignal()becausesigaction()can control which signals are blocked while the current signal is being handled. Also, your receiver has to process each signal received; that is relatively costly compared to sending a signal, so your killer (signalling) process can outrun the 'killed' ...
For unpacking complex binary strings with mixed doubles and integers using Ruby'sString.unpackI need to determine offsets within the binary string. Commonly, doubles are 8 bytes and integers are 4 bytes, but in order to make my code machine-independent, I would like to query these sizes from within my Ruby code. What...
I have found a workable solution, by usingArray#pack, the inverse method ofString#unpack. By packing a string of 1 integer or 1 double it is possible to determine the size of integers and doubles from within ruby itself which gives the same results as usingsizeof(int)orsizeof(double)(because of the implementation ofAr...
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed5 years ago. I came across a very interesting fact while executing the following a simple c program: ``` #include<stdio.h> int main( ) { int k=0; printf("%d%d%d", k++, k, ++k); ...
It's undefined behaviour. When there are no / ambiguous sequence points. See this wikipedia article: http://en.wikipedia.org/wiki/Sequence_point
Often stacks in C are dependent upon datatype used to declare them. For example, ``` int arr[5]; //creates an integer array of size 5 for stack use char arr[5]; //creates a character array of size 5 for stack use ``` are both limited to holding integer and character datatypes respectively and presumes that the progr...
I would use a structure like this: ``` struct THolder { int dataType; // this is a value representing the type void *val; // this is the value }; ``` Then use an array ofTHolderto store your values.
EDIT: Removed code/explanation because this project has been given again and students can easily find the solution via this post. To clarify what happened, I simply passed the wrong length/size in my recvfrom() call.
In this line: ``` if(recvfrom( temp->sockfd, sendHostIP, BUFFER_LEN, 0, (struct sockaddr *)&recvAddr, &recvLen) < 0) errorMsg("recvfrom"); ``` You passBUFFER_LENas the length (256), butsendHostIPis only of lengthMAXHOSTNAMELEN(64). This causesrecvfrom()to overflow that buffer. The same problem occurs when you ...
This method in Cocos2d: ``` /** Returns opposite of point. @return CGPoint @since v0.7.2 */ static inline CGPoint ccpNeg(const CGPoint v) { return ccp(-v.x, -v.y); } ``` Why does it say 'CGPoint' after inline? Why not ``` static inline ccpNeg(... ``` ?
Because the function wants to return a CGPoint.
I need to create a shared vector, with the same size as the block. ``` __global__ func() { const int size = blockDim.x; __shared__ float* Vec[size]; .. } ``` I get this error ``` error : expression must have a constant value ``` I cannot understand where the problem is, sinceblockDim.xis "constant" for ...
If you look at the section about__shared__of theCUDA C++ Programming Guide, there's some text on how to specify a size for anexterndeclared shared array. Although it's a bit more complicated, this is the syntax on how to specify execution-time sized shared arrays. The way you're doing it won't work.
I'm compiling several C/C++ packages from source on Ubuntu. I compare the results from my build to running with the debian install, and find that my executables are slower. I usedreadelf -ato compare the two executables. Things like the relocation section for '.rela.dyn' are substantially different, but I'm not sure ...
Well, as it is open source, you should get the compile flags they use to generate the executables :) my2c
I want to learn OpenGL ES, but so far I don't know anything about it and I was wondering if there is a tutorial which stars from 0 knowledge. Remember that I don't know anything about graphics, drawing, etc.
This is a great start since it's specific to iPhone: OpenGL ES from the Ground Up: Table of Contents
I'm writing a program in C on Debian Linux x64. In part of the code, I have the following if statement: ``` if (*all_drops >= (npes * 128)) { break; } ``` all_dropsis anint*which has been assigned anint's worth of memory, whilenpesis anintwith the value 2. Therefore, the if statement should be true when ...
This works as intented:http://ideone.com/DjHGI I guess the problem can be in the way you're initializing*all_drops
Is there a c atoi() equivalent for wide chars on Linux? I can find something for MS (wtoi) but I can find anything in a standard Linux lib.
You can usewcstolto convert from wide strings to integer values.
So, my basic problem is that I'm trying to write a program for a small project I'm working on for fun. Basically, my issue is this: I need to take user input, as an int, say 15, then manipulate the number so that it returns the result of 1 + 5, being 6. Or for another example say the number is 29, will give you 2 + 9...
This is not a particularly good job for a regex. The usual way would be to get individual digits as the remainder after dividing by 10.
Hi does anyone know a way to send signal SIGUSR1/2 without loss to another pid ? the problem is when i put kill(pid, SIGUSR1) in a while loop, my other program recieve only few of them, its seems there is a loss and i have to wait between two calls to kill(). Im actually forced to used usleep() in my loop in order to...
You need to usesigaction()rather thansignal()becausesigaction()can control which signals are blocked while the current signal is being handled. Also, your receiver has to process each signal received; that is relatively costly compared to sending a signal, so your killer (signalling) process can outrun the 'killed' ...
For unpacking complex binary strings with mixed doubles and integers using Ruby'sString.unpackI need to determine offsets within the binary string. Commonly, doubles are 8 bytes and integers are 4 bytes, but in order to make my code machine-independent, I would like to query these sizes from within my Ruby code. What...
I have found a workable solution, by usingArray#pack, the inverse method ofString#unpack. By packing a string of 1 integer or 1 double it is possible to determine the size of integers and doubles from within ruby itself which gives the same results as usingsizeof(int)orsizeof(double)(because of the implementation ofAr...
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed5 years ago. I came across a very interesting fact while executing the following a simple c program: ``` #include<stdio.h> int main( ) { int k=0; printf("%d%d%d", k++, k, ++k); ...
It's undefined behaviour. When there are no / ambiguous sequence points. See this wikipedia article: http://en.wikipedia.org/wiki/Sequence_point
Often stacks in C are dependent upon datatype used to declare them. For example, ``` int arr[5]; //creates an integer array of size 5 for stack use char arr[5]; //creates a character array of size 5 for stack use ``` are both limited to holding integer and character datatypes respectively and presumes that the progr...
I would use a structure like this: ``` struct THolder { int dataType; // this is a value representing the type void *val; // this is the value }; ``` Then use an array ofTHolderto store your values.
EDIT: Removed code/explanation because this project has been given again and students can easily find the solution via this post. To clarify what happened, I simply passed the wrong length/size in my recvfrom() call.
In this line: ``` if(recvfrom( temp->sockfd, sendHostIP, BUFFER_LEN, 0, (struct sockaddr *)&recvAddr, &recvLen) < 0) errorMsg("recvfrom"); ``` You passBUFFER_LENas the length (256), butsendHostIPis only of lengthMAXHOSTNAMELEN(64). This causesrecvfrom()to overflow that buffer. The same problem occurs when you ...
In reference to the thread:memmove implementation in C, I did not understand why would there be a memory overlap for 2 different variables? i.e. is this a normal scenario that the compiler allocates same 'common space' to 2 different variables and why is this policy used by compilers in such cases?
Nothing to do with the compiler. Consider the following: ``` int x[100]; memmove(&x[1], &x[0], 99*sizeof(int)); ```
``` int x = 5; int *xPtr = &x; void **xPtrPtr = &xPtr; printf("%d\n", *(int*)*xPtrPtr); ``` I have a void pointer pointing to an int pointer. What is the syntax for properly casting the void pointer when I want to dereference? The above code quits with: ``` error: invalid conversion from ‘int**’ to ‘void**’ ``` Tha...
For void pointers, you don't really need to know how many indirections there are. ``` #include <iostream> int main(void){ int x = 5; int* pX = &x; void* pV = &pX; std::cout << "x = " << **(int**)pV << std::endl; // better use C++-Style casts from the beginning // or you'll be stuck with the la...
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed12 years ago.Improve this question If you hit any non-existent page on SO, likehttps://stackoverflow.com/not-found, you'll see a small code snippet on the ri...
This might get closed as a duplicate on meta too, since it's been answeredhere. The suggestion for it ishere.
Hello every one I have following function in c and want to map in JNA what could be equivlent of this in JNA. 2.3. SI_Open Description: Opens a device (using device number as returned by SI_GetNumDevices) and returns a handle which will be used for subsequent accesses. ``` SI_STATUS SI_Open (DWORD DeviceNum, HANDL...
SI_STATUSis not a common type you should look at your header file for this answer I will take for granted thatSI_STATUStype isDWORD(or 32 bit integer). This would give the following mapping in jna ``` int SI_Open(int DeviceNum, PointerByReference handle) ```
Hi All I wrote a static library (libA) that uses another library (libB). How can I link libB to my libA in eclipse (linux)? i cannot find linkage options in project properties, they are not on there usual place. Thx
Static libraries don't link. They are an archive of object files (.ofiles). These archives are then taken as arguments during a linking phase, have their object files extracted and linked into the application at that time. As such, static libraries cannot link against anything.
``` x=4+2%-8; ``` This gives output=6 Please anyone explain how?
x=4+2%-8;is equivalent tox = 4 + (2 % -8);which givesx = 4 + 2which is 6. More:C Operator Precedence Table
I have a simple question How to simply convert integer (getting values 0-8) to char, e.g. char[2] in C? Thanks
``` main() { int i = 247593; char str[10]; sprintf(str, "%d", i); // Now str contains the integer as characters } ``` Hope it will be helpful to you.
I am working on a iPhone game. Everything is working fine, but what is the correnct way to reset a array of ints in Objective-C? The array holds the coordinates for walls in each level. The array is set, every time a new level is loaded - But how can i "clear" the array? LevelData.h ``` int wallH[50][2]; int wallV[5...
You can zero array usingmemsetfunction (in your case you know the number of elements in array so you can use "hardcoded" 100 determining size): ``` memset(wallH, 0, 100*sizeof(wallH[0][0]); ```
What is the benefit of usingNSNumberfrom Foundation Framework instead of basic C types (int, float, double)? Using NSNumber: ``` NSNumber *intNumber; NSInteger myInt; intNumber = [NSNumber numberWithInteger: 100]; myInt = [intNumber integerValue]; ``` Using pure C: ``` int intNumber; intNumber = 100; ``` Seems a ...
The purpose ofNSNumberis simply to box primitive types in objects (pointer types), so you can use them in situations that require pointer-type values to work. One common example: you have to useNSNumberif you want to persist numeric values in Core Data entities. You can and should use primitives for calculations (un...
I have written my own assertion debug. ``` #define ASSERT_EQUALS(a,b) \ do { \ if ((a)!=(b)) \ { \ printf(". ASSERT_EQUALS (%s:%d) %d!=%d\n",__FUNCTION__,__LINE__,a,b); \ } \ } while (0) ``` However its only compatible with integer types. Is there a way I can change this so I can support float/do...
Maybe you should just print them as floats. ``` #define ASSERT_EQUALS(a, b) \ do { \ if ((a)!=(b)) { \ printf(". ASSERT_EQUALS (%s:%d) %f!=%f\n",__FUNCTION__,__LINE__,(float)(a),(float)(b)); \ } \ } while (0) ``` It looks bad with integers, for example1will show up as1.00000, but it will work for b...
I've a question about passing in parameters via the command line. Mymain()looks like ``` int main(int argc, char **argv){ int b, d, n, flag; char *init_d, tst_dir[100]; argv++; init_d=*(argv++); //printf(); <--------What do I have to do to init_d so that I can print it later? ``` Ifargvis a pointer to ...
You can print the arguments without transferring them into character arrays. They are null-terminated C strings andprintfeats them for breakfast: ``` for (i=0; i<argc; i++) printf("%s\n", argv[i]); ```
Is there any mechanism to send asynchronous events/signals through JNI from C to Java or viceversa? I need to catch a signal/event from C to Java.
It sounds a bit tricky, as JNI is supposed to be one-way only: Java code can invoke a native method, which of course may call back into Java code, but can't itself initiate the process. But it isn't impossible, I think the most straightforward solution is to have a native call that blocks until the signal is received...
It is little bit weird. I just play with the unsigned char type and negative values. I have the following code. ``` #include <stdio.h> int main(int argc, char* agrv[]){ unsigned char c = -3; printf("%d, %u, %d, %u\n", c, c, ~c, ~c); } ``` The output is, ``` 253, 253, -254, 4294967042 ``` I can not figure ...
The%dformat prints out anint, and%uprints out anunsigned int. All arithmetic onunsigned charvalues is done by first casting them tointand doing the operations onintvalues, and so~c(which is equal to-1 - (int)c) will return a negativeintvalue. An explicit cast would be needed to get theunsigned charresult before prin...
In reference to the thread:memmove implementation in C, I did not understand why would there be a memory overlap for 2 different variables? i.e. is this a normal scenario that the compiler allocates same 'common space' to 2 different variables and why is this policy used by compilers in such cases?
Nothing to do with the compiler. Consider the following: ``` int x[100]; memmove(&x[1], &x[0], 99*sizeof(int)); ```
``` int x = 5; int *xPtr = &x; void **xPtrPtr = &xPtr; printf("%d\n", *(int*)*xPtrPtr); ``` I have a void pointer pointing to an int pointer. What is the syntax for properly casting the void pointer when I want to dereference? The above code quits with: ``` error: invalid conversion from ‘int**’ to ‘void**’ ``` Tha...
For void pointers, you don't really need to know how many indirections there are. ``` #include <iostream> int main(void){ int x = 5; int* pX = &x; void* pV = &pX; std::cout << "x = " << **(int**)pV << std::endl; // better use C++-Style casts from the beginning // or you'll be stuck with the la...
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed12 years ago.Improve this question If you hit any non-existent page on SO, likehttps://stackoverflow.com/not-found, you'll see a small code snippet on the ri...
This might get closed as a duplicate on meta too, since it's been answeredhere. The suggestion for it ishere.
Hello every one I have following function in c and want to map in JNA what could be equivlent of this in JNA. 2.3. SI_Open Description: Opens a device (using device number as returned by SI_GetNumDevices) and returns a handle which will be used for subsequent accesses. ``` SI_STATUS SI_Open (DWORD DeviceNum, HANDL...
SI_STATUSis not a common type you should look at your header file for this answer I will take for granted thatSI_STATUStype isDWORD(or 32 bit integer). This would give the following mapping in jna ``` int SI_Open(int DeviceNum, PointerByReference handle) ```
Hi All I wrote a static library (libA) that uses another library (libB). How can I link libB to my libA in eclipse (linux)? i cannot find linkage options in project properties, they are not on there usual place. Thx
Static libraries don't link. They are an archive of object files (.ofiles). These archives are then taken as arguments during a linking phase, have their object files extracted and linked into the application at that time. As such, static libraries cannot link against anything.
``` x=4+2%-8; ``` This gives output=6 Please anyone explain how?
x=4+2%-8;is equivalent tox = 4 + (2 % -8);which givesx = 4 + 2which is 6. More:C Operator Precedence Table
I have a simple question How to simply convert integer (getting values 0-8) to char, e.g. char[2] in C? Thanks
``` main() { int i = 247593; char str[10]; sprintf(str, "%d", i); // Now str contains the integer as characters } ``` Hope it will be helpful to you.
I am working on a iPhone game. Everything is working fine, but what is the correnct way to reset a array of ints in Objective-C? The array holds the coordinates for walls in each level. The array is set, every time a new level is loaded - But how can i "clear" the array? LevelData.h ``` int wallH[50][2]; int wallV[5...
You can zero array usingmemsetfunction (in your case you know the number of elements in array so you can use "hardcoded" 100 determining size): ``` memset(wallH, 0, 100*sizeof(wallH[0][0]); ```
What is the benefit of usingNSNumberfrom Foundation Framework instead of basic C types (int, float, double)? Using NSNumber: ``` NSNumber *intNumber; NSInteger myInt; intNumber = [NSNumber numberWithInteger: 100]; myInt = [intNumber integerValue]; ``` Using pure C: ``` int intNumber; intNumber = 100; ``` Seems a ...
The purpose ofNSNumberis simply to box primitive types in objects (pointer types), so you can use them in situations that require pointer-type values to work. One common example: you have to useNSNumberif you want to persist numeric values in Core Data entities. You can and should use primitives for calculations (un...
I have written my own assertion debug. ``` #define ASSERT_EQUALS(a,b) \ do { \ if ((a)!=(b)) \ { \ printf(". ASSERT_EQUALS (%s:%d) %d!=%d\n",__FUNCTION__,__LINE__,a,b); \ } \ } while (0) ``` However its only compatible with integer types. Is there a way I can change this so I can support float/do...
Maybe you should just print them as floats. ``` #define ASSERT_EQUALS(a, b) \ do { \ if ((a)!=(b)) { \ printf(". ASSERT_EQUALS (%s:%d) %f!=%f\n",__FUNCTION__,__LINE__,(float)(a),(float)(b)); \ } \ } while (0) ``` It looks bad with integers, for example1will show up as1.00000, but it will work for b...
I've a question about passing in parameters via the command line. Mymain()looks like ``` int main(int argc, char **argv){ int b, d, n, flag; char *init_d, tst_dir[100]; argv++; init_d=*(argv++); //printf(); <--------What do I have to do to init_d so that I can print it later? ``` Ifargvis a pointer to ...
You can print the arguments without transferring them into character arrays. They are null-terminated C strings andprintfeats them for breakfast: ``` for (i=0; i<argc; i++) printf("%s\n", argv[i]); ```
Is there any mechanism to send asynchronous events/signals through JNI from C to Java or viceversa? I need to catch a signal/event from C to Java.
It sounds a bit tricky, as JNI is supposed to be one-way only: Java code can invoke a native method, which of course may call back into Java code, but can't itself initiate the process. But it isn't impossible, I think the most straightforward solution is to have a native call that blocks until the signal is received...
Hello every one I have following function in c and want to map in JNA what could be equivlent of this in JNA. 2.3. SI_Open Description: Opens a device (using device number as returned by SI_GetNumDevices) and returns a handle which will be used for subsequent accesses. ``` SI_STATUS SI_Open (DWORD DeviceNum, HANDL...
SI_STATUSis not a common type you should look at your header file for this answer I will take for granted thatSI_STATUStype isDWORD(or 32 bit integer). This would give the following mapping in jna ``` int SI_Open(int DeviceNum, PointerByReference handle) ```
Hi All I wrote a static library (libA) that uses another library (libB). How can I link libB to my libA in eclipse (linux)? i cannot find linkage options in project properties, they are not on there usual place. Thx
Static libraries don't link. They are an archive of object files (.ofiles). These archives are then taken as arguments during a linking phase, have their object files extracted and linked into the application at that time. As such, static libraries cannot link against anything.
``` x=4+2%-8; ``` This gives output=6 Please anyone explain how?
x=4+2%-8;is equivalent tox = 4 + (2 % -8);which givesx = 4 + 2which is 6. More:C Operator Precedence Table
I have a simple question How to simply convert integer (getting values 0-8) to char, e.g. char[2] in C? Thanks
``` main() { int i = 247593; char str[10]; sprintf(str, "%d", i); // Now str contains the integer as characters } ``` Hope it will be helpful to you.
I am working on a iPhone game. Everything is working fine, but what is the correnct way to reset a array of ints in Objective-C? The array holds the coordinates for walls in each level. The array is set, every time a new level is loaded - But how can i "clear" the array? LevelData.h ``` int wallH[50][2]; int wallV[5...
You can zero array usingmemsetfunction (in your case you know the number of elements in array so you can use "hardcoded" 100 determining size): ``` memset(wallH, 0, 100*sizeof(wallH[0][0]); ```
What is the benefit of usingNSNumberfrom Foundation Framework instead of basic C types (int, float, double)? Using NSNumber: ``` NSNumber *intNumber; NSInteger myInt; intNumber = [NSNumber numberWithInteger: 100]; myInt = [intNumber integerValue]; ``` Using pure C: ``` int intNumber; intNumber = 100; ``` Seems a ...
The purpose ofNSNumberis simply to box primitive types in objects (pointer types), so you can use them in situations that require pointer-type values to work. One common example: you have to useNSNumberif you want to persist numeric values in Core Data entities. You can and should use primitives for calculations (un...
I have written my own assertion debug. ``` #define ASSERT_EQUALS(a,b) \ do { \ if ((a)!=(b)) \ { \ printf(". ASSERT_EQUALS (%s:%d) %d!=%d\n",__FUNCTION__,__LINE__,a,b); \ } \ } while (0) ``` However its only compatible with integer types. Is there a way I can change this so I can support float/do...
Maybe you should just print them as floats. ``` #define ASSERT_EQUALS(a, b) \ do { \ if ((a)!=(b)) { \ printf(". ASSERT_EQUALS (%s:%d) %f!=%f\n",__FUNCTION__,__LINE__,(float)(a),(float)(b)); \ } \ } while (0) ``` It looks bad with integers, for example1will show up as1.00000, but it will work for b...
I've a question about passing in parameters via the command line. Mymain()looks like ``` int main(int argc, char **argv){ int b, d, n, flag; char *init_d, tst_dir[100]; argv++; init_d=*(argv++); //printf(); <--------What do I have to do to init_d so that I can print it later? ``` Ifargvis a pointer to ...
You can print the arguments without transferring them into character arrays. They are null-terminated C strings andprintfeats them for breakfast: ``` for (i=0; i<argc; i++) printf("%s\n", argv[i]); ```
Is there any mechanism to send asynchronous events/signals through JNI from C to Java or viceversa? I need to catch a signal/event from C to Java.
It sounds a bit tricky, as JNI is supposed to be one-way only: Java code can invoke a native method, which of course may call back into Java code, but can't itself initiate the process. But it isn't impossible, I think the most straightforward solution is to have a native call that blocks until the signal is received...
It is little bit weird. I just play with the unsigned char type and negative values. I have the following code. ``` #include <stdio.h> int main(int argc, char* agrv[]){ unsigned char c = -3; printf("%d, %u, %d, %u\n", c, c, ~c, ~c); } ``` The output is, ``` 253, 253, -254, 4294967042 ``` I can not figure ...
The%dformat prints out anint, and%uprints out anunsigned int. All arithmetic onunsigned charvalues is done by first casting them tointand doing the operations onintvalues, and so~c(which is equal to-1 - (int)c) will return a negativeintvalue. An explicit cast would be needed to get theunsigned charresult before prin...
What is a good way to detect bugs where I overwrite an array bound? ``` int a[100]; for (int i = 0; i<1000; i++) a[i] = i; ``` It would be helpful to collect a list of different strategies that people have used in their experience to uncover bugs of this type. For example, doing a backtrace on from the point of the ...
Valgrind will spot this sort of thing pretty reliably!
In C Programming language and I use 32 bit system, I have a struct and this struct size is multiple of four. But I look at Linker Map file and size is multiple of eight Example ``` typedef struct _str { U64 var1, U32 var2 } STR; ``` Size of this struct is 16. But ``` typedef struct _str { U32 var1, U32 var2, U32 va...
The first structure is padded in order to get it aligned on a U64 boundary: it is equivalent to ``` struct STR { U64 var1; U32 var2; U8 pad[4]; /* sizeof(U64) - sizeof(U32) */ }; ``` So when used in an array of struct STR [], each U64 is well aligned regarding to ABI requirements. Have a look atProcedu...
Is there alternative forstrrev()in C? I am interested in a function that does the same but it must be included in the standard library. I am aware that operation can be easily implemented by user defined function but I am looking for a library alternative.Precisely there are few functions take for examplerindex(ident...
As far as I know, there is no such a function in C standard libraries. If you don't mind using C++, there isreversetemplate function inalgorithms.
I am learning about OpenMP concurrency, and tried my hand at some existing code I have. In this code, I tried to make all the for loops parallel. However, this seems to make the program MUCH slower, at least 10x slower, or even more than the single threaded version. Here is the code:http://pastebin.com/zyLzuWU2 I al...
One problem I see with your code is that you are using OpenMP across loops that are very small (8 or 64 iterations, for example). This will not be efficient due to overheads. If you want to use OpenMP for the n-queens problem, look at OpenMP 3.0 tasks and thread parallelism for branch-and-bound problems.
What are the possible effect of returning a static type data. And when should we actually use it? ``` static ssize_t my_read(int fd, char *ptr) { //code from Stevens Unix Network programming. if (something) return (-1) if (something else) return (0) return (1) } ``` why st...
The function is static, not the return type. This means that its name is only visible from within the current compilation unit, which is used as an encapsulation mechanism. The function can still be called from elsewhere through a function pointer, however. See alsothis discussion on the generalstatickeywordfor more...
I have the following old c code. ``` const char *c[3]; c[0] = "ABC"; c[1] = "EFG"; c[2] = 0; c_function(c); ``` Now, I need to use Python to call old c function. I have the following code. ``` c_names = (c_char_p * 3)() c_names[0] = "ABC"; c_names[1] = "EFG"; // c[2] = 0?? libc = CDLL("c_library.dll") libc.c_functi...
Noneand0both work: ``` >>> import ctypes >>> x=ctypes.c_char_p(0) >>> x c_char_p(None) >>> x=ctypes.c_char_p(None) >>> x c_char_p(None) ```
we gotif(expression) {...}for example. We all know if expression is true, it will execute lines in braces. But what is "True" in C? Is that != 0 means true as I think? Thank you
Here is what the standard has to say. §6.8.4 Selection statementsSyntaxselection-statement:if ( expression ) statementif ( expression ) statement else statementswitch ( expression ) statement§6.8.4.1 TheifstatementConstraintsThe controlling expression of an if statement shall have scalar type.SemanticsIn both forms, ...
``` /* 180 * Create a regular file 181 */ 182 static int 183 ufs_create(ap) 184 struct vop_create_args /* { 185 struct vnode *a_dvp; 186 struct vnode **a_vpp; 187 struct componentname *a_cnp; 188 struct vattr *a_vap; 189 ...
The return type isintand it takes one argument, astruct vop_create_args*namedap. This is K&R notation.
Is it possible to implementstrlen()in theCpreprocessor? Given: ``` #define MYSTRING "bob" ``` Is there some preprocessor macro,X, which would let me say: ``` #define MYSTRING_LEN X(MYSTRING) ```
It doesn't use the preprocessor, but sizeof is resolved at compile time. If your string is in an array, you can use that to determine its length at compile time: ``` static const char string[] = "bob"; #define STRLEN(s) (sizeof(s)/sizeof(s[0])) ``` Keep in mind the fact thatSTRLENabove will include the null terminat...
``` #include <stdio.h> #include <stdlib.h> int main() { char a[]="shevchenko ac milan"; printf("%s",&a); } ``` This is prints "shevchenko ac milan" ``` but #include <stdio.h> #include <stdlib.h> int main() { char a[]="shevchenko ac milan"; printf("%s",&a+1); } ``` Why does this print junk characters?
&ais of typepointer to achar[20]. When you do&a+1you'll go to the nextchar[20]item in memory, thus you'll go aftera. You should instead have achar*: by summing 1 to it you'll go to the nextchar. To obtain achar*you can just usea(it decays in achar*by doing this), and thusa+1to go the next char.
``` #include <stdio.h> #include <stdlib.h> int main() { char a="9jhjhi"; printf("%s",a); } ``` Why does this throw a segmentation fault? What happens behind the screens?
You need to usechar *a = "...". printfwhen passed%swill run through a string looking for a0/NULLbyte. In your case you are not assigning a string literal toa, and in fact your compiler should have thrown a warning that you were trying to initialize acharfrom a pointer. ``` #include <stdio.h> #include <stdlib.h> int ...
The following line of code was calling thecurrentPlaybackTimemethod on my singletonMAMusicPlayerclass twice: ``` float trackPosition = MAX(floor([[MAMusicPlayer sharedPlayer] currentPlaybackTime]),0.0f); [scrubber setValue:trackPosition]; ``` Through trial and error I managed to resolve the issue by adjusting the co...
MAX(a, b)is probably a macro defined as((a > b) ? a : b), so when terms are substituted foraandb, each term is evaluated twice.
Is there any reason why I never see main's prototype declared in C programs, ie: ``` int main(int argc, char* argv[]); int main(int argc, char* argv[]) { return 0; } ``` Always seemed inconsistent..
C language standard, draftn1256: 5.1.2.2.1 Program startup1 The function called at program startup is namedmain.The implementation declares no prototype for this function. It shall be defined with a return type ofintand with no parameters:int main(void) { /* ... */ }or with two parameters (referred to here asargcanda...
This question already has answers here:Closed12 years ago. Possible Duplicate:Is there a performance difference between i++ and ++i in C++? I understand that: ``` i++; ``` Is supposed to take more instructions than ``` ++i; ``` Because it's generating an intermediate result that you don't need to use, so people ...
It does not matter when using it on anint. However, when using iterators or other objects that overloadoperator++, it might still make a difference.
is there a macro or a global variable which through which I can learn about the name of the object file the current translation unit will be used for in C? I am only aware of the source file macro. Thanks.
Not in standard C. The preprocessor may be implemented as a separate program that has no knowledge of object files, so it can't be a built-in macro. A compiler could in theory produce a symbol with the object file name, but that would be invalidated as soon as the object file is renamed by the user. You can get the...
In What lines will this code fail (meaning: don't do what they are supposed to do), and why? ``` int main(void) { char student[64] = "some guy"; char* teacher; /* line1 */ strcpy(teacher, student); /* line2 */ teacher=student; /* line3 */ strcpy(student, "Alber Einstein"); /* line4 */ student = teacher; } ```
Line 1 causes undefined behaviour. Line 4 won't even compile. Since this seems like it could just as easily be a homework question, and I don't like to give the whole thing away, a quick read of thecomp.lang.c FAQor theC language specificationwill explain why.
What will be printed out? 6 6 or 6 7? And why? ``` void foo() { static int x = 5; x++; printf("%d", x); } int main() { foo(); foo(); return 0; } ```
There are two issues here, lifetime and scope. The scope of variable is where the variable name can be seen. Here,xis visible only inside functionfoo(). The lifetime of a variable is the period over which it exists. Ifxwere defined without the keywordstatic, the lifetime would be from the entry intofoo()to the ret...
i am beginner in c programming, i am currently using gedit of ubuntu 10.04 to write c prog, i want to plot a graph, but i am able to do it, can any one tell me hw it can be done or else is there any way to extract the data from the output to spreadsheet where i can plot the req, graph?? I appreciate your help..n thanx...
Medsphere has some pretty greatGTK# widgetsfor graphing (among other things), but you'll need to be a little more clear about your input/output requirements to get more specific help.
running the configure script for mozart oz gives me this: checking for stdint.h... (cached) yeschecking for gethostbyaddr in -lnsl... nochecking for gethostbyaddr in -lc... nochecking for gethostbyaddr... noconfigure: error: Function gethostbyaddr is not available.The system cannot be built. configure: error: /home/...
do a sudo apt-get install tk-dev tcl-dev build-essential libc6-dev g++-multilib ia32-libs lib32z1-dev lib32gmp3-dev this fixes it.
From msdn For functions declared with the naked attribute, the compiler generates code without prolog and epilog code. You can use this feature to write your own prolog/epilog code sequences using inline assembler code. Naked functions are particularly useful in writing virtual device drivers. ``` __d...
Prolog: Code that runs before the function body, typically code that handles function entry and argument handling. Epilog: Code that runs after the function body, typically code that handles return of function and return value. With "naked" you have to/get the opportunity to write this stuff yourself.
I'm giving a try at OpenCL, and in order to put this in production I'd like to be able to bind dynamically to OpenCL.DLL (when under Windows), in order to handle 'gracefully' the case where no OpenCL is installed on the host computer. Is there any available library (or code snippet) that takes care of this dynamic bi...
Here you go: http://clcc.sourceforge.net/clew_8h.html
Yesterday on an interview the interviewer asked me a question: Why doesn't the following code give the desired answer? ``` int a = 100000, b = 100000; long int c = a * b ; ``` The language is C. I've told the interviewer that we count first the 100,000 * 100,000 as an int(overflow) and just then cast it to long.
I'm guessing the clue would be aninteger overflowto occur, but with such low values, I don't see that happening. Maximum (positive) value for int (usually 32bit) is:2,147,483,647 The result of your calculation is:100,000,000 UPDATE: With your updated question:100000 * 100000instead of10000 * 10000results in10,000,...
I'm trying to convert a string to a double, but since I'm working on a Windows native application (as in linking only to ntdll.dll), I don't have most of the standard library available. I can use basic FP support in math.h, but that's basically it. How do I convert a string to the double closest to the rational numbe...
If you really want to get the nearest, the problem is quite hard and you need arbitrary precision arithmetic to achieve that result. Seeftp://ftp.ccs.neu.edu/pub/people/will/howtoread.psfor instance.
I have this particular problem where i have to write a c program that reads numerical data from a text file. The data is tab delimited. Here is a sample from the text file. ``` 1 23099 345565 345569 2 908 66766 66768 ``` This is data for clients and each client has a row.Each column represents customer ...
The easiest way is to create a csv file and not a xls file. Office can open those csv files with good results. And it is way easier to create a ascii text file with commaseparated values, than to create something into a closed format like the ms office formats.
Here is my code. ``` if(fseek(file,position,SEEK_SET)!=0) { throw std::runtime_error("can't seek to specified position"); } ``` I used to assume that even ifpositionis greater than num of characters in file this code would work correct (i.e. throw error), but it wouldn't. So I want to know how can I handle seeking...
Well, you can always check for file length before doing thefseek. ``` void safe_seek(FILE* f, off_t offset) { fseek(f, 0, SEEK_END); off_t file_length = ftell(f); if (file_length < offset) { // throw! } fseek(f, offset, SEEK_SET); } ``` Be aware though that this is not thread safe.
I know that using isDialogMessage() function we can able to switch the focus from one control to another. My doubt is is it possible to override that the control should focus from first button to third button.If possible how to customize WS_TABSTOP property I also like to know that on what basis the focus is shifted...
The order for tab stop depends on the order in which the controls have been added on the dialog. You can open the dialog in the resource editor in Visual Studio and pressCTRL+Dto see and modify the tab order. To modify just press on the number that appears in the top left of the control. The control with the number 1...
Is it possible to somehow refer to the value I am returning from a function? An example explains better: ``` CFTypeRef foo() { CFTypeRef valueRef = NULL; bar(&valueRef); // fills valueRef with some data return valueRef; } ``` I thought it would be nice to rewrite this as: ``` CFTypeRef foo() { bar(&...
This is not possible. At a low level, the return value is usually returned in a processor register, making it impossible to pass as a reference.
I am wondering what the difference is between these two variables in C: ``` float price = 3.00; ``` and ``` float price = 3.00f; ``` What is the use of suffixfin this case?
3.00is interpreted as adouble, as opposed to3.00fwhich is seen by the compiler as afloat. Thefsuffix simply tells the compiler which is afloatand which is adouble. SeeMSDN (C++)
By using functions like prctl, or pthread_set_name_np it's possible to change the name of a thread. The limit both functions imposes, at least in Linux 2.6.38, is that the name cannot be longer than 15 characters (NULL termination being the 16th byte). Where is this 15 character limit imposed, and is there any (even ...
15-char limit is enforced by the kernel: ``` struct task_struct::comm[TASK_COMM_LEN] ``` which is 16-byte wide. You have to recompile the kernel if you want to increase that.
Can we generate Control flow graph of the c program by Turbo C compiler? I want to know that there is something given by the compiler to generate a CFG of a C program.
Don't think Turbo C has this feature. Though, modern IDEs have capabilities to draw Class Diagrams, but I personally haven't seen any IDEs drawing Flow diagrams. Edit: Hereis a list of tools that does what you want to achieve.
friends, I have a piece of code which can perform simple add, subtraction, multiplication, division, and formula with brackets. Is there some kind of conversion tool for translating code from C to Smalltalk? Or any other relatively easy way to achieve this? Thanks in advance.
This should be trivial to write withPetitParser
What are the possible effect of returning a static type data. And when should we actually use it? ``` static ssize_t my_read(int fd, char *ptr) { //code from Stevens Unix Network programming. if (something) return (-1) if (something else) return (0) return (1) } ``` why st...
The function is static, not the return type. This means that its name is only visible from within the current compilation unit, which is used as an encapsulation mechanism. The function can still be called from elsewhere through a function pointer, however. See alsothis discussion on the generalstatickeywordfor more...
I have the following old c code. ``` const char *c[3]; c[0] = "ABC"; c[1] = "EFG"; c[2] = 0; c_function(c); ``` Now, I need to use Python to call old c function. I have the following code. ``` c_names = (c_char_p * 3)() c_names[0] = "ABC"; c_names[1] = "EFG"; // c[2] = 0?? libc = CDLL("c_library.dll") libc.c_functi...
Noneand0both work: ``` >>> import ctypes >>> x=ctypes.c_char_p(0) >>> x c_char_p(None) >>> x=ctypes.c_char_p(None) >>> x c_char_p(None) ```
we gotif(expression) {...}for example. We all know if expression is true, it will execute lines in braces. But what is "True" in C? Is that != 0 means true as I think? Thank you
Here is what the standard has to say. §6.8.4 Selection statementsSyntaxselection-statement:if ( expression ) statementif ( expression ) statement else statementswitch ( expression ) statement§6.8.4.1 TheifstatementConstraintsThe controlling expression of an if statement shall have scalar type.SemanticsIn both forms, ...
``` /* 180 * Create a regular file 181 */ 182 static int 183 ufs_create(ap) 184 struct vop_create_args /* { 185 struct vnode *a_dvp; 186 struct vnode **a_vpp; 187 struct componentname *a_cnp; 188 struct vattr *a_vap; 189 ...
The return type isintand it takes one argument, astruct vop_create_args*namedap. This is K&R notation.
Does -fomit-frame-pointeralwaysomit the frame pointer? Is there ever a situation where both the pc and fp need to be setup? Does dynamic stack growth force the fp to be setup? Asking specifically for MIPS32. Thanks!
The frame pointer is not really needed for correct execution, except sometimes for exception unwind. Dynamic stack growth usually requires some kind of a frame pointer, but it is not tied to a particular register, but rather allocated through normal data flow analysis. Basically,-fomit-frame-pointerdemotes the FP fro...
Is there a "good" way to write "pointer to something" in C/C++ ?I use to writevoid foo( char *str );But sometimes I find it quite illogical because the type ofstris "pointer to char", then it should more logical to attach the*to the type name.Is there a rule to write pointers ? ``` char*str; char* str; char *str; cha...
There is no strict rule, but bear in mind that the*attaches to the variable, so: ``` char *str1, *str2; // str1 and str2 are pointers char* str1, str2; // str1 is a pointer, str2 is a char ``` Some people like to dochar * str1as well, but it's up to you or your company's coding standard.
I want to check a header in my source file and if its already defined, I want to undefine it. Is it possible?
#undefis the opposite of#defineand actually cancels it. It's very useful when you need a macro for some task but does not wish to "pollute" the symbol tables ``` // referencing FOO is an error (not yet defined) #define FOO(arg_) .... FOO(A) FOO(B) FOO(C) #undef FOO // referencing FOO now is an error (not defined...
I have a sorted array ( in ascending order) and I want to find the subscript of a number in the array which is the the next highest number to a given number. For example,if I have 67 as a given number and if I have an array x=(23,36,45,62,79,103,109), then how do I get the subscript 5 from x (to get 79 which is...
Is this homework? You can do it pretty easily with a recursive call, splitting the array in half each time.