question
stringlengths
25
894
answer
stringlengths
4
863
My question is regarding the CPP backend, does it serve the same purposes as the C backend? The C backend was one of my favorite LLVM features, and I'm very upset it was removed. Whats the real differences? I' most appreciative of any help. Reference:The LLVM 3.1 Release Notes"The C backend has been removed ..."
The CPP backend creates LLVM API calls to create an AST that represent the equivalent of the LLVM assembly. You can try the CPP backend athttp://llvm.org/demo/by selecting the "LLVM C++ API code"Target. The C backend creates C code that execute the semantics of the LLVM assembly. They are fundamentally different.
This question already has answers here:Closed11 years ago. Possible Duplicate:Difference between format specifiers %i and %d in printf I just checked the reference, it says both of them indicate signed integer. I thought there must be some difference
There is no difference. From the C99 standard document, section 7.19.6.1: d, iThe int argument is converted to signed decimal in the style [−]dddd. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it is expanded with leading zeros. ...
I have the followingWndProc: ``` LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM w, LPARAM l) { switch (message) { case WM_DESTROY: PostQuitMessage(0); return 0; case WM_MOUSEMOVE: return 0; default: return DefWindowProc(hWnd, message, w, l); } } ``...
TheWM_MOUSEMOVEmessage is just the window manager telling youthat the mouse has movedand if your application wants to do something with that information it can do so. It isnota mechanism where you can intercept mouse movements and cancel them at will.
I try to use CFLocaleCopyCurrent under OSX 10.5.8 but I get weird error: ``` #include <CoreFoundation/CoreFoundation.h> int main(int argc, char **argv){ setlocale(LC_ALL, ""); CFLocaleRef loc = CFLocaleCopyCurrent(); return 0; } Undefined symbols: "_CFLocaleCopyCurrent", referenced from: _main in ccn51X...
try/usr/bin/gcc -framework Foundation test.c
im working on converting C code to c++ , in one section of the code i have something like function array in C that looks like: this is how C looks like : ``` void func1(bool a) { .. } void func2(bool a) { .. } void func3(bool a) { .. } struct func { void (*f)(incoming *); int arg_length; }; typedef stru...
You could define a class, and insert a '[]' operator to get pointers to functions, in your case.
I have a simple echo server written in C, I would like to stop the server if it received thequitword ``` int n; char buffer[256]; while(strcmp(buffer,"quit") != 0) { n = read(sock,buffer,255); if (n < 0) { perror("ERROR reading from socket"); exit(1); } ...
It's likely the buffer isn't 0-terminated so using "string" comparison functions is wrong. You should trystrncmpormemcmpinstead. Also, in thewhilecondition, you're testing before actually reading intobuffer.
I am trying to write raw binary bits at a time to a file. I have found an example that uses unsigned char ->https://stackoverflow.com/a/2666669/1541965 But the minimum size is 8 bit (because of the unsigned char 0 to 255). Is there a way to write bits to a file in a more direct way? Thanks.
You haven't said what operating system you're using. But generally the smallest unit you get to write to a file is one 8-bit byte. If you want to write individual bits, you'll need to assemble them into bytes in your own code. I don't know of any OS whose file IO facilities allow writing of individual bits.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
If GPL is ok, there'sSECCURE I haven't used it personally but did stumble upon it couple of months ago when evaluating my options for a pet project.
Consider the below program: ``` #pragma startup foo1 #pragma exit foo2 void foo1() { printf("Called before main\n"); } void foo2() { printf("Called after main\n"); } int main() { printf("main called\n"); return 0; } ``` I am getting the output as:http://ideone.com/ooMFI ``` main called ``` Why t...
Because none of these pragmas are recognized byGCC. In general, stay clear of pragmas if you're trying to write portable code, because they differ per compiler and even per platform within the same compiler family.
Well, I would like to initiate my 2D array by a void function. But I obtain a Segmentation Fault... That's my code : ``` #include <stdio.h> #include <stdlib.h> #include <string.h> void groupeetchoixgen(int*** choixGEN); void main(int args, char **argv) { int** choixGEN; int i,j...
On this line: ``` choixGEN=(int**) malloc (sizeof(int*)*2); ``` you are only allocating space for 2int*s, but you access the 3rd element in theforloop.
I'm calling a c program using crontab. If I call the program directly, everything is fine. If the program is called by cron, my .log files can't be opened. the program is in a directory /stuff1/stuff2/stuff3/program all pathnames in the program are absolute just to make sure, I chmod 777'd everything in stuff3 ED...
This'll probably help you get to the bottom of it, since you know at least some C:http://stromberg.dnsalias.org/~strombrg/debugging-with-syscall-tracers.html
``` #include <stdio.h> int main() { int *p = (int*) 60; --- Line 1 int *q = (int*) 40; --- Line 2 printf("%d", p-q); //Output is 5 return 0; } ``` Could anybody please explain to me the output of this program?
It means the (implementation-defined) action of assigning an integral value to a pointer happens. This often means thatppoints to the memory address at60andqto the address at40. These memory addresses could be in virtual memory, hardware memory, and many implementations have different conversion routines for these. S...
I want to share memory between two processes. One way I know is tommapa shared file. However, I don't want to use a shared file, I want an anonymous mapping in the memory. How can I do that.
shm_openis your friend. You can unmap the shared region by usingshm_unlink.
I am getting the following warning: ``` expected ‘float **’ but argument is of type ‘float (*)[6]’ ``` Here is my code: ``` //state and error are output parameters void func(float* state[6], float* err[6][6]); int main() { float state[6]; float err[6][6]; func(&state, &err); return 0; } ``` I want state...
Change your code to: ``` void func(float state[], float err[][6]); int main() { float state[6]; float err[6][6]; func(state, err); return 0; } ``` To understand why, you need to know thatfloat* err[6][6]is a 6x6 array of pointers to float, not a pointer to a 6x6 array of floats.
``` #include<stdio.h> int main(){ char a[3]; char *b=NULL; a[0]=0; a[1]=1; a[2]=2; b = a; printf("%c",b); b++; printf("%c",b); b++; printf("%c",b); return 0; } ``` I tried to print the values 0,1,2 by incrementing the pointer by 1. please help
b is a pointer in itself, you have to dereference it to get the actual values: ``` printf("%d", *b); b++; printf("%d", *b); b++; ``` etc.
Consider this code: ``` FILE * fp = fopen( filename, "r" ); int ret = fscanf(fp, "%d, %d, %d, %d, %d\n", &a, &b, &c, &d, &e); if (ret != 5) { // error and exit } long file_pos = ftell(fp); printf("file position: %ld\n", file_pos); ``` The line of file being read is: ``` 6, 5, 3, 2, 6\r\n ``` That is, the file ...
fscanf may be buffering the file - ie it reads a certain sized block and then parses it to decode the contents.
I have a C++ function defined in a .h file as follows and implemented in a .cpp file: ``` extern "C" void func(bool first, float min, float* state[6], float* err[6][6]) { //uses vectors and classes and other C++ constructs } ``` How can I call func in a C file? How do I set up my file architecture / makefile to ...
You call the function from C in the normal way. However, you need to wrap theextern "C"in an preprocessor macro to prevent the C compiler from seeing it: ``` #ifndef __cplusplus extern "C" #endif void func(bool first, float min, float* state[6], float* err[6][6]); ``` Assuming you're working with GCC, then compile ...
So I'm building a bunch of modules with g++. I hit some of the source files with -c to produce the .o object files. I then at some points combine object files using the -r flag for ld to produce even more .o files. Somewhere in the process, a function is not getting included. So what I'm trying to do is find a quick t...
On Linux you'd useobjdump -tfor that. Look for*UND*in its output.
Anybody knows where is a list of the AVERROR meanings? Something like ``` -1: reason A -2: reason B ``` and so forth?
You can useav_strerror()to get a string representation of the error code. If you simply want to look it up, you can refer to the docs forlibavutil/error.candlibavutil/error.h.
i know its old problem , but what will be the easy solution to keep the old logic of c app (legacy) that now converted to c++ ? in c its working : ``` void *p; void *response = malloc(60 * 81); p = response ; p+=4; ``` in g++ gives : ISO C++ forbids incrementing a pointer of type ‘void*’ update:if i change it to c...
The simplest would be to cast thevoid *tochar *. Since ISO C also forbidsvoid*arithmetic, gcc treats it as achar*as an extension. See this for more details:http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/Pointer-Arith.html#Pointer-Arith
``` int x=0; int*a=&x; void foo(int * a) { static x=0; x++; printf("x's value %d ", x); *a+=x; a=&x; *a=x+10; } int main(void) { foo(a); printf("a's value %d\n ", *a); foo(a); printf("a's value %d ", *a); return 1; } ``` I'm trying to analyze the above. First iteration ...
``` a=&x; *a=x+10; ``` The above code adds 10 tox, because you setato be a pointer tox, and then set the value pointed to byatox+10.
``` #define L 1 #define M L+1 int main(void){ int N=L*M*2; char s [N]={'1','2'}; printf("%d", sizeof(s)); return 1; } ``` Why does the above code cannot be compiled? The compiler of Eclipse says two things: Variable-sized object may not be initialized:Is because the definition of N with M and L...
because I can't initialize an array with type arr[x] where x is variable? Indeed, pre-C99, the array size must be aconstant expression. In C99, this has been relaxed withvariable-length arrays. (This is is nothing to do with macros.) excess elements in array initializer- What does it mean? Fix the first problem, ...
I have the following issues when trying to compile thelibtheoraplayerdemo (av_player demo). If someone can help me out with some errors from libtheoraplayer (), I would be really grateful.
If you are familiar with linux then check the vlc source code it is free but it is C code. it may be help to you. Thanks.
The problem is that the same code that compiles well on Windows, is unable to compile onUbuntu. Every time I get this error: cc1: warnings being treated as errors Now, it's big code base and I don't like fix all the warnings. Is there a way I can compile successfully in spite of the warnings?
Sure, find where-Werroris set and remove that flag. Then warnings will be only warnings.
Below are two files which I will use as my example. If I define an array of structures in file1.h and have file2.c include file1.h I would get a multiple definition error. Why is that? If I just have struct thread tasks[32] I don't get this error. file1.h ``` ... ... struct thread tasks[32] = {0}; // thread is struc...
Most likely you are including the header file in more than one source file. The#includedirective literally includes the contents of the header file into the source file, which means that all code in the header file will also be in the source file. This means that if two or more source file includes the same header fil...
I want tofprintf()3 strings to a file, all on the same line. The first two cannot contain spaces while the 3rd may. I.E.word word rest of line Can some one tell me how tofscanf()that into 3 variables? I don't mind putting some delimiters if it makes it easier. E.G.[word] [word] [rest of line]
You can do it without delimiters, too: ``` char s1[32], s2[32], s3[256]; if(sscanf(line, "%31s %31s %255[^\n]", S1, S2, S3) == 3) /* ... */ ``` This should work, as long as the inputlineactually does end with a newline. Of course, you should adjust the string sizes to fit. Also you can get trickery with the prepr...
I need to compress data for logging by appending short strings to the log file using C++/C. I first tired gzip(zlib), but this makes a symbol table for each short string and actually makes the data longer rather than compressing. I believe the thing I'm looking for is a static Huffman table. Anyway, I was wondering if...
You should look at theexamples/gzlog.[ch] source filesin thezlibdistribution. That code was written for precisely this purpose. It appends short strings to a growing compressed gzip file.
The following code is working fine in C but when I try to write it in c++ then the program does not work.Please explain. C code : ``` #include<stdio.h> #include<stdlib.h> int main() { int a = 33,b = 7; printf("%d\n",a&b); return 0; } ``` C++ code: ``` #include<iostream> using namespace std; int main...
Watch your operator precedence: ``` cout << (33 & 7) << endl; ``` &has lower precedence than<<. So you need to use(). For the full list of operator precedence in C and C++: http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence
I have built a working C library, that uses constants, in header files defined as ``` typedef struct Y { union { struct bit_field bits; uint8_t raw[4]; } X; } CardInfo; static const CardInfo Y_CONSTANT = { .raw = {0, 0, 0, 0 } }; ``` I know that the.rawinitializer is C only syntax. How do I define cons...
I had the same problem. For C89 the following is true: With C89-style initializers, structure members must be initialized in the order declared, and only the first member of a union can be initialized I found this explanation at:Initialization of structures and unions
I am implementing a client which uses two threads: one that receives data from a server and prints it to stdout, the other one uses fgets to ask a string to the user and sends a message to the server.The threads are always in execution, but there is a problem: I don't know how to stop the thread that takes input from ...
A signal can interrupt an I/O operation. Assuming you didn't use the SA_RESTART flag for the sigaction signal handler, the read will return with an errno of EINTR.
Let's assume I define BAR in foo.h. But foo.h might not exist. How do I include it, without the compiler complaining at me? ``` #include "foo.h" #ifndef BAR #define BAR 1 #endif int main() { return BAR; } ``` Therefore, if BAR was defined as 2 in foo.h, then the program would return 2 if foo.h exists and 1 i...
In general, you'll need to do something external to do this - e.g. by doing something like playing around with the search path (as suggested in the comments) and providing an emptyfoo.has a fallback, or wrapping the#includeinside a#ifdef HAS_FOO_H...#endifand settingHAS_FOO_Hby a compiler switch (-DHAS_FOO_Hfor gcc/cl...
I am doing some calculations with points and the vectors between the points and it is no surprise to me that I get nan for when the points are very close together. What I am trying to do now is rid all the nan values in the array that I have stored in an array along with the good data. I am hoping to just use a bit of...
Assuming this is C then useisnanfrom<math.h>: ``` #include <math.h> if (isnan(angle[i])) { angle[i] = 0.0; } ```
I am trying to find an open source FFT solution that is written in low level C. I need to run a triple axis accelerometer coordinates through the FFT to due vibration analysis. I have looked all around through google and cannot find anything. Space is a major concern for me in because this is going on a small device. ...
It sounds like you needKissFFT. Simple, easy to use, lightweight, written in C, quite efficient, free, doesn't have all the baggage of the heavyweights like FFTW.
I am coming from Java , so i am familiar with synchronize and not mutex. I wonder if pthread_mutex_t is also reentrancy. if not is there another mechanism for this? Thank you
This depends on the mutex type, the default does no checking and an attempt to lock it more than once in the same thread results in undefined behavior. Read about ithere. You can create a mutex of typePTHREAD_MUTEX_RECURSIVEto be able to recursively lock it, which is done by providing apthread_mutexattr_twith the des...
``` int x=0; int*a=&x; void foo(int * a) { static x=0; x++; printf("x's value %d ", x); *a+=x; a=&x; *a=x+10; } int main(void) { foo(a); printf("a's value %d\n ", *a); foo(a); printf("a's value %d ", *a); return 1; } ``` I'm trying to analyze the above. First iteration ...
``` a=&x; *a=x+10; ``` The above code adds 10 tox, because you setato be a pointer tox, and then set the value pointed to byatox+10.
``` #define L 1 #define M L+1 int main(void){ int N=L*M*2; char s [N]={'1','2'}; printf("%d", sizeof(s)); return 1; } ``` Why does the above code cannot be compiled? The compiler of Eclipse says two things: Variable-sized object may not be initialized:Is because the definition of N with M and L...
because I can't initialize an array with type arr[x] where x is variable? Indeed, pre-C99, the array size must be aconstant expression. In C99, this has been relaxed withvariable-length arrays. (This is is nothing to do with macros.) excess elements in array initializer- What does it mean? Fix the first problem, ...
I have the following issues when trying to compile thelibtheoraplayerdemo (av_player demo). If someone can help me out with some errors from libtheoraplayer (), I would be really grateful.
If you are familiar with linux then check the vlc source code it is free but it is C code. it may be help to you. Thanks.
The problem is that the same code that compiles well on Windows, is unable to compile onUbuntu. Every time I get this error: cc1: warnings being treated as errors Now, it's big code base and I don't like fix all the warnings. Is there a way I can compile successfully in spite of the warnings?
Sure, find where-Werroris set and remove that flag. Then warnings will be only warnings.
Below are two files which I will use as my example. If I define an array of structures in file1.h and have file2.c include file1.h I would get a multiple definition error. Why is that? If I just have struct thread tasks[32] I don't get this error. file1.h ``` ... ... struct thread tasks[32] = {0}; // thread is struc...
Most likely you are including the header file in more than one source file. The#includedirective literally includes the contents of the header file into the source file, which means that all code in the header file will also be in the source file. This means that if two or more source file includes the same header fil...
I want tofprintf()3 strings to a file, all on the same line. The first two cannot contain spaces while the 3rd may. I.E.word word rest of line Can some one tell me how tofscanf()that into 3 variables? I don't mind putting some delimiters if it makes it easier. E.G.[word] [word] [rest of line]
You can do it without delimiters, too: ``` char s1[32], s2[32], s3[256]; if(sscanf(line, "%31s %31s %255[^\n]", S1, S2, S3) == 3) /* ... */ ``` This should work, as long as the inputlineactually does end with a newline. Of course, you should adjust the string sizes to fit. Also you can get trickery with the prepr...
I need to compress data for logging by appending short strings to the log file using C++/C. I first tired gzip(zlib), but this makes a symbol table for each short string and actually makes the data longer rather than compressing. I believe the thing I'm looking for is a static Huffman table. Anyway, I was wondering if...
You should look at theexamples/gzlog.[ch] source filesin thezlibdistribution. That code was written for precisely this purpose. It appends short strings to a growing compressed gzip file.
The following code is working fine in C but when I try to write it in c++ then the program does not work.Please explain. C code : ``` #include<stdio.h> #include<stdlib.h> int main() { int a = 33,b = 7; printf("%d\n",a&b); return 0; } ``` C++ code: ``` #include<iostream> using namespace std; int main...
Watch your operator precedence: ``` cout << (33 & 7) << endl; ``` &has lower precedence than<<. So you need to use(). For the full list of operator precedence in C and C++: http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence
I have built a working C library, that uses constants, in header files defined as ``` typedef struct Y { union { struct bit_field bits; uint8_t raw[4]; } X; } CardInfo; static const CardInfo Y_CONSTANT = { .raw = {0, 0, 0, 0 } }; ``` I know that the.rawinitializer is C only syntax. How do I define cons...
I had the same problem. For C89 the following is true: With C89-style initializers, structure members must be initialized in the order declared, and only the first member of a union can be initialized I found this explanation at:Initialization of structures and unions
I am writing a c++ application and trying to cross compile for arm: sudo apt-get install gcc-4.4-arm-linux-gnueabi However in the /usr/arm-linux-gnueabi/include directory I find no c++ directory. Can someone tell me where to find it?
Install C++ compiler: ``` sudo apt-get install g++-4.4-arm-linux-gnueabi ```
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. Just curious about the term vector ...
Yes, here "vector" means a one-dimensional array. This is a bit confusing because to represent a mathematical vector also uses a one-dimensional array, to store the coordinates in each of the dimensions, but this is a different usage. In this case, "vector" bring up an image of all of the elements of the array laid ...
I know that its possible to call functions in the native code from the java code, but what about vice-versa? Is it possible for me to call a Java function from the native C code?
Yes! You are interested in theJava Native Interface.
I have a string array of, ``` char *string_arr[] = { "Hi", "Hi2", "Hi3", "Hi4" }; ``` Now I need to realloc memory to the array, because I have to insert another element into the array like "Hi5". How can I do that? I tried: ``` string_arr = realloc (.....); ``` but it doesn't work, it gives: "incompatibl...
You can only "realloc()" a pointer to memory you got from "malloc ()". ``` char **string_arr; int nelms = 10; string_array = (char **)malloc (sizeof (char *) * nelms); if (!string_array) { perror ("malloc failed"); return; } string_array[0] = strdup ("Hi"); string_array[1] = strdup ("Hi2"); string_array[2] = st...
The Arm "#pragma anon_unions" allows: ``` typedef struct { uint32_t sensorID; uint8_t messageHeader; uint8_t messageID; uint16_t payloadLength; } Header; typedef struct { uint8_t startOfPacket[SERIAL_SOP_SIZE]; Header; // Anonymous. uint8_t payload[SIZE]; } Packet; Packet packet; pack...
It compiles in Visual C++ butonly in C mode: A Microsoft C extension allows you to declare a structure variable within another structure without giving it a name. These nested structures are called anonymous structures.C++ does not allowanonymous structures.
I am using the zeromq client server model. My client takes options from the command line and sends them to the server. The server reads each option and produces output to stdout (it has been adapted from a simple command line tool). What is the best way to redirect the stdout back to the client? If I can direct std...
You can redirect it to a filefreopen( "file.txt", "w", stdout ); or... combinestringstreamwithcout.rdbuf()
``` struct hostent *gethostbyname(const char *name) ``` Note that hostent.h_addr_list is a field with variant length. How does the functiongethostbynamehave the implementation that returns a pointer pointing to a struct but doesn't require the caller to release the resource? All examples used in the famous book Uni...
Themanpage you link to holds the answer: When non-NULL, the return value may point at static data, see the notes below. And a little later: The functions gethostbyname() and gethostbyaddr() may return pointers to static data, which may be overwritten by later calls.
``` int main(void) { int x; float y; x=10; y=4.0; printf("%d\n",x/y); return 0; } ``` I compiled this code using a gcc compiler and when run I get 0 as output.Why is this code giving output as 0 instead of 2?
IT's not the division, it's the print format. Change: ``` printf("%d\n",x/y); ``` to: ``` printf("%f\n",x/y); ```
in C# I would just do: ``` private long[] myMethodName() { //etc } ``` What is the equivalent in C? This gives an error: ``` long[] readSeqFile(char *fileName) ```
Typically for C you would pass a pointer and length ``` // returns number of elements written size_t myMethodName(long* dest, size_t len) { //etc } ```
Im having some trouble parsing http headers. Here is my problem: ``` char resp[] = "HTTP/1.1 200 OK\r\n" "Content-Type: text/html\r\n" "Content-Length: 4\r\n" "\r\n" "text"; // some stuff sscanf(resp, "HTTP/%f %d\r\n",&version,&code); sscanf(resp, "%*[^]Content-Le...
To first order one shouldneveruse the*scanffunctions. Parsing HTTP headers is significantly harder than it appears. I would first see iflibcurlhas already implemented something you can use, and failing that, go straight toflexandbison.
This question already has answers here:C preprocessor macro for returning a string repeated a certain number of times(5 answers)Closed5 years ago. Suppose I want to generate------, with only-, is there a C macro to generate repeated string ?
use boost, E.g ``` #include <stdio.h> #include <boost/preprocessor/repetition/repeat.hpp> #define Fold(z, n, text) text #define STRREP(str, n) BOOST_PP_REPEAT(n, Fold, str) int main(){ printf("%s\n", STRREP("-", 6)); return 0; } ```
I have this struct: ``` typedef struct Grades { int grade1; int grade2; int grade3; int grade4; int grade5; } ``` I created a pointer to a Grades struct using ``` struct Grades *pointer; ``` and I have a function() that returns a (void *) pointer to a specific Grades struct. How do I set my pointer to that...
If function() returns a pointer, you should be able to just do ``` pointer = function(); ```
Does anyone know how to set an int file descriptor buffer to no buffer and to flush immediately? I've tried to usesetvbufbut it takes aFILE*notint fd. Kevin
A file associated with anintis an operating system handle.setvbuf()manages buffers with a C runtime libraryFILE. To prevent buffering, you would have to use the proper operating system specific function, which perhaps can be done when the file isopened. For example, on Linux ``` int fd = open ("/dev/whatever", O_AP...
So I have this array in a header file like this: ``` // header.h static const unsigned int array1[]={0x00,0x01,0x02,0x03}; ``` And: ``` // file.c main() { unsigned int *ptrToArray; ptrArray = &array1[0]; } ``` Correct me if I am wrong. I assume: to find the number of bytes of array elements, instead of...
The type of*ptrToArrayisint, thereforesizeof(*ptrToArray)is the same assizeof(int). So it won't tell you anything about the number of elements inarray1. Whilst you can write*(ptrArray+1), etc., you should just writeptrToArray[1]!
I'm having a devil of a time finding out whether I can make a simple midi output layer using Coremidiwithoutusing Objective-C. The app is a QT desktop app in C++, and I want to keep OS specific things to a minimum and localized to just some output modules. Timing and latency is crucial so I'd like the midi output lay...
CoreMIDI's API is plain old C. You don't need Objective-C or C++. (It can of course be used directly from Objective-C or C++ code, if you want to, though.)
Are there any downsides to using'?'-style character literals to compare against, or assign to, values known to be of typewchar_t, instead of usingL'?'-style literals?
They have the wrong datatype and encoding, so that's a bad idea. The compiler will silently widen character literals (for strings you'd get a type mismatch compile error), using the standard integral conversions (such as sign-extension). But the value might not match. For example, characters 0x80 through 0xff often...
I am using MySQL. I have a select statement followed by a number of insert statement done using the C Connector. I would like to know how to put them all under one transaction and finally commit then. I have gone through the MySQL 5.0 Reference Manual andC API Function Overviewit have this functionmysql_commit()? I m...
As far as I understand, there is no mysql_starttransaction() or something similar; so you're stuck with something like: ``` mysql_autocommit(conn, 0); //Do stuff here mysql_commit(conn); //...or mysql_rollback(conn); ``` I would rather use the "query" method for all these calls: ``` mysql_query(conn, "START TRANSA...
(im a newbie in c) I was wondering how i can fetch text in .txt file located on the web, into a variable. I was looking on libcurl or something, but couldnt find out how to use it on Peppermint Os (based on Ubuntu/Debian). Anyone who can help me out?
If you don't absolutely need to do the downloading inside your program, you could simply download the file using wget or curl and then pipe the output to STDIN of your program, from where you store the input in a variable. This would allow you to use any file (from the web or not) as input.
This question already has answers here:Closed11 years ago. Possible Duplicate:access() Security Hole I quote from man page access(2): Warning: Usingaccess() to check if a user is authorized to, for example, open a file before actually doing so usingopen(2) creates a security hole, because the user might exploit th...
It is a classic"Time of check to time of use"race condition.
Are there any built in functions in C programming language for sorting arrays? Or do I have to write my own functions?
Check out qsort Syntax: #include <stdlib.h>void qsort( void *buf, size_t num, size_t size, int (*compare)(const void *, const void *) ); Description: Theqsort()function sorts buf (which contains num items, each of size size) using Quicksort. The compare function is used to compare the items in buf. compare should ...
Searching for manuals and docs about Open Watcom linker, inline assembly and C compiler, as I found official manuals not good enough. I'm focused especially on C and assembly. I would appreciate you for links to tutorials, books and etc.
Back in time Watcom was a perfect tool for 32-bit C/Asm development. At the same time much information could be found in ftp archives like good oldftp://x2ftp.oulu.fi. It is now defunct, butmirrorsexist. Look at the /watcom folder there. Also try searching older sites likehttp://www.programmersheaven.com, they arethe...
Given the below declaration for pcap callback: ``` void my_callback(u_char *args, const struct pcap_pkthdr *header, const u_char *packet) ``` How to ascertain the total number of bytes present in the packet? I need that value so that I can pass it to crc32() function.
according tothis referencethe information about the size of the packet is in thepcap_pkthdr's structure
I was trying to reverse a linked list, however whenever I execute the following function, I get only the last element. For example, if the list contained 11,12,13 earlier. After executing the function, it contains only 13. Kindly point out the bug in my code ``` void reverselist() { struct node *a, *b, *c; ...
Doesn't your loop guard insure that start is null?If you aren't using start to identify the first element of the list, then the variable you ARE using is still pointing to what WAS the first element, which is now the last.
I can't use C++ syntax likecout, so I've tried using<conio.h>but it still says undefined reference to '_gotoxy' What's the problem? Everyone says thatconio.hits not in K&R either because it isn't a standard library. Anyone got an idea? I am using MinGW and command prompt.
When linking you need to add the ncurses library: ``` $ gcc my-source.c -o my-program -lncurses ``` That last flag to the command line above (-lncurses) is what tells the compiler to link (-l) with the ncurses library.
I have created an app in android usingJNI(as major part of my code is in C).Now i am having a requirement to parsexmlin my application.since i have chosenlibxml2for my application, can any one please tell me how to uselibxml2in my android application.
since there is no prebuilt libxml.so/.a file for libxml2 parser, so we need to create the library (either .so/.a) and use that in application, u have to download all the .c/.h/android.mk/Application.mk and just build the libxml library(either .so/.a)
I am creating a decompiler from IL (Compiled C#\VB code). Is there any way to create reference in C? Edit:I want something faster than pointer like stack. Is there a thing like that?
A reference is just a syntactically sugar-coated pointer–a pointer will do just fine.
I want to useatoifunction in my program, but I found it not working. ``` #include <ctype.h> int value; value=atoi(buf); ``` char bufpoints to "1000" or something like, terminated by\0. I have checked it. But the value evaluates always to zero. I have triedstrtol(), but I get the same error. My ADS (ARM Developer Su...
ARM might have a problem with string functions, you haven't mentioned whether it returns a value and it's incorrect (i heard it's a bug and it's better you should write the function on your own) or there is no value at all. anyway look at the arm article about it i think it's the solution -ARM article about string fun...
I wrote the following: ``` #include <stdio.h> #include <string.h> char* getString(); char* getString(){ char str[10]; gets(str); return str; } int main() { char* s; s=getString(); strcpy(s,"Hi"); puts(s); return 0; } ``` I know that the length ofstrmust be less than 10, but even ...
``` char str[10]; // ... return str; ``` This iswrong!!!Local variables are invalidated when their scope exits; thus using returned array is undefined behavior. You have to malloc a string and return it: ``` return strdup(str); ```
Please tell me why the following code runs even on astrict C-99 compiler: ``` #include <stdio.h> int main() { int n; scanf("%d",&n); int a[n]; a[1]=10; a[2]=5; printf("%d %d",a[1],a[2]); } ``` The variable declaration must occur before any other statements in C right? If we so want a dynamica...
This is known as avariable-length array, and is supported by the C99 standard.This does not work in C89 or any version of C++.
``` #include <stdio.h> int main(void){ int *ptr; printf("the value of ptr is %p",ptr); } ``` This gives me0x7fffbd8ce900, which is only 6 bytes. Should it be 8 bytes (64bit)?
Although a pointer is 64 bits,current processors actually only support 48 bits, so the upper two bytes of an address are always either 0000 or (due to sign-extension) FFFF. In the future, if 48 bits is no longer enough, new processors can add support for 56-bit or 64-bit virtual addresses, and existing programs will ...
could any one explain what does #define something (54) mean? Why 54 is inside a bracket?
#define something (54)tells the C pre-processor to replace any text matching "something" with "(54)" before the code is actually compiled. The reason you will often see the use of( )around a#defineis that in some cases it prevents the replaced text from having adverse or undefined behavior when the#definedtext is rep...
I thought the result would be(2**32 - 1) ``` #include <stdio.h> int main(){ unsigned int a = 0xffffffff; printf("the size of int a %d\n",a); return 0; } ``` but it gives me-1, any idea?
You're using the wrong format string.%dis a signed decimal int. You should use%u. printfhas no knowledge of the types of variables you pass it. It's up to you to choose the right format strings.
I want to define a macro accepting either 1 or 2 parameters. Both the parameters should be different type. How to use ellipsis and read the arguments passed? Below is the sample: ``` void test(char *var2) { printf("%s\n",var2); } #define PRINT_STRING(...) ( if (!var1) test(var2) ) int main(int argc, _TCHAR a...
This is known as aVariadic macro.
I have written setter and getter APIs for certain members of a struct in C. I want the getter function to be called only if setter API was called. Otherwise, default values should be assigned to the members of the function. Is there a way to find out if the members of struct were assigned values or not? Thanks!
Is there a way to find out if the members of struct were assigned values or not ? No. You would need to keep track of that yourself by a separate set of variables, or by initializing the values of the struct to values they normally cannot have(e.g. -1 , but in such a case, every piece of code would need to honor the ...
I'm trying to send an array of characters in C, byte by byte to an output for a microcontroller. I'm using the following code: ``` int main() { ... LogOutput("Hello World!"); } void LogOutput(char *msg) { int i; for (i = 0; i < sizeof(msg); i++) { USART0_TX(msg[i]); // transmit byte ...
You're using thesizeofoperator, and getting the size of thedatatype, not the length of the string. Usestrlento get the length of a string (includestring.hforstrlenand other string manipulation functions).
This question already has answers here:Closed11 years ago. Possible Duplicate:Split string with delimiters in C What's the best way to split a "," separated list into an array in C. I know how many things are in the list. ``` char list = "one,two,three,four"; int ENTServerAmount = 8; char **ENTServer; ENTServer = m...
strtok()is probably the function you are looking for. ``` char list[] = "one,two,three,four"; int ENTServerAmount = 8; char **ENTServer; char *tmp = strtok (str, ","); int index = 0; while (pch != NULL) { ENTSever[index++] = tmp; tmp = strtok (NULL, ","); } ```
My question ist ``` void function (const char **params) { const char *para; para = &params[0]; //1 para = params; //2 para = *&params; //3 } ``` all 3 options will be compiled by Netbeans gdb but gcc says sth like assignment from incompatible pointer type. Why is this differnce .....
In all three cases, the type of the right-hand side isconst char **, which cannot be assigned to aconst char *without a cast. All compilers should warn you about this if you turn their warning level up high enough. It's not clear what you want to do; if you want to point at the beginning of the first sub-array, then...
How would I approach this algorithmic problem? Given two words of equal length that are in a dictionary, write a method to transform one word into another word by changing only one letter at a time. The new word you get in each step must be in the dictionary. Example: ``` Input: DAMP, LIKE Output: DAMP -> LAM...
Try thinking this problem in terms ofgraphs: Consider all words in a dictionary as vertices, and insert an edge between each two vertices that differ by only one letter. The output is a well-known object in the graph, and you probably already know an algorithm to solve the problem. Spoiler: The output is a path in t...
How does the header stdint.h define u32 to be 32 bits on every machine? Could somebody elaborate on the process that stdint.h does to make this happen? Where can I find my machine's (Windows 7) stdint.h file?
The provider of the C standard library for the compiler toolchain will ensure that it is correct for that particular deployment. Presumably they are allowed to use whatever means necessary to ensure this is the case. It could be as simple as knowing whether to typedef it to int or long.
Suppose my C program handlesSIGUSR1. When it receives this signal, is it possible to know who sent it? I.e., How to get the pid of sender process?
Yes, if you use thesigaction()call to set up your signal handler instead ofsignal. Doing so will let you set up a signal handler that takes three parameters: Anint, for the signal number (just likesignal)Asiginfo_t *, which is a structure containing all sorts of information about the source of the signal, including t...
I have a misunderstanding regarding this code - ``` typedef struct _EXP{ int x; char* name; char lastName[40]; }XMP ...main... XMP a; a.name = "eaaa"; a.lastName = strcpy(a.lastName, "bbb"); ``` Why can't I use:a.lastName = "bbbb";and that's all?
Well consider the types here. The array has thecontents ofthe string, while thechar*merelypoints tothe data. Consequently the array requiresstrcpyand friends. Besides, if you allocated memory for thechar*on the heap or stack and then wanted to assign some content to that, you'd also have to usestrcpybecause a mere as...
Why the result of these two expressions should be different ?The same thing happens in gcc and python. what is happening in here ? Is there any way to prevent it ?
Floating point numbers have limited precision. If you add a small number (3) to a large number (1e20), the result often is the same as the large number. That is the case here, hence ``` (3 + 1e20) - 1e20 = 1e20 - 1e20 = 0 ``` The precision ofdoubleis roughly 15 decimal digits,floats have about 7 decimal digits of pr...
I came across the following problem while reading ...just cant get the logic behind this. ``` auto int c; static int c; register int c; extern int c; ``` It is given that the first three are definition and last one is declaration ..how come ?
The last one withexterndoes not define storage forc. It merely indicates thatcexists somewhere and the linker should be able to resolve it to some globalcdefined elsewhere. If you compiled and linked a single .c file and tried to use the lastcyou'd have a linker error. With the the first 3cs you would not as they hav...
I am looking at the Connection Manager (ConnMan) source code, which is a tool for Linux(-like) systems to manage networks. One of the (undocumented) source files has the vague namingrtnl.c. Does anybody know, what is meant with RTNL? Googling for it was not very effective. Every site that really is connected to networ...
If you look at the source it says it's for "Routing Netlink". The netlink manpage says " Netlink is used to transfer information between kernel and userspace processes." The source for rtnl.c is only like 50 lines and it seems pretty obvious from reading it what it's for...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. Where can I find the latest ANSI C ...
You can buy it here (ISO/IEC 9899:2011): http://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=57853 Price is around USD 240. You can also get the latest (April 12, 2011) draft version for free: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf UPDATE (June 16, 2016): C11 has also ...
In the book it explains: ``` ptr = &a /* set ptr to point to a */ *ptr = a /* '*' on left:set what ptr points to */ ``` They seem the same to me, aren't they?
No. The first one changes the pointer (it now points ata). The second one changes the thing that the pointer is pointing at. Consider: ``` int a = 5; int b = 6; int *ptr = &b; if (first_version) { ptr = &a; // The value of a and b haven't changed. // ptr now points at a instead of b } else { *ptr...
I stumbled upon code containing something like: ``` char c = "abc"[1]; ``` and it compiles and runs fine with gcc!cwill be'b'after this expression. Is this standard to index literal strings or is it mere luck that it works?
Of course it is, a string literal is of array type. It is converted to a pointer tocharin the expression and is like an any pointer tochar. ``` char c = "abc"[1]; ``` and ``` char *p = "abc"; char c = p[1]; ``` are equivalent.
I am running CC compiler over SUN/Solaris, I have more then 64 threads assigned by the OS to different cores. I am interested to know if there is method to get the core id for different threads during run time? I am not setting affinity for those threads, i use psrset to create the processor set.
I found the answer: getcpuid() on Solaris returns the core id (even for hyper thread): i have tested it and it works great.http://www.unix.com/man-page/all/3c/getcpuid/
In the first program below there is no error.But for the second program there is an error. Why is that so? First program: ``` #include<stdio.h> void main() { int k=8; int m=7; k<m?k=k+1:m+1; printf("%d",k); } ``` Second program: ``` #include<stdio.h> void main() { int k=8; int m=7; k<m?k=k+1:m=m+1; printf("%d",k);...
The conditional operator has higher precedence than the assignment operator. You need extra parentheses to have the desired precedence. ``` k < m? k = k + 1 : m = m + 1; ``` is evaluated as ``` ((k < m) ? (k = k + 1) : m) = m + 1; ``` Add parentheses to have the correct precedence: ``` (k < m) ? (k = k + 1) : (m ...
I have a problem with receiving UDP packets. My environment is running Android 2.1 on ARMv7. With C socket programming, I userecvmsgto receive packets from kernel but occasionally there are some packet loss events. The sender and receiver are in the same LAN so it's no doubt that packets shouldn't lose. And I proved ...
Yes, it's possible. UDP is unreliable. If dropping of UDP datagrams is creating a problem, then something is very wrong with your design.
A certain parameter has3possible values, and there arensuch parameters with 3 values each. Need to create scenarios by randomly changing them and save each scenario as a text file, without any duplicated scenarios.
Count from 0 to 3n-1, and convert your number to an n-digit base-3 number (including leading zeros). Each digit in the result represents the value for one parameter.
I'm trying to create a C program in the CodeBlocks IDE (on Windows), and something I need is the library . When I try and build and run, this line errors: ``` #include <sys/times.h> ``` What do I do? Is that a Unix library? Can I download it and just add it somehow to my CodeBlocks environment? I mean, is already t...
Remove -ansi compilation flag fromSettings>Compiler and Debugger>Compiler Optionsin Code::Blocks. If that does not help,<sys/times.h>is unavailable under Windows. Edit:sys/times.his a part of thePOSIXlibrary. POSIX headers are not available under MinGW, and need Cygwin.time.his a standard ANSI header. If you want to...
I'm using the following code to get the output up to 5 decimal characters of any number input by user when divided by 1, I have to typecast it with(float). Can any one tell me how this can be done without typecasting or using float constant? ``` int main() { int n; scanf("%d",&n); printf("%.5 ", 1/(float...
You canuse this piece of codethat uses only integers: ``` printf(n==1?"1.00000":"0.%05d ", 100000/n); ```
This question already has answers here:Closed11 years ago. Possible Duplicate:Why does modulus division (%) only work with integers? This code doesn't work in C and C++ but works in C# and Java: ``` float x = 3.4f % 1.1f; double x = 3.4 % 1.1; ``` Also, division remainder is defined for reals in Python. What is t...
The C committee explained its position of why there is no remainder operator for floating types in theRationaledocument: (6.5.5 Multiplicative operators)The C89 Committee rejected extending the % operator to work on floating types as such usage would duplicate the facility provided by fmod (see §7.12.10.1).
``` #include <langinfo.h> #include <stdio.h> int main(int argc, char **argv){ char *firstDayAb; firstDayAb = nl_langinfo(ABDAY_1); printf("\nFirst day ab is %s\n", firstDayAb); return 0; } ``` This code works fine on Mac and Linux but it doesn't work on windows due to absence of langinfo.h. How to avoid using lang...
``` #include <stdio.h> #include <time.h> int main () { struct tm timeinfo = {0}; char buffer [80]; timeinfo.tm_wday = 1; strftime (buffer, 80, "First day ab is %a", &timeinfo); puts (buffer); return 0; } ```
I have a text field that is editable by the user and it contains some example text saying "Tap here to enter details". I would like the text box to clear when the user taps it so that the user does not have to delete my example before inputting their message. Is there an easy way of doing this. The only thing I can th...
There is a property for UITextFieldclearsOnBeginEditing
I have a file which will contains basic mathematical operations. An example: ``` 1 + 23 / 42 * 23 ``` I am scanning the file, putting each "element" into a struct and pushing it onto a stack I created. The problem I have is as follows: ``` char reading; while(!feof(fp)) { fscanf(fp, "%c", &reading); .... ``` T...
fscanfis the wrong tool for this job, because it needs a format string that knows in advance what format to expect. Your best bet is to read a character at a time and build up tokens that you can then interpret, especially if you'll have to accept input like2+2(no spaces), or(1 + 23) / 42, with parentheses.