question
stringlengths
25
894
answer
stringlengths
4
863
I need to make an array of strings for a program in one of my CS classes. We are to just assume that the length of all the strings is no more than 50 (this accounts for the null character). I need usemalloc()orcalloc()to allocate the proper amount of memory for the array, but I am new to C and I don't really know ho...
Assuming typechar, at minimum you will needX * sizeof(char) * 50. If you are doing all of these allocations separately, there will be overhead for each allocation. So the total amount of memory in this case will be higher. This overhead is unspecified and can be fairly large. But I wouldn't worry about that for a h...
I am trying to sum values in a for loop with C. The initial value of variablex = 1and I want to double it a set number of times and add the result. I have made the for loop, but my sum is always off by the initial value. For example, ifx = 1, the pattern should go: ``` 1, 2, 4, 8, 16 ``` ...and thetotalshould be31....
Switch the two statements in the body of the for loop. Also it is a good idea to initialize total to 0, in case you want to move all of this into a function.
Is there any difference between these two functions? I mean in-terms of the result returned? ``` int Length(struct node* head) { struct node* current = head; int count = 0; while (current != NULL) { count++; current = current->next; } return count; } ``` and this function ``` int Length(struct n...
They are the same. One uses a local 'current' variable to iterate over the list, while the other one uses the same variable that was received through the function arguments.
I need R header files to compile something. I installed R on ubuntu via: ``` sudo apt-get r-base-dev ``` R works fine. But I can't find the R headers such as Rmath.h. I get this error when I try to compile: ``` gcc -g -std=c99 -I/usr/include -O3 -lRmath -lm -lpthread -o qcpg qcpg.c In file included from qcpg.c:1:0...
You also want to do ``` sudo apt-get install r-mathlib ``` which contains, among other things, the file/usr/include/Rmath.h.
If I have a program that is using scanf to get user inputted data: ``` scanf("%d",&val); ``` When I run it through lint I get warnings saying that scanf returns a int and it is not being assigned anywhere. What is the c practice to solve this problem? Do I type cast it as void? ``` (void)scanf("%d",&val); ```
The C best practice to solve this warnings is simple: Check the resultcode. The scanf function returns in the int if the operation has gone ok or not, and stores the error usually in errno. The lack of resultcode checks usually results in big errors in certain situations.
I have a "generic" linked link in C that takesvoid * datato store the data in a Node. ``` insertNode(linkedList * list, void *data); //Storing/retrieving a string works fine; char *str="test"; insertNode(list, str); char *getback=(char *)node->data; //Storing/retrieving an Int results a cast warning int num=1; ins...
Useintptr_toruintptr_t. They are integers of the same size as a pointer: ``` #include <stdint.h> ... intptr_t num = 1; insertNode(list, (void *) num); intptr_t getback = (intptr_t) node->data; ``` Of course, the maximum value that you can store depends on the system, but you can examine it at compile time viaINTPTR_...
I'm trying to make coroutine and continuation with C. I realized I need some kind of spaghetti stack. Is it possible to execute a function within a new call-stack? Of course within single thread. How can I make a new, separated call-stack, and execute some code on it?
check out makecontext/swapcontext. If those aren't available, then you could use setjmp/longjmp, but those are a little more complex.
What is the default WindowProc of a list-view control before I change it usingSetWindowLong()?
That's determined by the system when it registers the window class. It is presumably implemented in comctl32. There's nothing special about one of the built-in window classes in this regard. Just as is the case for a user defined class, the default window proc is whatever was specified when the class was registered.
The return value of an open() was -1 and on trying to find the error using perror() the output was "File exists". How do I find the error or the reason for the file not opening.
Looks like EEXISTpathname already exists and O_CREAT and O_EXCL were used.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question Why is it required to initialise the references during its initialisation. If not initialised it throws err...
In C there are no references. You probably mean address operator:http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Faddre.htm
Note that in general,doubleis different fromlong double. strtodconverts string todouble, but which function should be use to converting string to long double?
In C++03, useboost::lexical_cast, or: ``` std::stringstream ss(the_string); long double ld; if (ss >> ld) { // it worked } ``` In C99, usestrtold. In C89, usesscanfwith%Lg. In C++11 usestold. There may be subtle differences as to exactly which formats each one accepts, so check the details first...
I'm looking for some way of splitting the console into distinct zones, a bit likescreendoes. The idea is to "freeze" the first X lines, so that they display fixed information, only updated from time to time, while the remaining lines keep working like normal. I've seen this in an application running on an ARM Linux d...
I assume you can make use of theNCurses libraryto achieve the user experience you describe.
I need to create three bit masks that end up in three 32-bitunsigned ints(let's call them x, y and z). The masks should end up like this: ``` x: 0000 0001 1111 1111 1111 1111 1111 1111 y: 0000 1110 0000 0000 0000 0000 0000 0000 z: 1111 0000 0000 0000 0000 0000 0000 0000 ``` So far I've got this: ``` unsigned int x ...
``` unsigned int x = 0x01FFFFFF, y = 0x0E000000, z = 0xF0000000; ``` Is this readable for you?
I am using theandroid/log.hmethods in my native code to write to the android log (__android_log_write(ANDROID_LOG_INFO, ANDROID_DEBUG_TAG, message);). I am also doing logging in the Java code. However, when running, only the log messages from the Java code is displayed in the logger. What could cause these problems? ...
I'm not sure, but I use__android_log_printin my NDK code and that works fine. I don't know the difference between the two methods off the top of my head, but give that a try (it takes the same arguments).
I have a structure like this ``` typedef struct{ int stat; }dot; ``` And I would like to acces this structure in a procedure like this ``` void change(dot *stat){ stat[5][5].stat = 5; } int main(){ dot mydottes[10][10]; mydottes[5][5].stat = 3; change(&mydottes); return 0; } ``` But when I ...
Change your code as follows: ``` void change(dot stat[][10]){ // <<< stat[5][5].stat = 5; } int main(){ dot mydottes[10][10]; mydottes[5][5].stat = 3; change(mydottes); // <<< return 0; } ```
I want to be able to tell when my program's stdout is redirected to a file/device, and when it is left to print normally on the screen. How can this be done in C? Update 1: From the comments, it seems to be system dependent. If so, then how can this be done with posix-compliant systems?
Perhapsisatty(stdout)? Edit: As Roland and tripleee suggest, a better answer would beisatty(STDOUT_FILENO).
What is exactly the difference between commands exec(const char *c) and system(const char *c) in unix based systems ? Both can be called from a C program to execute system calls. Is there a difference b/w the two ?
execreplaces your process with the specified program. Your program is done, and will not continue running. spawnstarts a new process (probably by first usingfork), and runs the specified program while your program continues executing. systemstarts a new process (probably by first usingfork), and runs the specified ...
I use this method for doing malloc over a 2d array, my sources arehttp://c-faq.com/aryptr/dynmuldimary.htmlandModify malloc strategy for 2D Array so malloc succeeds: ``` int main(int argc, char *argv[]) { long **array = NULL; array = malloc(5 * sizeof(long *)); for (int i = 0; i < 5; i++) array[i...
You're invoking undefined behaviour. Undefined behaviour, as its name implies, isn't defined to cause a segmentation fault. That code could set the value of that memory to the value you're giving it, it could ignore the assignment completely, or it could order pizza for all we know.
I was asked this as interview question. Couldn't answer. Write a C program to find size of structure without using thesizeofoperator.
``` struct XYZ{ int x; float y; char z; }; int main(){ struct XYZ arr[2]; int sz = (char*)&arr[1] - (char*)&arr[0]; printf("%d",sz); return 0; } ```
I want to connect to oracle database using C language in Windows OS. But I do not how to start with it and what will be pre-requisite? can any one provide me any help or tutotial or sample code? Thank you.
http://www.dreamincode.net/forums/topic/30799-how-to-connect-c-with-oracle/ Oracle C++ Call Interface (OCCI) is an Application Programming Interface (API) that provides C++ applications access to data in an Oracle database. To know more about the OCCI refer here http://www.oracle.com/technetwork/database/features/o...
I've looked through the docs and it seems that you can only execute an xpath search from axmlDocPtrby creating anxpath context. Is there anyway inlibxml2to xpath search from axmlNodePtr?
CallxmlXPathNewContext(), specifying the real top-levelxmlDocPtrfor the document, then set thexmlXPathContext::nodefield to the desiredxmlNodePtrpointer that is a child of thexmlDocPtrdocument.
I am trying to understand the for loop better. I have the following variables: x = 1 y = 10 I want to increment x and double it ten times with a for loop to have the following output: 1, 2, 4, 8, 16, etc. This is what I have, but it is not quite doing the trick: ``` int x = 1; int y = 10; for (int i = 0; i < y;...
It looks fine to me. If you want it to print at each iteration, you need to move theprintfinto the loop. Also, your code will only work in C99 or with GCC's default extensions since you haveint iinside theforloop.
I need to make an array of strings for a program in one of my CS classes. We are to just assume that the length of all the strings is no more than 50 (this accounts for the null character). I need usemalloc()orcalloc()to allocate the proper amount of memory for the array, but I am new to C and I don't really know ho...
Assuming typechar, at minimum you will needX * sizeof(char) * 50. If you are doing all of these allocations separately, there will be overhead for each allocation. So the total amount of memory in this case will be higher. This overhead is unspecified and can be fairly large. But I wouldn't worry about that for a h...
I am trying to sum values in a for loop with C. The initial value of variablex = 1and I want to double it a set number of times and add the result. I have made the for loop, but my sum is always off by the initial value. For example, ifx = 1, the pattern should go: ``` 1, 2, 4, 8, 16 ``` ...and thetotalshould be31....
Switch the two statements in the body of the for loop. Also it is a good idea to initialize total to 0, in case you want to move all of this into a function.
Is there any difference between these two functions? I mean in-terms of the result returned? ``` int Length(struct node* head) { struct node* current = head; int count = 0; while (current != NULL) { count++; current = current->next; } return count; } ``` and this function ``` int Length(struct n...
They are the same. One uses a local 'current' variable to iterate over the list, while the other one uses the same variable that was received through the function arguments.
What's the logic behind calls likegetpid()returning a value of typepid_tinstead of anunsigned int? Orint? How does this help? I'm guessing this has to do with portability? Guaranteeing thatpid_tis the same size across different platforms that may have different sizes ofints etc.?
I think it's the opposite: making the program portable across platforms, regardless of whether, e.g., a PID is 16 or 32 bits (or even longer).
I'm trying to compile c/c++ program online by gcc compiler. when user enter c/c++ code,I will make temp file (temp.cpp) and after that I will compile it by ``` exce('gcc temp.cpp'); ``` php function.after that I will run it by exce() function too. now how can I sure user c/c++ code don't be to hurt my website?how can ...
As long as you don't execute the compiled program on your server, it's fine. If youdorun the program on your server, then you'll have to sandbox it, which can be difficult. Seecodepad's about pageto see how they do it.
Is ``` void * mremap(void *old_address, size_t old_size , size_t new_size, unsigned long flags); ``` compatible with malloc()? GCC (C++) and using Linux. Thanks.
No, it is not. Apart from the fact thatmallocdoesn't need to give you an address at a page border (which is whatmremapexpects), it would be dangerous to mess with memory mappings frommallocwithoutmallocknowing you did it. Usereallocinstead.
The below program gives me an error in the intialisation(*a)[5]=((*)[])&v;. When I don't type at that line then I'm still getting the error. ``` int main() { int v[10]; int **p; int (*a)[5]; (*a)[5]=((*)[])&v; printf("%d\n",*a); printf("%d\n",sizeof(v)); return 0; } ```
&vis a reference to the int arrayv, so it is of typeint **(essentially).int (*a)[5]means you're declaring a pointer to an array of 5 ints. BUT, in the next line, when you write,(*a)[5], it means you are dereferencingato get an int pointer, and then dereferncing again to access the element stored at[5]. but arrays in C...
I have a thread that is essentially just for listening on a socket. I have the thread blocking on accept() currently. How do I tell the thread to finish any current transaction and stop listening, rather than staying blocked on accept? I don't really want to do non-blocking if I don't have to...
Use theselect(2)call to check whichfdare ready to read. The file descriptors from call can be read with out it blocking. egaccept()on the returned fd will immediately create a new connection.
What was is it the original reason to usetrigraph sequenceof some chars to become other chars in ansi C like: ``` ??=define arraycheck(a, b) a??(b??) ??!??! b??(a??) ``` becomes ``` #define arraycheck(a, b) a[b] || b[a] ```
Short answer: keyboards/character encodings that didn't include such graphs. From wikipedia: The basic character set of the C programming language is a superset of the ASCII character set that includes nine characters which lie outside the ISO 646 invariant character set. This can pose a problem for writing source c...
Sorry if this question is silly, but I can't seem to find the answer on Google. I haven't done C programing in a while and for the life of me remember how, in C or C++, to jump back (or forward) to a specific line in code. If I remember right, there was a way to do this. Thanks for the help! Cheers!
The infamous goto, in conjuntion with labels. ``` label_name: goto label_name; ``` Before using it, search for 'goto considered harmful'.
I use curly braces with all of my switch case statements in C/Objective-C/C++ I had not, until a few moments ago, considered whether including thebreak;statement inside the braces was good or bad practice. I suspect that it doesn't matter, but I figure it is still worth asking. ``` switch (foo) { case 1: { ...
Short answer: it doesn't matter.
I am trying to measure the execution time taken by some functions in my C code. I am ussing the difference of time using the clock() function, but I mostly get 0 as a result, since the value of CLOCKS_PER_SEC seems to be set at only 1000 on my implementation. What are some other ways to measure accurately the executi...
You can use performance counters: http://msdn.microsoft.com/en-us/library/ms644904%28v=vs.85%29.aspx
I have a code like this: ``` #include<stdio.h> int main() { extern int i; i = 20; printf("%d\n", sizeof(i)); return 0; } ``` I get an error like this: ``` In function `main': undefined reference to `i' ``` Even though I have definediwhy there is an error thrown? Thanks in advance.
You have declared i to be defined in a separate file, but haven't linked to an external file. If you remove the extern keyword, this will work as you expect.
I ran into the following code in an old exam of the C course I'm taking: ``` struct QuestionSet{ char q1:1; char q2:1; char q3:1; } ``` I have no idea what the syntax "char q1:1" means, and I haven't been able to find it anywhere in "The C Programming Language" which is the course book. Can anyone explai...
It's abitfield. The number after the colon indicates the number of bits to assign to the struct element. So the three elements are all one bit wide, and are able to store two values: 0, and either 1 or -1 (depending on your compiler, though -1 would be the more logical option when considering two's-complement arithm...
If my application runs 'x' number of threads, and if there are any one of them does the nasty memory corruption, and hence SIGFAULT occurs!!!. Does it affect other threads also ?
Unless you handle it, then yes, it kills the entire application.
I have public interface which allows people to interact with the database by typing in sql commands. However, I do not want them to change the database in any way (and if possible, not access certain tables). As I understand though, SQLite has no concept of users, so how do I accomplish this?
If within the query there are no application definedsqlfunctions, which indirectly modifies the database(e.g:SELECT eval('DELETE FROM t1') FROM t2;), then usesqlite3_stmt_readonlyto determine whether the preparedsqlstatement writes the database, otherwise you can try to open an other,read_only, database connectionhand...
I want to obfuscate my dll export names. I have come across the same question in stack overflow in the below link, However I could not find the acceptance of solution.Modify dll exports (symbol table). I want to obfuscate the function names Can anyone suggest?
You can use a .def file, in which you can either give exported functions other names, or just export them by ordinal. SeeExporting from a DLL Using DEF Filesand.def files C/C++ DLLs.
Some of theCcode do not compile withC++compiler if compiled asC++files, due to the stricter type safety ofC++. Is there any tool which takes theCcode and generates a validC++code out of it. In other words, it adds to theCcode what is required to make that code compile with aC++compiler. Note that I know that C and C+...
Simply place your C code in a separated .c file, within your project, and you should be able to compile it as C. Which compiler are you using?
``` #include<stdio.h> main() { int x[3][5]={{1,2,10,4,5},{6,7,1,9,10},{11,12,13,14,15}}; printf("%d\n",x); printf("%d\n",*x); } ``` Here first printf will print the address of first element. So why not the second printf prints the value at the address x i.e the first value. To print the value I need to write **x.
For pointers,x[0]is the same as*x. It follows from this that*x[0]is the same as**x. In*x[0]: xis aint[3][5], which gets converted toint(*)[5]when used in expression. So x[0] is lvalue of typeint[5](the first 5-element "row"), which gets once again converted toint*, and dereferenced to its first element. *xis evalua...
If I want to make a commandline tool using makefile for, say this C program: ``` # include<stdio.h> int main() { printf("Hello World!"); return 0; } ``` I have no previous experience with makefile or linux shell commands whatsoever. Just starting out. Can anyone tell me how to go about it?
You don't really need a makefile for a single source file like this - just compile it like this: ``` $ gcc -Wall foo.c -o foo ``` If you really want a makefile though then you can do something like this: ``` # # makefile # foo: foo.c gcc -Wall foo.c -o foo ``` then from the command line you could say: ``` $ ...
If I store a pointer to a function, and then at some later point during my program's execution, compare it to the address of the same function, are the two addresses guaranteed to be equal. E.g. ``` int foo(void){return 0;} int (*foo_p)(void) = &foo; assert(foo_p == &foo); ``` In the above code is the assertion al...
Per 6.5.9: Two pointers compare equal if and only if both are null pointers, both are pointers to the sameobject (including a pointer to an object and a subobject at its beginning) orfunction, both are pointers to one past the last element of the same array object, or one is a pointer to one past the end of one array...
Inint (*x)[10];xis a pointer to an array of 10ints So why does this code not compile: ``` int arr[3] ; int (*p)[3] =arr; ``` But this works: ``` int arr[3]; int (*p)[3] =&arr; ```
arris an expression that evaluates to anint*(this is the famous 'arrays decay to pointer' feature). &arris an expression that evaluates to aint (*)[3]. Array names 'decay' to pointers to the first element of the array in all expressions except when they are operands to thesizeofor&operators. For those two operation...
As the mutex in most of the systems are implemented using CAS ops, I was wondering about performance comparison of these two constructs. Is it fair to say that if a mutex is implemented using CAS, then the try-lock call on that mutex will be same/similar performance compare to CAS operations ? CAS, being highly syst...
Your reasoning is sound; on any sane implementation, the cost of a "trylock" operation will be roughly the same as a CAS. However, CAS in general cannot be replaced by trylock; trylock is a weaker primitive that can't manipulate arbitrary data.
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...
Look atmsgpack-rpc. It's easy and very simple RPC implementation.
I'm using a pre-built library called 'libdscud-6.02.a', which includes a lot of low level I/O calls for some specific hardware. From this, I created some wrapper functions which I compiled into an object file called 'io.o'. Now, I have a few programs which I'm compiling with these I/O functions and instead of having...
You could do the opposite and add the io.o file to the .a file using ar: ``` ar q libdscud-6.02.a io.o ```
This question already has answers here:Closed12 years ago. Possible Duplicate:Why is FILE all-caps as in FILE*? Why is the standard libraryFILEtype written uppercase ?Is it because of its opaque nature ? Thank you.
If you look at the naming convention used in C, upper case is typically used for preprocessor macros. My guess is that it originally was implemented as a macro expanding to the concrete type used by the library implementation.
my current makefile looks likes this ``` all: hello hello: hello.o clang -o hello hello.o hello.o: hello.c clang -Wall -std=c99 -c -o hello.o hello.c -lpthread clean: rm -f *.o *exe hello ``` How can I modify it to compile with the following: ``` clang -std=gnu99 -Wall -o hello hello.c -lpthread ```
Use ``` hello: hello.c clang -std=gnu99 -Wall -o hello hello.c -lpthread ``` instead of the two rules you have for hello and hello.o now. When your program gets bigger, however, the separation of compilation to object files and linking may at some point be faster than compiling and linking everything in one go....
Is there a portable library to watch for filesystem changes without polling? I know there is inotifyfor Linuxsolution for osxFindFirstChangeNotificationfor WindowsNIO.2for JavaSystem.IO.FileSystemWatcherfor .NET but i have not found any portable wrapper for those. Is there a portable wrapper for Linux, Windows and...
QFileSystemWatcher-- Qt is very cross-platform.
Thedocumentation for GCC's__attribute__((...))syntaxindicates that attributes must be surrounded by double parentheses, but does not give a rationale for this design decision. What practical reason would have caused GCC's designers to require this? Does it have anything to do with the preprocessor's handling of doubl...
To make it easier to eliminate it for different compiler. If you have portable code, you have to remove them for other compilers, so you do ``` #ifndef __GNUC__ #define __attribute__(x) #endif ``` The problem is that attributes have various number of arguments and you can combine multiple attributes in one__attribut...
If I use something likedoubleto hold file sizes in bytes, this will naturally fail very soon, so which data type would I use? Nowadays a couple of TB are common, so I'd like the data type to be able to hold a number that big.
It will depends on you platform. On Unix System, you can probably use theoff_ttype. On Windows, you'll probably want to useLARGE_INTEGER. Those are the types used on those system by the function returning the file size (staton Unix,GetFileSizeon Windows). If you want a portable type,uint64_tshould be large enough.
I need to compile a program in MS-DOS. I have the Borland editor, and I can compile the program usingAlt+F9, but what does it do at the backend? I want to compile it in MS-DOS. I’m trying this: ``` cd c:\tc\bin tcc -o hello.exe hello.c ``` wherehello.cis my file, andhello.exethe file I want to produce. It's not work...
If I remember correctly, Borland/Turbo C compiler's command line options didn't look like gcc options. You should trytcc /?for a command line help.
I have a custom class Manager in Xcode. This class spawns several instances of class Player on a timer, so every tick of the timer it will make a new instance. I would like to pass the instance of Manager to each instance of Player through Players init method: -(id)initWithMngr:(UIImage *)image andManager:(Manager *)...
You should add either#import "Manager.h"or@class Manager;to your file, where interface ofPlayerclass is defined - possibly, "Player.h". (Here I suppose that yourManagerclass interface is defined in "Manager.h" file andPlayer- in "Player.h".) If you will choose variant with@class Manager, don't forget to add#import "M...
Why this code give me a warning says: passing argument 1 of "test" from incompatible pointer type? I know it's about the const before char **, but why? ``` void test(const int ** a) { } int main() { int a=0; int *b=&a; int **c=&b; test(c); return 0; } ```
You can't assign anint **to aconst int **, because if you did so, the latter pointer would allow you to give anint *variable the address of aconst intobject: ``` const int myconst = 10; int *intptr; const int **x = &intptr; /* This is the implicit conversion that isn't allowed */ *x = &myconst; /* All...
The question title might be misleading when read out of context. Let me first explain what I am trying to build. I am building a script which will take 100s of very simple C programs written by my students and check for some very basic properties such as. Have they declared a variable called 'x', is it's type 'int' ...
You can use ANTLR to do this. There is already a C grammar you can use with ANTLR so mainly all you have to do is pass the code into antlr then walk the syntax tree looking for various attributes.... you can use ANTLR from a number of languages. While it might seem daunting at first. It's actually surprisingly ea...
In 3 operations how can I turn a byte into a 32 bit int that matches this: 0x1fffe I can only explicitly access a byte at a time thus I start with 0xFF and then shift it. I can do it using 4 operations but I cant find a way to eliminate one operation. ``` int mask2 = 0xFF << 8; mask2 = mask2 | 0xFE; mask2 ...
Maybe this is what you want... you start withone singlebyte value (0xff), and you work on it with 3bitwiseoperations, obtaining 0x1fffe. ``` int in = 0xff; int out = in<<9 | in<<1; ```
I have a text file with hexadecimal values, after I fscanf a value I need to know how I can convert it from hexadecimal string to an int. And then convert it back to hexadecimal string for a later print. Anyone knows an algorithm for this? thank you.
You should use the%xformat specifier instead of%sto read your values. This will read the data as hexadecimal integers. For example, if your file looks like this: ff3c 5a cb2d Then you can read those 3 values like this: ``` int a, b, c; fscanf(fp, "%x %x %x", &a, &b, &c); // a = 0xff3c, b = 0x5a, c = 0xcb2d ```
I'm developing on an ARM9E processor running Linux. Sometimes my application crashes with the following message : [ 142.410000] Alignment trap: rtspserverd (996) PC=0x4034f61c Instr=0xe591300c Address=0x0000000d FSR 0x001 How can I translate the PC address to actual source code? In other words, how can I make sen...
Withobjdump. Dump your executable, then search for4034f61c:. The-x,--disassemble, and-loptions are particularly useful.
I learned how to encode wav into an mp3 usinglame_encode_buffer_interleavedfrom this question:Is there any LAME c++ wraper\simplifier (working on Linux Mac and Win from pure code)? Now I want to decode the mp3 back into wav. I know there'slame_decodebut I don't know how to use it since it requires two pcm buffers (pc...
Take a look into the lame frontend source code. Start at thelame_decoder()function in the.../frontend/lame_main.cfile, it decodes an MP3 file and writes the wave header.
Is it possible to turn off allmacroandpastingerrors (or errors of any types)? ie: ``` error: macro "macro_name" passed 1 arguments, but takes just 0 error: pasting "&" and "0" does not give a valid preprocessing token ``` The reason is that I'm debugging code that has a bunch of these errors (which I haven't fixed y...
No, that's why they're errors instead of warnings; the compiler doesn't know what to do with/how to work around them. You should usually fix errors in the order they come up anyway,especiallythe preprocessor errors you want to turn off, because an error in one part of the code can propagate and cause "errors" in othe...
As we all know that within a network, communication is by the MAC address and not by the ip address. So I always used to think that whether we can write a socket program in server-client paradigm which are only using MAC address for communication but not ip address i.e. the struct sock_in should be left unfilled, and ...
Raw sockets, as given by the example above (by Carl) can work to give you access for L3 header. However, note that on more up-to-date Windows (XP SP3, Vista and 7) raw sockets are greatly restricted by the socket layer, making it difficult to send arbitrary data of your choosing. You can also use special libraries th...
So, given the following: ``` #include <stdio.h> int * getarr(); int main(int argc, char* argv) { int * arr = getarr(); printf("%d", sizeof(arr)); } int* getarr() { static int a[4] = {0,1,0,3}; return a; } ``` How does one find the length ofarr?arr[4] == 0, but so doesarr[0]andarr[2]. If this were a...
You cannot retreive the length of the array when you are in themain()function. This information has been lost when theint[4]was converted to anint *returned bygetarr()
I have a Scheme-like treegraphstructure. I want to parse it using C into some in-memory representation and walk over it. It there any library or front-end of parser to do this? EDIT: I have parsed the following expression ``` true && (false || true) ; true ; false || false ``` into following (This is my scheme-li...
It seems like this is a form ofS-Expression. PerhapsThis S-Expression Parsercan be modified for your needs.
Is it possible to get maximum frame size of each function compiled by GCC? I have a bunch of C and C++ source files in my project and I want to have a statistics of stack usage of each function, just couldn't find any related options in GCC manual.
You can try-fstack-usage. https://gcc.gnu.org/onlinedocs/gnat_ugn/Static-Stack-Usage-Analysis.html There is also-Wstack-usage=<stack_limit>(eg.-Wstack-usage=4096) which will give you a warning as you compile your code.
Is there a way using c to save a retrieved webpage as an opera web document(.mht)? I can retrieve the page and save as html, but is there a way to convert it into this format?
Did you look into theChilkat MHT library?
Say I have four 32-bit numbers, defined so that their bits don't overlap, i.e. ``` unsigned long int num0 = 0xFF000000; unsigned long int num1 = 0x00FF0000; unsigned long int num2 = 0x0000FF00; unsigned long int num3 = 0x000000FF; ``` Where in each number one could have anything in the place of theFFs. Am I right i...
as long as for two numbers num1 and num2 appliesnum1 & num2 == 0, then follows: num1 + num2 == num1 | num2 the reason for this is, that addition is basically a bitwise XOR,pluscarry bit. But as long as there are no carry bits (num1 & num2 == 0) then addition boils down to bitwise XOR, which is (again because ofnum1 ...
I have a problem with the addition of two float numbers. Code below: ``` float a = 30000.0f; float b = 4499722832.0f; printf("%f\n", a+b); ``` Why the output result is 450002816.000000? (The correct one should be 450002832.)
Float are not represented exactly in C - seehttp://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computersandhttp://en.wikipedia.org/wiki/Single_precision, so calculations with float can only give an approximate result. This is especially apparent for larger values, since the possible differ...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do...
Here the list for your particular question C Interfaces and Implementations: Techniques for Creating Reusable SoftwareManaging Projects with GNU MakeActively participate in a notable open source project or three Instead of make can start with cmake or scons.
Inint (*x)[10];xis a pointer to an array of 10ints So why does this code not compile: ``` int arr[3] ; int (*p)[3] =arr; ``` But this works: ``` int arr[3]; int (*p)[3] =&arr; ```
arris an expression that evaluates to anint*(this is the famous 'arrays decay to pointer' feature). &arris an expression that evaluates to aint (*)[3]. Array names 'decay' to pointers to the first element of the array in all expressions except when they are operands to thesizeofor&operators. For those two operation...
As the mutex in most of the systems are implemented using CAS ops, I was wondering about performance comparison of these two constructs. Is it fair to say that if a mutex is implemented using CAS, then the try-lock call on that mutex will be same/similar performance compare to CAS operations ? CAS, being highly syst...
Your reasoning is sound; on any sane implementation, the cost of a "trylock" operation will be roughly the same as a CAS. However, CAS in general cannot be replaced by trylock; trylock is a weaker primitive that can't manipulate arbitrary data.
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...
Look atmsgpack-rpc. It's easy and very simple RPC implementation.
I'm using a pre-built library called 'libdscud-6.02.a', which includes a lot of low level I/O calls for some specific hardware. From this, I created some wrapper functions which I compiled into an object file called 'io.o'. Now, I have a few programs which I'm compiling with these I/O functions and instead of having...
You could do the opposite and add the io.o file to the .a file using ar: ``` ar q libdscud-6.02.a io.o ```
This question already has answers here:Closed12 years ago. Possible Duplicate:Why is FILE all-caps as in FILE*? Why is the standard libraryFILEtype written uppercase ?Is it because of its opaque nature ? Thank you.
If you look at the naming convention used in C, upper case is typically used for preprocessor macros. My guess is that it originally was implemented as a macro expanding to the concrete type used by the library implementation.
my current makefile looks likes this ``` all: hello hello: hello.o clang -o hello hello.o hello.o: hello.c clang -Wall -std=c99 -c -o hello.o hello.c -lpthread clean: rm -f *.o *exe hello ``` How can I modify it to compile with the following: ``` clang -std=gnu99 -Wall -o hello hello.c -lpthread ```
Use ``` hello: hello.c clang -std=gnu99 -Wall -o hello hello.c -lpthread ``` instead of the two rules you have for hello and hello.o now. When your program gets bigger, however, the separation of compilation to object files and linking may at some point be faster than compiling and linking everything in one go....
Is there a portable library to watch for filesystem changes without polling? I know there is inotifyfor Linuxsolution for osxFindFirstChangeNotificationfor WindowsNIO.2for JavaSystem.IO.FileSystemWatcherfor .NET but i have not found any portable wrapper for those. Is there a portable wrapper for Linux, Windows and...
QFileSystemWatcher-- Qt is very cross-platform.
Thedocumentation for GCC's__attribute__((...))syntaxindicates that attributes must be surrounded by double parentheses, but does not give a rationale for this design decision. What practical reason would have caused GCC's designers to require this? Does it have anything to do with the preprocessor's handling of doubl...
To make it easier to eliminate it for different compiler. If you have portable code, you have to remove them for other compilers, so you do ``` #ifndef __GNUC__ #define __attribute__(x) #endif ``` The problem is that attributes have various number of arguments and you can combine multiple attributes in one__attribut...
If I use something likedoubleto hold file sizes in bytes, this will naturally fail very soon, so which data type would I use? Nowadays a couple of TB are common, so I'd like the data type to be able to hold a number that big.
It will depends on you platform. On Unix System, you can probably use theoff_ttype. On Windows, you'll probably want to useLARGE_INTEGER. Those are the types used on those system by the function returning the file size (staton Unix,GetFileSizeon Windows). If you want a portable type,uint64_tshould be large enough.
I need to compile a program in MS-DOS. I have the Borland editor, and I can compile the program usingAlt+F9, but what does it do at the backend? I want to compile it in MS-DOS. I’m trying this: ``` cd c:\tc\bin tcc -o hello.exe hello.c ``` wherehello.cis my file, andhello.exethe file I want to produce. It's not work...
If I remember correctly, Borland/Turbo C compiler's command line options didn't look like gcc options. You should trytcc /?for a command line help.
I have a custom class Manager in Xcode. This class spawns several instances of class Player on a timer, so every tick of the timer it will make a new instance. I would like to pass the instance of Manager to each instance of Player through Players init method: -(id)initWithMngr:(UIImage *)image andManager:(Manager *)...
You should add either#import "Manager.h"or@class Manager;to your file, where interface ofPlayerclass is defined - possibly, "Player.h". (Here I suppose that yourManagerclass interface is defined in "Manager.h" file andPlayer- in "Player.h".) If you will choose variant with@class Manager, don't forget to add#import "M...
Why this code give me a warning says: passing argument 1 of "test" from incompatible pointer type? I know it's about the const before char **, but why? ``` void test(const int ** a) { } int main() { int a=0; int *b=&a; int **c=&b; test(c); return 0; } ```
You can't assign anint **to aconst int **, because if you did so, the latter pointer would allow you to give anint *variable the address of aconst intobject: ``` const int myconst = 10; int *intptr; const int **x = &intptr; /* This is the implicit conversion that isn't allowed */ *x = &myconst; /* All...
The question title might be misleading when read out of context. Let me first explain what I am trying to build. I am building a script which will take 100s of very simple C programs written by my students and check for some very basic properties such as. Have they declared a variable called 'x', is it's type 'int' ...
You can use ANTLR to do this. There is already a C grammar you can use with ANTLR so mainly all you have to do is pass the code into antlr then walk the syntax tree looking for various attributes.... you can use ANTLR from a number of languages. While it might seem daunting at first. It's actually surprisingly ea...
In 3 operations how can I turn a byte into a 32 bit int that matches this: 0x1fffe I can only explicitly access a byte at a time thus I start with 0xFF and then shift it. I can do it using 4 operations but I cant find a way to eliminate one operation. ``` int mask2 = 0xFF << 8; mask2 = mask2 | 0xFE; mask2 ...
Maybe this is what you want... you start withone singlebyte value (0xff), and you work on it with 3bitwiseoperations, obtaining 0x1fffe. ``` int in = 0xff; int out = in<<9 | in<<1; ```
I have a text file with hexadecimal values, after I fscanf a value I need to know how I can convert it from hexadecimal string to an int. And then convert it back to hexadecimal string for a later print. Anyone knows an algorithm for this? thank you.
You should use the%xformat specifier instead of%sto read your values. This will read the data as hexadecimal integers. For example, if your file looks like this: ff3c 5a cb2d Then you can read those 3 values like this: ``` int a, b, c; fscanf(fp, "%x %x %x", &a, &b, &c); // a = 0xff3c, b = 0x5a, c = 0xcb2d ```
I'm developing on an ARM9E processor running Linux. Sometimes my application crashes with the following message : [ 142.410000] Alignment trap: rtspserverd (996) PC=0x4034f61c Instr=0xe591300c Address=0x0000000d FSR 0x001 How can I translate the PC address to actual source code? In other words, how can I make sen...
Withobjdump. Dump your executable, then search for4034f61c:. The-x,--disassemble, and-loptions are particularly useful.
I have searched, but cannot find how (or if) I can step over or continue after a c assert() in xcode 4/ios 5.0. I am using c++ not objective-c. Will I need to define my own assert to achieve this? Thanks~
Asserts aren't normally meant to be ignored. They are there for the programmer to communicate to other programmers that "this should never, ever happen". If you're curious to see what happens if you continue past the assert, comment it out and see how your program behaves after the point where it would normally fail.
Where do i find standard system icons of messageboxes via WinApi? I want to create an advanced dialogbox (with details-extension) as WinApi resource, but I want to use the system default icons like: For .NET I know that i'll find them inSystem.Drawing.SystemIcons, but where do I find them using native C and WinApi?...
You should be able to get them usingLoadIcon. To get the question mark icon useLoadIcon(NULL, IDI_QUESTION), the other identifiers areIDI_ERROR,IDI_WARNINGandIDI_INFORMATION.
I need to compile various different tiny programs. (One program per .c file.) Currently I wrote a simple shell script that finds all the .c files and runs gcc on each of them. Is it possible to run gcc once and feed it the .c files, instead of running and stopping gcc again and again like this shell script does ? ```...
No. You can only compile one program/module at a time.
What does this line exactly mean? It is clear what define is, but I don't understand why is passing the pointer of x at the denominator: ``` #define ArrayLength(x) (sizeof(x)/sizeof(*(x))) ``` thanks
The denominator ``` sizeof(*(x)) ``` is thelength of the first element in the arrayin bytes. The variablexis of an array type, and itdecaysto a pointer, pointing to the start of the array. The asterisk (*) is thedereference operator, so*(x)means"the data pointed to byx". The numerator ``` sizeof(x) ``` applies th...
In C we can make comments in two ways: 1> ``` /* this is one way */ ``` 2> ``` // this is 2nd way ``` What is the difference between the two?Is one better than the other? or do both have same impact and no difference in compiling or processing at any platform? Edit : Especially writing code for embedded
Technically, only the first way is guaranteed to work on all compilers, present and past. In practice, all C compilers implemented since the mid-1980s or so implement both ways, so unless you will be writing for a legacy compiler, you can do whichever way works best for you or your organization.
My teams C-code guidelines write that it'd be better to place a '<' in a comment like shown below: ``` #define MAX_PACK_ITEM_NUM 50 /**< max number of item */ ``` I wonder, what is the real use of this '<' ?
It's a way fordoxygento generate documentation for members of a file/struct/union/class/enum. By using that marker, you can put comments after each member, leading to less clutter. You can read more about ithere.
Let's say I have a 100x100 matrix A, and I want to get another 100x50 matrix B containing only the 50 first columns of A. The easiest method is to use cvGetSubRect, but this doesn't copy the values, it just gives me a header pointing to the data of A and "skips" the columns I don't need, while it is crucial for my app...
UseMat::copyTo()to do a full copy. If necessary (e.g., if the shape is wrong), this will reallocate data for the target matrix. Since the question is actually tagged "c", I will mention for completeness that the C-API copy function iscvCopy().
Imagine this code: ``` int foo() { return foo(); } ``` The compiler can optimize this. Can I force the compiler to use a new stack frame for foo, instead of using the same stack frame (per case, so disabling optimization completely doesn't count)?
Yes, with-fno-optimize-sibling-callsoption.
I am trying to understand thesigsetjmp()andsiglongjmp()functions. The man pages state thatsigsetjmp()saves the context andsiglongjmp()restores the context. My question is, will they take care of stack pointer and program counter values as well? Any links to extra resources are welcome.
The stack pointer and program counter are both parts of the context (which you can think of as being, essentially, the state of the CPU registers).
As the title says: What exactly is a core file and why is it useful? I know when one is generated by UNIX, and I know how to check for one. I'm aware they're useful for debugging... but I'm not entirely sure what it contains so I'm not sure why its useful!
A core file is, essentially, a dump of the memory and registers of the program at the time that it crashed. When viewed in a debugger, you can get information on where the program was at the time of the crash, as well as getting stack traces or viewing the state of heap memory. Basically it lets you do anything you co...
I'm confused about why we need to passvoidinto C functions: ``` int f(void) { return 0; } ``` versus ``` int f() { return 0; } ``` What is the proper thing to do and why?
In C,int f()is an old-style declaration. It says thatfexpects a fixed but unspecified number and type(s) of arguments. For example, givenint f() { return 0; }, the compiler won't complain aboutf(42), orf("hello, world")(though the behavior of such a call is undefined). int f(void)explicitly says thatftakes no argum...
Can anyone explain the implementation/algo that was used in rewind function? or is it possible to implement rewind function using lseek()?
Here's a quote from a reference: A call to rewind is equivalent to:fseek ( stream , 0L , SEEK_SET );except that, unlike fseek, rewind clears the error indicator. http://www.cplusplus.com/reference/clibrary/cstdio/rewind/
I wrote the following macro: ``` #define m[a,b] m.values[m.rows*(a)+(b)] ``` However gcc gives me this error: ``` error: missing whitespace after the macro name ``` What is wrong and how do I fix it?
You cannot use[and]as delimiters for macro arguments; you must use(and). Try this: ``` #define m(a,b) m.values[m.rows*(a)+(b)] ``` But note that defining the name of a macro as the name of an existing variable may be confusing. You should avoid shadowing names like this.
What is the most efficient way to convert an array of unsigned short numbers (16 bits per value) into an array of unsigned ints numbers (32 bits per value)?
Copy it. ``` unsigned short source[]; // … unsigned int target[]; // … unsigned short* const end = source + sizeof source / sizeof source[0]; std::copy(source, end, target); ``` std::copyinternally choses the best copying mechanism for given input types. In this case, however, there’s probably no better way than cop...
I am trying to code up a small operating system and I have 100 processes that need to have unique process IDs generated automatically. they have to be generated sequentially in a round-robin fashion. Is there any algorithm for this? Any help? Thank you.
Just make an array with 100 elements (initialized to 0) and manage that ``` int array[100] = {0}; ``` ``` /* kill process N */ void killprocess(int N) { array[N] = 0; } ``` ``` /* add process N */ void addprocess(int N) { array[N] = 1; } ``` ``` /* find free process starting with N */ int findfreepro...