question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
This code raises segmentation fault on the last line. Header is a pointer to a contiguous block of memory which is all 0, and dereferencing the remainder returns 0 which is probably related to the issue. I still feel like this should work though, what is the issue?
```
void setHeader(void *header, size_t payload) {
... |
Why do you think this should work? Unless the pointed-to object is sufficiently large that addingpayload + 4does not exceed the size of the object, the pointer arithmetic has undefined behavior. Even if the arithmetic is defined (e.g. if the object size is exactlypayload + 4), dereferencing the slot one past the end o... |
I am working on a project which requires the understanding ofllvmcompiler source-code. To browse source code of llvm, I tried to use cscope with following command in the root directory of the source:
cscope -R *
But it doesn't work. As there are mainly .cpp and .h files but some .c files are also there. So now I don... |
You can use following commands to do the required task from the root directory of llvm source tree:
```
touch tags.lst
find | grep "\.c$" >> tags.lst
find | grep "\.cpp$" >> tags.lst
find | grep "\.h$" >> tags.lst
cscope -i tags.lst
```
It would create cscope.out file which is used with cscope to browse the code. Ho... |
I tried the following two approaches. When I test it in a small program, both seem to work. But it could be possible that memory is coming from the OS which will be zeroed by default.
Approach1:
```
int n_var = 1000;
double *vars = malloc(n_var*sizeof(*vars));
if(!vars) die("Memory error.");
memset(vars, 0, n_var*s... |
Theoretically, nothing mandates that the representation of 0.0 is all bit clear and thus you should initialize explicitly.
Practically, the most common double formats have this property and both ways will works.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
The following took 0.0260015 seconds
```
for (i = 0 ; i < 10000000 ; i += 2)
```
And this took 0.0170010
```
for (i = 0 ; i < 10000000 ; i = i + 2)
```
@MasterID is right though when I enabled 'optimize code' both reported 0.0150009 seconds
|
How can I get the PID of the user process which triggered my Kernel module'sfile_operation.readroutine (i.e., which process is reading/dev/mydev) ?
|
When your read function is executing, it's doing so in the context of the process that issued the system call. You should thus pe able to usecurrent, i.e.current->pid.
|
I need that code for my program to have colors. But it wont compile if i use -pedantic. Is there a way around this? its btw
```
gcc -pedantic MP1.c -o hahah
MP1.c: In function `main':
MP1.c:65: warning: ISO C90 forbids mixed declarations and code
MP1.c:686:30: warning: (this will be reported only once per input file... |
Move declaration oforiginalAttrsto the top of the scope in which it is used. The error is unrelated to use ofConsoleInfo.wAttributesbut to the location of the declaration oforiginalAttrs. Without seeing the entire code, it is probably something like:
```
printf("hello\n"); /* For example. */
int originalAttrs = Conso... |
I'm trying to make small program which will tell mi which files are and which files aren't included in my application. I tried to use this Regex:
```
#include (<|")([^\r\n;#">]*)(>|")
```
It works good but it also gets wrong output as correct:
```
#include <stdio.h"
```
This is impossible in C compiler.
So questio... |
```
#include (?:<([^\r\n;#">]*)>|"([^\r\n;#">]*)")
```
So instead of accepting[<"]x[>"]you accept<x>or"x".Example.
|
Is it possible to do these things from a nativeCorC++-compiled program (gcc):
Callclangand compile givenCcode of a function, passed asconst char *.Obtain a pointer and run it in the LLVM virtual machine.Acquire the result in the native program and continue.
How?
|
For a minimalistic example, seeClang interpreter.
Clingis bit more practical example of such an approach.
|
Consider this simple problem:
Suppose I have a 1x4 array. I have to add 5 to each of its element. Then is it advisable to use a loop. Removing the size of code factor & good organization of code, is there any other reason why I should use a loop? Wont it take more time than executing 4 straight lines of code wherein ... |
You don't really need to worry about this. Write the way you find it easier to read, then let the compiler decide whether it finds it necessary to perform some loop unrolling optimization. Trust compiler vendors, their developers are very good at understanding these kinds of optimization-related stuff...
|
Are there any helper methods to traverse the AST, basic blocks etc. generated by LLVM compiler for a C code ?
|
If you're trying to load a module (from a .bc file compiled from a .c file byclang -emit-llvm) and traverse its functions, basic blocks, etc., then you might want to start with thellvm::Moduleclass. It has functions for iterating through global variables and functions. Then thellvm::Functionclasshas functions for iter... |
How does the initialization happen in cases 2, 3, 4, 5 below. 1 will contain garbage.
```
char x[16];
char x[16] = {0};
char x[16] = {0, };
char x[16] = {1};
char x[16] = {1, };
```
|
If you use the brace initializer syntax with arrays, any additional elements not mentioned in the initializer list are initialized with zeros.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Single Linked List is Palindrome or not
Suppose i have a link list having a char item,i need to find if the characters in that link list is a palindrome or not. I know link list not at all a suitable structure for this, but then if we have... |
Knowing the size of the list you can tell what the middle is. Then as you go through you just cache all the chars up to the middle and make sure they appear in reverse order after the middle.
|
So basically I want to initialize a in_addr_t at with a specific address and parsing it from text makes no sense. It's tempting to do something like:
```
in_addr_t foo = network_byte_order(127 << 24 | 0 << 16 | 0 << 8 | 99 << 0};
```
For 127.0.0.99 and then wrapping it in a macro so it works conveniently for any add... |
There isn't an existing macro for this. Look at how this example of howINADDR_LOOPBACKis defined innetinet/in.h. It's just a hexadecimal constant, an even simpler approach than yours:
```
# define INADDR_LOOPBACK ((in_addr_t) 0x7f000001) /* Inet 127.0.0.1. */
```
So your approach is fine.
You should use the... |
I'm a newbie to C, I understand why ternary operators can be useful, less code than if/else blocks.
I have been given some C code to maintain, and one thing I've noticed is the previous programmer used ternary operators like this
```
myInt = (!myInt) ? MACRO1 : MACRO2;
```
Does this accomplish exactly the same thin... |
Yes, this code accomplishes exactly the same thing. It just depends on the logic used when writing the condition - so it can be chalked up to style (i.e. whichever is easier for you to think).
|
I have to create an array of char pointers each of them of size 10000000 using the best and optimized way to do this in C.
|
I think this will do (haven't checked for nulls though):
```
int i;
int num_arrays;
char **huge_char_array;
num_arrays = 10; //number of arrays you want.
huge_char_array = (char **)malloc(sizeof(char *) * num_arrays);
for(i = 0; i < num_arrays; i++)
{
huge_char_array[i] = (char *)malloc(sizeof(char) * 10000000);
... |
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
String literals are arrays, and as such can be indexed into:"abcdefgh"[0]is'a', for example.
|
I have an in-memory SQLite database which I want to serialize and send to another computer. Is this possible without writing the database out to disk and reading the file from there?
|
You could use the online backup API to transfer the in-memory database, to a file-based database created in shared memory (for Linux, in /dev/shm for instance) avoiding the disk operations. Then this pseudo-file is transferred to the remote host (still put in /dev/shm), and the online load API is used to transfer from... |
I am writing some code to get a hex dump of the stack in c. I keep getting a compile error on this following line when I compile it using gcc in ubuntu however it compiles fine under gcc in windows.
```
char buffer[10];
for (int i=0;i<20;i++)
printf("0x%lx => 0x%lx\n", &(buffer[i]), ((long *)buffer)[i]);
```
Thi... |
You should be using%pto print pointers, and remember to cast tovoid *.
```
printf("%p => ??\n", (void *)&(buffer[i]), ...);
```
I'm not sure what you're trying to do but if you're trying to interpret a portion ofbufferas a long and print it than you can use%ld.
|
how could I get information about the storage devices connected to the PC (floppy, HDD, usb disk drive, flash drive) from BIOS using 8086 assembly . I'm using VS 2008. Can you point me to a reference book or some info? I want to detect all working such devices and be able to read and write to them. Thanks.
|
Look these up:
Ralf Brown's Interrupt ListHelpPCTechHelpThe Undocumented PC: A Programmer's Guide to I/O, CPUs, and Fixed Memory AreasPCI System Architecture (and the like)
|
Is there a clean way of casting a struct into an uint64_t or any other int, given that struct in <= to the sizeof int?
The only thing I can think of is only an 'ok' solution - to use unions. However I have never been fond of them.
Let me add a code snippet to clarify:
```
typedef struct {
uint8_t field: 5;
uint8_t f... |
I've just hit the same problem, and I solved it with a union like this:
```
typedef union {
struct {
uint8_t field: 5;
uint8_t field2: 4;
/* and so on... */
} fields;
uint32_t bits;
} some_struct_t;
/* cast from uint32_t x */
some_struct_t mystruct = { .bits = x };
/* cast to uin... |
May be it is one of the simplest things for C programmers but I really can't get it.
```
unsigned char Value[4];
unsigned long ulVer = 00010001;
unsigned long uSize = sizeof(ulVer);
memcpy(Value, &ulVer, uSize);
memcpy(&ulVer, Value, uSize);
printf("%d",ulVer);
```
Why ulVer is 4097, not 10001 ?
|
00010001; is an octal constant because it starts with 0.
You need to write 10001 if that's what you want in decimal.
|
I have twochararrays -
```
char* c1[] = { 0x01, 0x02, 0x03, 0x04, ... 0x016 };
char* c2[] = { 0x01, 0x02, 0x03, 0x04, ... 0x016 };
```
I want achar(char* result) with appended bytes ofc1andc2
|
You need to allocate memory, and copy the data from the old array to the new one.
```
char* result;
result=(char*)malloc( sizeof(c1) + sizeof(c) );
memcpy(result, c, sizeof(c));
memcpy(result+sizeof(c), c1, sizeof(c1));
```
When you are finish your work with result free memory withfree(result);
|
I have two bytes and I am setting different bits in order to get different combinations.
E.g, byte 1 bit 7 and byte 2 bit 1,bit 2 makes a combination device ready.
Now, I have created mask
```
#define C1_device_ready (0x80 | 0x100 | 0x200)
```
Then I read the data and try to compare.
for 1 byte I can do (data[0] &... |
Ifdatais an array ofunsigned char, you could test
```
if ((data[0] & mask) == (mask & 0xFF) && (data[1] & mask) == ((mask >> 8) & 0xFF))
```
or combine the twodata[i]and check
```
if (((data[0] | (data[1] << 8)) & mask) == mask)
```
|
Look at the code in config.h:
```
#if (API_TYPE == 1)
#define URL_API @"https://dapi.xxx.com/1.1/"
#elif (API_TYPE == 2)
#define URL_API @"https://tapi.xxx.com/1.1/"
#elif (API_TYPE == 3)
#define URL_API @"https://api.xxx.com/1.1/"
#else
// I want stop pre-compile if in here.
// assert(0);
#endif
``... |
You can insert#error "Error message", which will stop preprocessing and a compilation won't even begin.
|
I have an in-memory SQLite database which I want to serialize and send to another computer. Is this possible without writing the database out to disk and reading the file from there?
|
You could use the online backup API to transfer the in-memory database, to a file-based database created in shared memory (for Linux, in /dev/shm for instance) avoiding the disk operations. Then this pseudo-file is transferred to the remote host (still put in /dev/shm), and the online load API is used to transfer from... |
I am writing some code to get a hex dump of the stack in c. I keep getting a compile error on this following line when I compile it using gcc in ubuntu however it compiles fine under gcc in windows.
```
char buffer[10];
for (int i=0;i<20;i++)
printf("0x%lx => 0x%lx\n", &(buffer[i]), ((long *)buffer)[i]);
```
Thi... |
You should be using%pto print pointers, and remember to cast tovoid *.
```
printf("%p => ??\n", (void *)&(buffer[i]), ...);
```
I'm not sure what you're trying to do but if you're trying to interpret a portion ofbufferas a long and print it than you can use%ld.
|
how could I get information about the storage devices connected to the PC (floppy, HDD, usb disk drive, flash drive) from BIOS using 8086 assembly . I'm using VS 2008. Can you point me to a reference book or some info? I want to detect all working such devices and be able to read and write to them. Thanks.
|
Look these up:
Ralf Brown's Interrupt ListHelpPCTechHelpThe Undocumented PC: A Programmer's Guide to I/O, CPUs, and Fixed Memory AreasPCI System Architecture (and the like)
|
Is there a clean way of casting a struct into an uint64_t or any other int, given that struct in <= to the sizeof int?
The only thing I can think of is only an 'ok' solution - to use unions. However I have never been fond of them.
Let me add a code snippet to clarify:
```
typedef struct {
uint8_t field: 5;
uint8_t f... |
I've just hit the same problem, and I solved it with a union like this:
```
typedef union {
struct {
uint8_t field: 5;
uint8_t field2: 4;
/* and so on... */
} fields;
uint32_t bits;
} some_struct_t;
/* cast from uint32_t x */
some_struct_t mystruct = { .bits = x };
/* cast to uin... |
May be it is one of the simplest things for C programmers but I really can't get it.
```
unsigned char Value[4];
unsigned long ulVer = 00010001;
unsigned long uSize = sizeof(ulVer);
memcpy(Value, &ulVer, uSize);
memcpy(&ulVer, Value, uSize);
printf("%d",ulVer);
```
Why ulVer is 4097, not 10001 ?
|
00010001; is an octal constant because it starts with 0.
You need to write 10001 if that's what you want in decimal.
|
I have twochararrays -
```
char* c1[] = { 0x01, 0x02, 0x03, 0x04, ... 0x016 };
char* c2[] = { 0x01, 0x02, 0x03, 0x04, ... 0x016 };
```
I want achar(char* result) with appended bytes ofc1andc2
|
You need to allocate memory, and copy the data from the old array to the new one.
```
char* result;
result=(char*)malloc( sizeof(c1) + sizeof(c) );
memcpy(result, c, sizeof(c));
memcpy(result+sizeof(c), c1, sizeof(c1));
```
When you are finish your work with result free memory withfree(result);
|
I have two bytes and I am setting different bits in order to get different combinations.
E.g, byte 1 bit 7 and byte 2 bit 1,bit 2 makes a combination device ready.
Now, I have created mask
```
#define C1_device_ready (0x80 | 0x100 | 0x200)
```
Then I read the data and try to compare.
for 1 byte I can do (data[0] &... |
Ifdatais an array ofunsigned char, you could test
```
if ((data[0] & mask) == (mask & 0xFF) && (data[1] & mask) == ((mask >> 8) & 0xFF))
```
or combine the twodata[i]and check
```
if (((data[0] | (data[1] << 8)) & mask) == mask)
```
|
Look at the code in config.h:
```
#if (API_TYPE == 1)
#define URL_API @"https://dapi.xxx.com/1.1/"
#elif (API_TYPE == 2)
#define URL_API @"https://tapi.xxx.com/1.1/"
#elif (API_TYPE == 3)
#define URL_API @"https://api.xxx.com/1.1/"
#else
// I want stop pre-compile if in here.
// assert(0);
#endif
``... |
You can insert#error "Error message", which will stop preprocessing and a compilation won't even begin.
|
I wondering whether is it possible to use bit operations to merge two bitfields according a bitmask?
For example I have two values, and a bitmask:
```
char mask = 0x29; // 0010 1001
char a = 0x9; // 0000 1001 original value
char b = 0xE8; // 1110 1000 modified value
```
And I want to set the bits in b to the ... |
Try something like:
```
b &= ~mask; /* Clear bits set in mask. */
b |= (mask & a); /* Add bits set both in a and in mask. */
```
Also, you might want to useunsignedtypes instead of the inconclusivechar.
|
Is there a plugin for eclipse IDE where I can run my SWIG module.
I'm trying to work in Windows, so can anyone tell me any available plugins for working with SWIG inside Eclipse?
Also I need to run C/C++ programs, so an IDE is the best way to work.
I don't want to use Microsoft Visual C++.
SWIG code:
```
%module t... |
I assume you want to add something like:
```
$ swig -java interface.i
```
to the eclipse build process. maybe take a look at:
Eclipse adding your own build command
I think eclipse should be fine for C/C++ dev
I use emacs instead for everything (C, Java, Android projects) but there's a bit of a learning curve invo... |
This is just a quick question. As I understand it, code from a static library is included directly, at compile time, into a .exe... so if I have some Library code running in a program, is it correct to say that the current directory as far as that code is concerned is the same as that of the .exe's, regardless of wher... |
It doesn't matter where the lib is, even if it is dynamically linked.
|
Please help with the segment below. When n is removed from the top of the stack and stack is empty, output should be '-1 popped'.(I'm getting 0 atm)
```
void pop(void) {
struct node *temp;
int n;
if (top == NULL) {
printf("%d popped\n", top);
return;
}
n = top->item;
temp = top... |
Logic fault, You are comparing against zero and want an output of -1 !!!
```
if (top == NULL) {
printf("%d popped\n", top);
return;
}
```
Should be
```
if (top == NULL) {
printf("%d popped\n",-1);
return;
}
```
|
I want to delete the cell which has "sth" in:
```
char* a[200];
```
how should I do it? I tried this but it does not work!
```
for(i=0;i<100;ti++)
{
if(strcmp(a[i],"sth")!=0)
temp[i]=a[i];
}
a=temp //not sure here
```
|
something like
```
j=0;
for(i=0;i<100;i++)
{
a[j]=a[i];
if(strcmp(a[i],"sth")) {
j++;
}else{
a[j]=0;
}
}
```
i didnt free the memory here, since i dont know where the strings came from. If the strings were allocated with malloc they should be freed (if not used elsewhere)
|
I want to create a binary file from a C file using ubuntu. I have done something like:
```
gcc -c ArrayError3.c -o ArrayError3.
```
This creates a file ArrayError3 on my Desktop. When I click on it, ubuntu tells me that there is no application installed for object files. I am very much a newbie to C and linux. Could... |
Just drop the-cso it won't stop after making the object file. The-coption tellsgccnot to run the linker. If omit it, gcc will make a full blown executable for you.
|
I want to do this but it doesn't work. Is it possible to do it or do I have to declare A as double pointer float**? Note that I need an universal function for various array dimensions so I can't change the function arguments.
```
void func(float** arr, int x, int y){
//access to arr[0][0] for e.g. causes SEGFAULT... |
To pass 2D array to function you need to know at least element count in 2nd dimension at compilation time.
```
void func(float arr[][2], int n)
```
If you don't know the size of array at compile time there isn't much you can do except:
```
void func(float *arr, int n, int m)
{
// getting arr[i][j] with arr[i*m ... |
Is there a non-boost way to create a function with variable arguments? I know theargument typesnumber of argumentsand they areusuallyless then 5,all of the same type.
I need to know if there is a way without supplying the argument count or ending the param list with null.
|
I know the argument types and they are usually less then 5.
If it is not going to be greater than5, then simple overloadsmaydo the work. Call the overload which accepts maximam number of arguments from all other overloads accepting less than 5 arguments, or define a worker (internal) function, call this from the over... |
Tested on regexpal.com this regex works fine, but when run in my program it doesn't work at all. The objective is to pull the video ID from the url (And throw an error if it's not a valid url)
```
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
int main(){
regex_t expression;
char * regexpression... |
AddREG_EXTENDEDflag toregcomp()function:
```
regcomp(&expression,regexpression,REG_EXTENDED);
```
|
I wanted to ask, if I have a pointer pointing at some struct, but then I free(struct) then if I dereference the pointer, will it be pointing to NULL? As in can I check, pointer != NULL or is this undefined?
Thanks!
|
Calling free() on the pointer does not change the pointer value. It will still point to the same memory that no longer belongs to your application. You should always assign NULL to a free'd pointer immediately after you free it to ensure that you don't use it again.
```
void *p = malloc(10); // p points to alloc... |
Why wouldn't this work? I've reviewed my code several times and just can't find what's wrong.
Thanks!
```
void generateData(float** inData, int x, int y){
inData[0][0]= 3000.0; // SEGFAULT
}
float** createMatrix(int x, int y){
float** array= malloc(sizeof(float*) * y);
for(int i=0; i<y; i++)
arr... |
You forgot this ever so important line;
```
return array;
```
increateMatrix. Look at your compiler warnings, or turn them on if you don't already have them on.
|
This bit of C code is giving segmentation error in gdb
```
if ((seq_entry_action=malloc((seq_subphases)*sizeof(int*)))==NULL){
printf("Cannot allocate memory for seq_entry_action\n");
}
```
where:
```
int **seq_entry_action=NULL;
unsigned int seq_subphases=0;
```
At the time of executing, and If I add a breakp... |
it was like that indeed... an earlier malloc of wrongly computed sizeof() was the reason this malloc failed.
|
I have a function that takes a pointer to a floating point array. Based on other conditions, I know that pointer is actually pointing to a 2x2 OR 3x3 matrix. (in fact the memory was initially allocated as such, e.g. float M[2][2] ) The important thing is I want to make this determination in the function body, not as... |
```
float (*somethingAsMatrix)[2] = (float (*)[2]) matrixReturnAsArray;
```
|
I am writing an LLVM pass that modifies the intermediate code. I want to check each terminating instruction of a basic block to see if it has a back edge. To make it more clear, in the following example, I want to see if to reach labelsland.lhs.trueorif.end, a back jump is required.
```
entry:
%pa = alloca %struct.... |
Not sure what you mean by back edge or back jump here, as LLVM intermediate code has no explicit layout in memory. You should think of basic blocks within each function has having no explicit order and no explicit assignment to memory addresses. This is handled by the backend when emitting assembly code.
|
Hi i have a simple code which prints three characters of a charater array as shown below
```
void main()
{
char str[]={65,66,67};
printf("%.3s",str);
}
```
this gives the outputABC,but i was wondering since this is not a string means it is not null terminated then how can%swork on it and give the correct res... |
Since you passed the length of the string, no 0 terminator is required by printf.
7.21.6.1 - 8If the precision is specified, no more than that many bytes are
written. If the precision is not specified or is greater than the size
of the array, the array shall contain a null character.
|
In some C-source file I've seen comments in the format:
```
/**
* @bla bla bla
* bla bla..
*/
```
Someone told me that if I comment my.c/.hfiles properly, then with a certain tool I can autogenerate man pages from those files automatically.
Does anybody know if this is possible? (How to do, which software shou... |
It looks like you are searching fordoxygen
|
I want to use a macro like this
```
#define Return(x) {call_my_function(); return (x);}
```
is there any way to use or declare a macro without parentheses, so I can use it like a real return call and not a function? For example:
```
BOOL my_func() {
code....
Return FALSE;
}
```
|
You could do something horrific as
```
#define Return for (call_my_function(); ;) return
```
Edit:Changed to Daniel's version for the nice smiley that makes. And Jim's idea of "overloading"returndirectly is valid and even more horrific ;)
|
dois a keyword in C and all I have seen is that it is only used withwhile. So my question is candobe used alone withoutwhile.
If yes how?
|
No. It cannot.
To be more precise, this is what theC standardhas to say:
6.8.5 Iteration statementsSyntaxiteration-statement:while ( expression ) statementdo statement while ( expression ) ;for ( expressionopt ; expressionopt ; expressionopt ) statementfor ( declaration expressionopt ; expressionopt ) statement
|
So in my main function I'm creating a 2D array:
```
int dataDim = 100;
float inData[2][dataDim];
```
I want to pass it to a function where I will be able to fill it up with data. How to pass it in a manner that I will be able to fill it up directly? Maybe
```
function(float** array)
```
and then accessingarray[0][... |
in C, multidimensional arrays' sizes must be known to pass as such, although some sizes may be omitted, if you like.
Exact
```
void function(float array[][100]);
void function(float (*array)[100]);
```
Syntactically Valid
Although the compiler may legally ignore the size2.
```
void function(float array[2][100]);... |
should we useperrorinside signal handler because they have a user space buffer likeprintfand other stdio functions?
|
perroris not listed in the table of async-signal-safe functions (e.g.,section 2.4.3 Signal Actions) so it is not safe to call from a signal handler that may be invoked in response to a signal interrupting a non-async-signal-safe function.
|
I am using this part of c code in carbide c/c++
```
char c1[]={0x01};
char c2[]={0x02};
char* c [] = {c1,c2};
```
when i check values of c[0],c[1].. i am seeing two values like this in debug mode
```
c[0] = \x01\x01 & (x) = *[0] = \x01
c[1] = \x02\x01\x01 & (x) = *[1] = \x02
```
and if i calculate length ... |
c1andc2do not have null terminators, andstrlen()requires a null terminator (along with many other C string handling functions, likeprintf("%s", c1)for example). A null terminator is only implicitly added when a string literal is used to initialise thechar[].
Change to either:
```
char c1[] = { 0x01, 0x00 };
char c2[... |
I am trying to make an s-function block in matlab simulink.Here is the mdlOutput function.it gives me an error when i define local variables inside
```
//////
static void mdlOutputs(SimStruct *S, int_T tid)
{
real_T *y = ssGetOutputPortRealSignal(S,0);// no error
real_T *x = ssGetContState... |
I got it .I have to define variables before the UNUSED_ARG(tid) command
|
I have this been givenCcode where the heading statement includes the following:
```
#define, EQ(a, b) ((a) == (b))
```
What does it mean?
|
The comma is an error that will prevent the code from compiling: I'll assume that it's a typo.
Given:
```
#define EQ(a, b) ((a) == (b))
```
This defines a macro for the equality operator==.
Using this macro later in the code, you can type, e.g.:
```
if (EQ(2+2, 4))
```
instead of:
```
if (2+2 == 4)
```
Not ver... |
I am trying to write some soft on 8051 uC in C. Problem is that the longest integer is equal 16 bits. Is it possible to create my own 32 bit unsigned integer variable? Of course it should support all operations like +, -, << etc.
If it is not possible what is alternative? For me the only way which comes to my mind is... |
If your compiler/libc implementation conforms to C99, you can use the
```
uint32_t
```
type to represent 32-bit unsigned integers. If it doesn't, you can still give
```
unsigned long
```
a try (print its sizeof to see how big it is).
|
What is the correct way to free a float ** like below.
e.g.float ** someArray
```
for(int i = 0; i < numberOfDimensions; i++)
{
somearray[i] = (float *) malloc(numberOfDimensions * sizeof(float));
}
```
|
If you have malloc'ed another round of memory and assigned it to each float pointer in the original array, then you should free them as well beforehand:
```
int i;
for (i = 0; i < numberOfDimensions; i++)
free(someArray[i]);
// and free the container array only now
free(someArray);
```
P. s.:don't cast the ret... |
Hello can you give me an example of the usage of this method
```
+(NSString *)description
```
Do I use description with an instance of a NSObject (any kind of object) or NSString?
or do I use without an instance, directly using NSObject (any kind of object) or NSString?
|
The description of the instance gives you information about the specific instance you have created.
- (NSString *)description;
```
NSString *string = [NSString alloc] initwithString:@"aString"]];
[string description];
```
Gives you information about this instance (location in memory etc)
On the other side:
+ (NSS... |
What is the best way to put a DLL written in C into a VB.NET (Express Edition 2010) project? I have the declarations for the external functions locating absolute paths right now like so:
C:\Users\Kyle\Documents\Pelles C Projects\ROBOLIB\ROBOLIB.dll
Because Visual Basic creates so many different directories the progr... |
You can add the DLL to your project (either per Drag'n'Drop or right mouse click -> Add -> Existing Element). If you right click the file and choose properties, you can define "Copy to output directory".
Of course, you should ensure that the installer (in case you create one) copies the files.
|
I am using an open source library and it builds to a file like libshared.la. Can i statically link with this file using normal gcc commands? I'm more familiar with the dynamic linking of .so file and the static linking of .a files. Not sure about .la though.
thanks!
|
That is a libtool file. You can use it usinglibtool:
```
$ libtool --mode=link gcc -g -O -o test test.o \
/usr/local/lib/libhello.la
```
More aboutlibtool:
http://www.gnu.org/software/libtool/manual/html_node/Using-libtool.html
|
I'm developing C module for php under linux and I'm trying to find a way that could help me profile my code by maximum memory spike (usage).
Using valgrind I can get total memory allocation within the code. But as it is with allocated memory it comes and goes ;). What I need to get is the highest memory usage that ap... |
Take a look at Massif:http://valgrind.org/docs/manual/ms-manual.html
|
i have a device which is stethoscope digital machine, so i attach that machine with PC and get that machine data using C++ code(Algorithm), so how can i start? Can any one give me any type of tutorial or any related example link which will be help me to accomplish that task ?
i haven't much knowledge of this type of ... |
If you use Windows
```
HANDLE m_hParallelComm = CreateFile(portName,GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0,NULL);
if(m_hParallelComm == INVALID_HANDLE_VALUE)
return false;
ReadFile( m_hParallelComm,data, dwSize, &dwNumberOfBytesToRead, NULL);
CloseHandle(m_hParallelComm);
```
For read file f... |
I want to pass a value by reference in C. Are this two functions the same? Which is the difference? Is the same in C++?
```
void foo1(int * val1, int * val2)
void foo2(int &val1, int &val2)
```
Thanks,
|
References are C++ only (not C).
The implementations of the methods will be different, since dereferencing a reference is different from dereferencing a pointer in C++.
e.g.
```
ref.method();
```
vs.
```
ptr->method();
```
In both cases you're calling on the original object passed to the method, not a copy.
|
As you know that MFC's CFontDialog does only support int in Font size.
And if you checked MS Office you'll find that the Font Dialog supports Float font size normally.
So what is the appropriate way to implement this feature
Is there any implemented font dialog I may use in MFC?Is there any external 3rd parity libra... |
MS Office doesnt use CFont Dialog. You cant use CFont dialog to support decimal numbers. Checkthisdiscussion about the same topic.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
You don't need to know C or C++ to learn C#. If you already know them, some of the C# syntax will be familiar, but learning C/C++ just to learn C# is definitely a waste of your time.
That said, C and C++ aren't bad languages to have a grip on, but if you're going to learn them, learn them for their own sake and not j... |
Can someone please tell me what do these lines of code do
```
*(a++) = (int)((value >> 16) & 0xFF) ;
*(a++) = (int)((value >> 8) & 0xFF) ;
*(a++) = (int)((value & 0xFF)) ;
```
I understand that it checks the value, if it is much greater than 16 it converts it to type int and if it is much smaller than 8 does th... |
I understand that it checks the value
It doesn't check anything, it's not like the<<symbol in math which means "much smaller". To break down this line:
```
*(a++) = (int)((value >> 16) & 0xFF);
```
(>>)shiftsvalue16 times to the right(&)andsthe result with0xFF, thereby discarding everything to the leftStores the r... |
I have seen this alternative to usingCGRectMake()in order to initialise aCGRectvariable:
CGRect frame = (CGRect){0,0,10,10};
My question is, how doesCGRect frame = (CGRect){0,0,10,10};work? What's going on behind the scenes? It looks like a c-style array is being initialised ({x,y,w,h}) which is then being cast as a... |
It's a so-called compound literal. You can read more about them in this article by Mike Ash:Friday Q&A 2011-02-18: Compound Literals.
|
So, I can initialize a C array like this:
```
CGFloat colors[8]= {1,0.5,0.5, 1,
0.5,0.2,0.2, 1};
```
What if I want to definecolors[8]but assign the 8 values conditionally. Is this possible? If it is, I cannot find the right syntax. Something like this:
```
CGFloat colors[8];
if (red){
colors= {1,0.5,0.5, 1,
... |
This will not work, as this way of assignment is only allowed at array initialization. what you can do is:
```
CGFloat colors[8];
if (red){
CGFloat temp[] = {1,0.5,0.5, 1, 0.5,0.2,0.2, 1};
memcpy(colors, temp, sizeof(colors));
}
else
{
// ...
}
```
|
I'm writing a C program under Android/Linux that runs a system command. The command outputs some text to stdout, and I'm trying to capture the output into a string or character array.
For example:
```
system("ls");
```
would list the contents of the current directory to stdout, and I would like to be able to captur... |
You want to usepopen. It returns a stream, likefopen. However, you need to close the stream withpclose. This is becausepclosetakes care of cleaning up the resources associated with launching the child process.
```
FILE *ls = popen("ls", "r");
char buf[256];
while (fgets(buf, sizeof(buf), ls) != 0) {
/*...*/
}
pcl... |
I have noticed two methods to return to the beginning of a file
```
FILE *fp = fopen("test.bin", "r")
fseek(fp, 0, SEEK_END);
rewind(fp);
```
and
```
FILE *fp = fopen("test.bin", "r")
fseek(fp, 0, SEEK_END);
fseek(fp, 0, SEEK_SET);
```
What would be difference if any between these methods?
|
They are basically two different ways to accomplish the same thing: set the pointer to the beginning of the file. The only difference is thatrewindalso clears the error indicator.
If given the choice, you should usefseek. This is becauserewinddoesn't return an integer indicating whether the operation has succeeded.
|
```
#include <stdio.h>
#include <conio.h>
typedef arrChoice[10] /*is this a global variable?*/
int main() {};
getch();
return 0;
}
```
its not done yet, but this is what i meant.
|
typedef is not a global variable, it's simply an alias for another type. I usually use them for function pointers when I'm passing those around because writing them out every time is annoying.
typedef int (*function)(int, int);
I also use them to define a structure, union, or enumeration as a type
```
typedef struc... |
How do I printf integers? When I use:
```
int n = GetInt();
printf("%n \n", n);
```
I get the error that there was an unused variable and I can't compile it.
|
A signed integer uses%d(or%i).
See alsoman 3 printf(on Unix-like systems) for the whole list of modifiers.
|
I'm seeing code allocating memory for float usingsizeof(int).I'm wondering whethersizeof(float)always equal tosizeof(int)on all architectures?
```
float *pointer2Float = (float *) USER_DEFINED_MALLOC (...,..., sizeof(int))
```
Note: thisUSER_DEFINED_MALLOCisa wrapper for conventional malloc, I think.
Thanks
Regard... |
No, there are implementations (mainly embedded systems) with 16-bitintand 32-bitfloat.
And of course, the sizes are allowed to be quite different per the standard.
|
Ive got the following
```
typedef struct{
GLfloat x;
GLfloat y;
GLfloat z;
}Vertex3D;
```
and I want to use a for loop. is it possible to specify which primitive you want from a struct based on its index. e.g if I wanted using the number 0 for x 1 for y and 2 for z like an array?
Thanks for all your responses.... |
Not legally. The structure's elements might be aligned in memory, but I highly recommend not doing it this way, it could cause many headaches later, especially if you find your struct needs additional members later.
Try instead:
```
typedef struct
{
GLfloat c[3];
}Vertex3D;
```
and
```
#define VERTEX_X 0
#def... |
Let us say I have a double for loop.
```
/*Just a double for loop
*/
for(int i = 0; i<IMAX; i++){
for(int j = 0; j<JMAX; j++){
count++;
recover_loop_indices(count,IMAX,JMAX); /*this is not real world code.Just to illustrate what I mean*/
}
}
```
My question is precisely, givencount,IMAXandJMAX, is it... |
Yes, based on count:
```
i = floor(count / JMAX);
j = count % JMAX;
```
You don't need IMAX at all. In fact, this is often how one can reconstruct an image from a serial stream of pixels, given only the width of the stream.
Edit:
I am assuming you want to recover the values of i and jbeforethe count++. To recover ... |
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question
Today OpenGL 4.3 and OpenGL ES 3.0 specificationshave been unveiledand for texture compre... |
There is a codec for ASTC at thiswebsite(malideveloper.com).
Source code seem to be included as well.
Hope that helps.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:GCC left shift overflow
Consider the following minimal program.
```
#include <stdint.h>
#include <stdio.h>
int main()
{
uint32_t v = 1024;
v &= (((uint32_t)1 << 32) - 1);
printf("v = %u\n", v);
return 0;
}
```
This print... |
Shifting a 32-bit value by 32 bits is undefined behaviour in C. Don't do it.
|
This is my code:
```
typedef struct{
char name[64];
} Cat;
Cat createCat(char name[64]) {
Cat newCat;
int i;
for(i = 0; i < 64; i += 1) {
newCat.name[i] = name[i];
}
return newCat;
}
Cat exampleCat = createCat("Bob");
```
It compiles with the following error:
initializer element is not constant... |
```
Cat exampleCat = createCat("Bob");
```
You can't do a method call here. InitializeexampleCatsomewhere else.
This is explained in the spec, section 6.7.8/4:
All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.
|
This is my code:
```
typedef struct{
char name[64];
} Cat;
Cat createCat(char name[64]) {
Cat newCat;
newCat.name = name;
return newCat;
}
```
It compiles with the following error message:
incompatible types when assigning to type 'char[64]' from type 'char
*'
What am I doing wrong here?
|
Array decay to pointers when passed to functions. So:
```
Cat createCat(char name[64]) {
```
is the same as:
```
Cat createCat(char* name) {
```
and the line:
```
newCat.name = name;
```
is attempting to assign achar*to achar[], as the error states. AsMysticalhas already commented, you need to usememcpy()orstrcp... |
This question already has answers here:How can I "add existing frameworks" in Xcode 4?(10 answers)Closed9 years ago.
I have a static C library compiled with arm7-gcc and i want to use it in my iOS project. i added it to project but i can't figure out how to use it.
|
After adding the library to the project and including the header in your application codeб there is a second step. That step is letting the Xcode project know where the header file/files is/are. You do this by editing the "User Header Search Paths" build setting with the path to the header files.
|
I am using an open source library and it builds to a file like libshared.la. Can i statically link with this file using normal gcc commands? I'm more familiar with the dynamic linking of .so file and the static linking of .a files. Not sure about .la though.
thanks!
|
That is a libtool file. You can use it usinglibtool:
```
$ libtool --mode=link gcc -g -O -o test test.o \
/usr/local/lib/libhello.la
```
More aboutlibtool:
http://www.gnu.org/software/libtool/manual/html_node/Using-libtool.html
|
I'm developing C module for php under linux and I'm trying to find a way that could help me profile my code by maximum memory spike (usage).
Using valgrind I can get total memory allocation within the code. But as it is with allocated memory it comes and goes ;). What I need to get is the highest memory usage that ap... |
Take a look at Massif:http://valgrind.org/docs/manual/ms-manual.html
|
i have a device which is stethoscope digital machine, so i attach that machine with PC and get that machine data using C++ code(Algorithm), so how can i start? Can any one give me any type of tutorial or any related example link which will be help me to accomplish that task ?
i haven't much knowledge of this type of ... |
If you use Windows
```
HANDLE m_hParallelComm = CreateFile(portName,GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0,NULL);
if(m_hParallelComm == INVALID_HANDLE_VALUE)
return false;
ReadFile( m_hParallelComm,data, dwSize, &dwNumberOfBytesToRead, NULL);
CloseHandle(m_hParallelComm);
```
For read file f... |
I want to pass a value by reference in C. Are this two functions the same? Which is the difference? Is the same in C++?
```
void foo1(int * val1, int * val2)
void foo2(int &val1, int &val2)
```
Thanks,
|
References are C++ only (not C).
The implementations of the methods will be different, since dereferencing a reference is different from dereferencing a pointer in C++.
e.g.
```
ref.method();
```
vs.
```
ptr->method();
```
In both cases you're calling on the original object passed to the method, not a copy.
|
As you know that MFC's CFontDialog does only support int in Font size.
And if you checked MS Office you'll find that the Font Dialog supports Float font size normally.
So what is the appropriate way to implement this feature
Is there any implemented font dialog I may use in MFC?Is there any external 3rd parity libra... |
MS Office doesnt use CFont Dialog. You cant use CFont dialog to support decimal numbers. Checkthisdiscussion about the same topic.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
You don't need to know C or C++ to learn C#. If you already know them, some of the C# syntax will be familiar, but learning C/C++ just to learn C# is definitely a waste of your time.
That said, C and C++ aren't bad languages to have a grip on, but if you're going to learn them, learn them for their own sake and not j... |
Can someone please tell me what do these lines of code do
```
*(a++) = (int)((value >> 16) & 0xFF) ;
*(a++) = (int)((value >> 8) & 0xFF) ;
*(a++) = (int)((value & 0xFF)) ;
```
I understand that it checks the value, if it is much greater than 16 it converts it to type int and if it is much smaller than 8 does th... |
I understand that it checks the value
It doesn't check anything, it's not like the<<symbol in math which means "much smaller". To break down this line:
```
*(a++) = (int)((value >> 16) & 0xFF);
```
(>>)shiftsvalue16 times to the right(&)andsthe result with0xFF, thereby discarding everything to the leftStores the r... |
I have seen this alternative to usingCGRectMake()in order to initialise aCGRectvariable:
CGRect frame = (CGRect){0,0,10,10};
My question is, how doesCGRect frame = (CGRect){0,0,10,10};work? What's going on behind the scenes? It looks like a c-style array is being initialised ({x,y,w,h}) which is then being cast as a... |
It's a so-called compound literal. You can read more about them in this article by Mike Ash:Friday Q&A 2011-02-18: Compound Literals.
|
So, I can initialize a C array like this:
```
CGFloat colors[8]= {1,0.5,0.5, 1,
0.5,0.2,0.2, 1};
```
What if I want to definecolors[8]but assign the 8 values conditionally. Is this possible? If it is, I cannot find the right syntax. Something like this:
```
CGFloat colors[8];
if (red){
colors= {1,0.5,0.5, 1,
... |
This will not work, as this way of assignment is only allowed at array initialization. what you can do is:
```
CGFloat colors[8];
if (red){
CGFloat temp[] = {1,0.5,0.5, 1, 0.5,0.2,0.2, 1};
memcpy(colors, temp, sizeof(colors));
}
else
{
// ...
}
```
|
I'm writing a C program under Android/Linux that runs a system command. The command outputs some text to stdout, and I'm trying to capture the output into a string or character array.
For example:
```
system("ls");
```
would list the contents of the current directory to stdout, and I would like to be able to captur... |
You want to usepopen. It returns a stream, likefopen. However, you need to close the stream withpclose. This is becausepclosetakes care of cleaning up the resources associated with launching the child process.
```
FILE *ls = popen("ls", "r");
char buf[256];
while (fgets(buf, sizeof(buf), ls) != 0) {
/*...*/
}
pcl... |
I have noticed two methods to return to the beginning of a file
```
FILE *fp = fopen("test.bin", "r")
fseek(fp, 0, SEEK_END);
rewind(fp);
```
and
```
FILE *fp = fopen("test.bin", "r")
fseek(fp, 0, SEEK_END);
fseek(fp, 0, SEEK_SET);
```
What would be difference if any between these methods?
|
They are basically two different ways to accomplish the same thing: set the pointer to the beginning of the file. The only difference is thatrewindalso clears the error indicator.
If given the choice, you should usefseek. This is becauserewinddoesn't return an integer indicating whether the operation has succeeded.
|
```
#include <stdio.h>
#include <conio.h>
typedef arrChoice[10] /*is this a global variable?*/
int main() {};
getch();
return 0;
}
```
its not done yet, but this is what i meant.
|
typedef is not a global variable, it's simply an alias for another type. I usually use them for function pointers when I'm passing those around because writing them out every time is annoying.
typedef int (*function)(int, int);
I also use them to define a structure, union, or enumeration as a type
```
typedef struc... |
For example, in a linux-machine there are so many process.
Each one is able to use a syscall, but usually few are used.
Well, there is a tool or a manner to show when a syscall is used and which is the process associated?
|
You can use various tools, likestrace,ltraceand many other, although I'm not sure you want to trace all processes at the same time.
Normally you'd attach to one process of interest and follow its system calls.
|
It is possible to convertinteger to stringinCwithoutsprintf?
|
There's a nonstandard function:
```
char *string = itoa(numberToConvert, 10); // assuming you want a base-10 representation
```
Edit: it seems you want some algorithm to do this. Here's how in base-10:
```
#include <stdio.h>
#define STRINGIFY(x) #x
#define INTMIN_STR STRINGIFY(INT_MIN)
int main() {
int anInte... |
I have decided to use theGTKlibrary and I have been messing around with it.
My problem does not lie within C or GTK itself, it all aboutEclipse. Even though my applications compile and run with no errors, but Eclipse is constantly telling me that there are problems such as:
GTK_DIALOG_MODAL, GTK_MESSAGE_INFO, GTK_BU... |
I guess Eclipse cannot find GTK's header files. You can tell it where to look for them by adding one or more include directories to the project properties:
```
Project → Properties → C/C++ General → Paths and Symbols → Includes
```
This works for Eclipse Indigo and Juno, at least.
|
```
#define B 100+B
main()
{
int i= B;
}
```
I know it's wrong, but just out of curiosity, when I compile it I get this weird error:
"B was not declared in this scope".
Why is it so? If this error was because the compiler removes the macro after its substitution then how does the following code worked fine, whe... |
Here's the output of the preprocessor:
```
gcc -E x.c
# 1 "x.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "x.c"
main()
{
int i= 100+B;
}
```
As you can see, it did the substituion. Now comes the compile step which fails because there's noBdeclared.
The other code is fine, here's the output:
```
main()
{
i... |
I would like to declare an array in kernel module and to access it within a userspace app. how can I do it?
How do I memory map it for using via userspace so it can be used by a user?
|
You will most likely need to implement a character device. Then in your instance ofstruct file_operationsimplement themmap function.
|
When definingt_ioctllike this, I get no warning:
```
long t_ioctl(struct file *filep, unsigned int cmd, unsigned long input){
```
When definingt_ioctllike this:
```
static long t_ioctl(struct file *filep, unsigned int cmd, unsigned long input){
```
I get the warning:
```
warning: 't_ioctl' defined but not used
``... |
Most likely you have a definition like this in the same file:
```
static struct file_operations fileops = {
.read = t_read,
.write = t_write,
/* etc. ... */
};
```
And you're missing
```
.compat_ioctl = t_ioctl, /* or .ioctl/.unlocked_ioctl, depending on version etc. */
```
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question
I created a library that I want to use in another part of my program, but I don't want to... |
http://crasseux.com/books/ctutorial/Building-a-library.html
Just googled "building c libraries".
|
I'm trying to build an implementation of<ctype.h>with a lookup table and bits masks (this method). But I've seen in the C11 standard I need some informations about the current locale :
7.4 Character handling<ctype.h>[...]2 The behavior of these functions is affected by the current locale.
So, do I need a<locale.h>im... |
A fast simple way to do this for 8-bit characters is to have one bitmask for each defined value of LC_CTYPE. For wide character types you can reduce the size of the tables by some method like a 2-stage lookup. To be efficient, this will need to be designed for each character encoding. Having a dynamic lookup on LC_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.