question
stringlengths
25
894
answer
stringlengths
4
863
I have this code in C: ``` int main(){ char a[10]; _asm{ mov DWORD PTR[a],eax;} ``` This works well, but why do I actually need the ``` DWORD PTR ``` When the DWORD size is already stated by using eax? IAnd for destination, I dont need any size whe I have pointer, right? Thanks.
It is because your code is wrong. Theavariable is an array, not a pointer. Declare it char* and you don't need the override. The code is nonsense of course.
In C: How do you find the number of elements in an array of structs, after sending it to a function? ``` int main(void) { myStruct array[] = { struct1, struct2, struct3, struct4, struct5, struct6 }; printf("%d\n", sizeof(array)); printf("%d\n", sizeof(array[0])); f(array); } void f(myStruct* array) { printf("%d\n", sizeof(array)); printf("%d\n", sizeof(array[0])); } ``` For some reason the printf in main shows different results than the printf in f. My need is to know how many elements are in the array.
You can't. You have to pass the size to the function, eg: ``` void f(myStruct* array, size_t siz); ``` Also notice that infarray is a pointer, while inmainit is an array. Arrays and pointers are different things.
I've thought about this for awhile but what is maybe a good way to go about randomly generating a 2-d or possibly 3-d array. Im not looking for specific code per se, but more just a general idea or way one might think of doing it. edit: Sorry I mistyped, What I meant is say you have an array (2d or 3d) filled with empty space, and I wanted to randomly generate Char *'s in it......randomly(everything else would be blank). is what I meant.
create a 2D/3D arrayFill it with random data?????Profit!
I'm doing asynchronous file I/O under unix using open/close/etc. I have everything working fine and I'm able to initiate background reads and writes and wait for them to finish using a select. I have one issue left, however. I would like to find out how much data is left to read/write.Now I assume this is an easy ioctl call but I can find very little useful documentation on the whole thing :( Anyone who can help would be much appreciated!
If you are doing reads from a standard file, you could use lseek using SEEK_CUR and a value of 0 for the offset to get the current file position, and then lseek to the end to get the end of file position and subtract them. Not sure how you would know how much data is left to write, since you are the one writing it. That would depend on your own code.
How to convert lower case ASCII char into upper case using a bitmask (no -32 allowed)? I'm not asking for solving my homework, only some hints. Thanks
As you state "(no -32 allowed)", I guess you know that the difference between lower case characters and upper case characters is 32. Now convert 32 to its binary representation, there's only one bit set. After that, work out a way to use abit maskto switch the bit.
I want to read a 8 bit grayscale bmp file, reconstruct it's pixel matrix, then process it with sobel operator. However program can not construct pixel matrix, it divides the original pitcure blocks. When I run the program like that;./sobel cube.bmp output.bmp processed.bmp output.txtcube.bmp is the input output.bmp is the output of constructed pixel matrix. proccessed.bmp is the output of processed with sobel operator.Code and Sample photos
possibly not the answer you are looking for but, take a look at openCV. Assuming your interest is in the image processing steps not specifically BMP manipulation, this library takes care of all the file i/o, display etc for you. It also has a good sobel filter.
I have been programming for a while at an intermediate level of course. I have been executing the same code in these different compilers (mostly GCC and MinGW), but I'm unable to make out the difference between these compilers. I mean by what way is the one better than the other? Or what makes them different? Are there some special needs where you might want to use GCC and for others maybe MinGW?
MinGW and GCC are really the same compiler underneath. MinGW is a GCC port for the Windows platform. The reasons why you would use different compilers (as in, based on different front-ends) are: You have a binary-only library that is guaranteed to play nice only if you use particular compilers and those happen to be different compilers for different platformsYou need to target multiple platforms, and there is no compiler that targets all your platformsYou have legacy code that uses particular compiler extensions on different platforms.
I have an integer matrix that should act like a buffer: x = {{0, 0, 0, 0, 0}, {1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}}; Now if I add a new row{3, 3, 3, 3, 3}, the new matrix should look like: x = {{1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}, {3, 3, 3, 3, 3}}; Is there a clever way of doing this without copying all elements around?
If your matrix is defined as anint **and you separately allocate each row, then you would only have to swap the row pointers.
There is a library which I build against different 32-bit platforms. Now, 64-bit architectures must be supported. What are the most general strategies to extend existing 32-bit code to support 64-bit architectures? Should I use #ifdef's or anything else?
The amount of effort involved will depend entirely on how well written the original code is. In the best possible case there will be no effort involved other than re-compiling. In the worst case you will have to spend a lot of time making your code "64 bit clean". Typical problems are: assumptions about sizes of int/long/pointer/etcassigning pointers <=> intsrelying on default argument or function result conversions (i.e. no function prototypes)inappropriate printf/scanf format specifiersassumptions about size/alignment/padding of structs (particularly in regard to file or network I/O, or interfacing with other APIs, etc)inappropriate casts when doing pointer arithmetic with byte offsets
We have a daemon server program which forks one child. When the child exits, Parent is receivingSIGTERMsignal. So, we want to know 1) Who sent thisSIGTERM? 2) Whether theSIGTERMis only for parent or its group? 3) What are the possible waysSIGTERMcan be generated under this scenario? 4) Is it possible to mask thisSIGTERMsignal? If yes what would be the side effect of this call?
You need a sig-handler of type SA_SIGINFO. Then you will get the siginfo_t which contains si_pid which is signalling process.http://linux.die.net/man/2/sigaction
I have a problem with the following code: ``` #include <stdio.h> #include <iostream> int main () { int a, b; printf("Please type in your number a: "); scanf_s("%d", &a); printf("Please type in your number b: "); scanf_s("%d", &b); printf("Solution 1 (divide and modulus): %f\n", a / b + a % b); printf("Solution 2 (cast): %f", (float) a / b); std::cin.get(); std::cin.get(); return 0; } ``` I want my program to read two integers and i want to use two different methods to divide them without round-off errors. Sincerly the first solution does not work. The output are just zeros. I don't know where the problem is.
The result ofa/b + a%bis aninteger(%d), but you are printing out afloat(%f).
I wrote a simple program in C on Linux to delete all the files in a directory except one calledsvnlike this: ``` 1 #include <stdio.h> 2 3 int main() 4 { 5 system("rm !(svn)"); 6 return 0; 7 } ``` But when I compile and run it, the terminal says:sh: Syntax error: "(" unexpected However, when I type and run the command in the terminal directly, all things are done correctly. Any ideas?
The answer is don't usesystem. Use the Linux system calls to list the files in the directory and remove them using unlink(). Something like: ``` DIR* dirHandle = opendir(dirName); struct dirent* dirEntry; while ((dirEntry = readdir(dirHandle)) != NULL) { if (strcmp(dirEntry->d_name, "svn") != 0) { unlink(dirEntry->d_name); } } ``` Warning: all error handling omitted, not compiled and tested, readdir might return.and..which also need to be not deleted.
I searchingminmax heapalgorithm implementation, i remember some things about this structure, her implementation is on one heap. Even levels (floors) in heap tree is a min colored, and rest of nodes is max colored. I remember some draft of workings of this but i searching some good document about it or someCorC++code snippet, i can't find any useful information's by Google, i think is a non widespread algorithm. Greetings and Thanks for helpful answers.
This is the original proposal for MinMaxHeaps: http://www.cs.otago.ac.nz/staffpriv/mike/Papers/MinMaxHeaps/MinMaxHeaps.pdf I've implemented a heap off this and found it to be very simple. An improvement which I've personally never implemented is a min max fine heap: http://arxiv.org/ftp/cs/papers/0007/0007043.pdf
I have a C file generated with f2c (Fortran to C translator) that contains the following C structure: ``` struct { real rez, pi, st; } const_; ``` How can I declare thisconst_variable as an external in another .c file without modifying the one generated by f2c?
In another file. ``` extern struct { real rez, pi, st; } const_; ```
I must run the command "ulimit -n 400" to raise number of allowed open files before I start my program written in C, but is there a way to do the equivalent from within the C program? That is, increase the number of allowed open file descriptors for that process. (I am not interested in per thread limits.) Will it involve setting ulimits, then forking a child which will be allowed to have more open files? Of course, I could write a shell wrapper which runs ulimit, then start my C program, but it feels less elegant. I could also grep through the source code of bash or sh to see how it is done there - maybe I will if I get no answer here. Also related, if you want to select on a lot of file descriptors,look here.
I think that you are looking forsetrlimit(2).
The following code isundefined behavior in C++(although it will work okay on almost any widely used implementation): ``` int* pointer; //uninitialized - likely illegal pointer value pointer++; //incrementing an illegal pointer is UB ``` Is the above code legal in C?
It's undefined behavior in C as well because on certain architectures, loading an invalid pointer into a register triggers a hardware fault. SeeIs storing an invalid pointer automatically undefined behavior?
I need to use a C++ XML parser/writer for implementing virtual registry on the basis of the following 2 conditions. It should not write entries in registryIt should support unicode characters. I have tried the following parsers but none have solved the 2 conditions: Msxml (writes in to registry for COM creation)Xerces (registers COM)Tiny Xml (no entries in reg, but does not support unicode characters)Rapid Xml (no unicode uspport) So please if you could know any which solves my 2 condition, please let me know
Take a look atpugixml.
I'm taking some C++ classes and have send the teacher 9 exercises, each exercise is a simple directory with the name 'ex$' where $ is the number. Each directory has a single source file named 'ex$.cpp. I want to create a makefile that will allow me to type: ``` make ex$ ``` And it will build a executable that corresponds to the compiled source file inside 'ex$' directory. The catch is that I want to do that without creating a target for each exercise(Some kind of 'generic target'). I also need to have an 'all' target that will go into each directory starting with 'ex' and build the executable there. How can I do that?
If all your C++ targets can be built with essentially the same command, you can do this fairly easily. Readthis. Look for$@, in particular. Since this is part of an education, I'll leave the rest vague.
Pretty much the title explains what I try to achieve. Having a set of points in two dimensions, I want to create somehow the curve tha passes from all these points. Whether it will be a graphical window with the mathematical curve or just a jpg produced, is of no importance. Any help? Thx!
First of all, please refrain from tagging questions with C and C++, or using the term C/C++. C and C++ are two distinct, very different languages. That being said, it seems you are looking for a way toplotdata. There are different libraries allowing you to do that, among those are: http://codecutter.org/tools/koolplot/ http://www.gnu.org/software/plotutils/ http://www.mps.mpg.de/dislin/ You can integrate those libraries into your application to produce plots of your data points. There are of course different, additional libraries, but these are the ones that came to my mind first.
I would like to detect underflow when converting string to double in C++ (Visual C++ 2010) usingstrtodfunction. The code below doesn't work as I expect although I did it according tostrtod's documentation: ``` char numStr[] = "123456.122111111123123123123132123123123123123124434345345"; char* pEnd; double d = strtod(numStr, &pEnd); int errorNum = errno; if (errorNum == ERANGE) // this should be true { // underflow occurred } ``` Using the debugger, I found out thaterrorNumis always set to0andERANGEis34. What am I missing?
That value doesn't underflow. It's (much) greater than the smallest normal positive double. Even the last place alone (5*10^-51) is. The smallest normal 64-bit IEEE double is 2^−1022.
I used to use gcc compiler on my unix machine. I am now forced to work on a windows machine. Is there any cool IDE or a simple editor for C with a unix terminal like feel (Black Screen and colored syntaxon it :)) What other editors/IDE are as robust as gcc for windows? Also what is your personal favorite. I would like a try a few of the those before I stick with one. Thanks.
Visual Studio. You can change the fonts & colors however you want. I have been using the same coloring scheme since Borland Turbo C++ back in the 80's -- yellow text on a dark blue background.
From the man page of qsort, in an example of sorting strings: ``` static int cmpstringp(const void *p1, const void *p2) { /* The actual arguments to this function are "pointers to pointers to char", but strcmp(3) arguments are "pointers to char", hence the following cast plus dereference */ return strcmp(* (char * const *) p1, * (char * const *) p2); } ``` Why is it necessary to havechar * const *in the arguments tostrcmp()? Isn'tchar *enough?
strcmpis declared as ``` int strcmp( const char *string1, const char *string2 ); ``` This properly expresses the function's interface contract - which is thatstrcmpwill not modify its input data - and allows the compiler to optimize inside the function (assuming it were not part of the CRT, and likely in assembler already).
Given strings like the following: ``` sdfsd34 sdfdsf1 ``` I would like to extract:34, 1using c++ (STL but no boost), c. thanks
You’re searching for the functionstring.find_last_not_of: ``` string str = "sdfsd34"; size_t last_index = str.find_last_not_of("0123456789"); string result = str.substr(last_index + 1); ```
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 answered with facts and citations.Closed4 years ago.Improve this question I am working on C/C++ on UNIX and have often seen core files. Many times the core files are difficult to debug to find the actual cause of core or the segmentation fault. Could you please suggest me an efficient debugger?
For segmentation faults, memory leaks, uninitialized data and such, running your program throughvalgrindis always a good idea. If you are especially interested in memory leaks, the option "--leak-check=full" pays off. And yes, learn gdb. It takes a little time, but it's worth it.
How can I tell GCC to unroll a particular loop? I have used the CUDA SDK where loops can be unrolled manually using#pragma unroll. Is there a similar feature for gcc? I googled a bit but could not find anything.
GCC 8 has gained a new pragma that allows you to control how loop unrolling is done: #pragma GCC unroll n Quoting from the manual: You can use this pragma to control how many times a loop should be unrolled. It must be placed immediately before a for, while or do loop or a #pragma GCC ivdep, and applies only to the loop that follows. n is an integer constant expression specifying the unrolling factor. The values of 0 and 1 block any unrolling of the loop.
I need to code a Caesar cipher in C, so I'm working step by step to understand everything I'm doing. I need to take care of special chars example : if a user enters "This is a déjà vù !" it will convert this to "This is a deja vu" Is there a C function capable of doing this instead of doing it by hand for each special char in ASCII code ? This is what I'm trying to avoid : ``` case -85 : case -86 : case -87 : case -88 : *p = 'e'; ```
Is there a C function capable of doing this instead of doing it by hand for each special char in ASCII code ? Iconvwill do what you want when you chooseASCII//TRANSLITas the target encoding.
In my program, i need to verify that the parameter passed to the program is an integer, so i created this little function to handle the case where user typed "1st" instead of "1". The problem is that it doesn't work at all. I try the debug and all i can tell you is that the parameters are 12 and the long is 2. (12 is the value i want to test, and 2 is the number of the numbers passed to the function) ``` int intOnly(char *toCheck, int longeur) { int i = 0; while (i < longeur) { switch (toCheck[i]) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case ' ': i++; default: return 0; break; } return 1; } } ``` I hope that everything is clear, Thanks for you help ;)
If you want to check if a character is one of the ten digits, you need to use the character constants'0','1', etc. (not integer constants,0,1, etc.).
I would like to send a .gif file over a serial port connection using C in Linux. I know how to send bytes over the connection and receive them on the other hand, but have no real idea how to do it with a .gif file. How can I send the image byte per byte over the connection and reconstruct it on the other end? Thanks.
Sending a gif is no different than sending any other sequence of bytes. As long as you're not using a file mode that tries to translate carriage returns and/or line feeds like some non-binary connections do, you just read the file in and send the contents, and on the other end read them off the connection and write them to a file.
Let's say I have the following code and output: ``` for (j = 0; j <= i; j++) printf("substring %d is %s\n", j, sub_str[j]); ``` Output: ``` substring 0 is max_n=20 substring 1 is max_m=20 ``` Now I only want to print some substrings. However, if I try to do this conditionally: ``` for (j=0; j <=i; j++) { if (sub_str[j] == "max_n=20") { printf("substring %d is %s\n", j, sub_str[j]); } } ``` I get no output at all. What's wrong with my code?
You can't use==to compare strings in C. You must usestrcmp. ``` for (j=0; j<=i; j++) { if (strcmp(sub_str[j], "max_n=20") == 0) { printf("substring %d is %s\n", j, sub_str[j]); } } ```
Can I use a socket library from TCC? I can't find any reference to winsock or sys/socket.h in the include directory. If i remember correctly, winsock was part of the windows platform SDK (?) If so can I link that with TCC?
According toTinycc-devel mailing list you should give this a try: ``` tiny_impdef winsock.dll -o winsock.def tcc yourcode.c winsock.def -o yourcode.exe ```
I want users to enter 2 digits using c=ReceiveByte() command. For example, I want the user to do the following : ``` Enter 5 Enter 3 Output number 53 in ascii value on screen ( using hyperterminal ) Store number in a single array Use that number for other loops etc. ``` My draft code is : ``` . . int c1[3]; c1[0]=ReceiveByte(); c1[1]=ReceiveByte(); . . for(i=0;i<3;i++) TransmitByte(c1[i]); . . ``` Is this right ? or am I storing the 2 digits incorrectly ? Thanks alot for your help !
For output, you don't need to modify c1[0] and c1[1] since these already contain the characters as entered. As your code stands you just need to make sure that c1[2] contains a valid character, e.g. ``` c1[2] = '\n'; ``` BTW, if you need to get the entered number as an int: ``` int num = (c1[0] - '0') * 10 + (c1[1] - '0'); ```
The RealView ARM C Compilersupportsplacing a variable at a given memory address using the variable attributeat(address): ``` int var __attribute__((at(0x40001000))); var = 4; // changes the memory located at 0x40001000 ``` Does GCC have a similar variable attribute?
I don't know, but you can easily create a workaround like this: ``` int *var = (int*)0x40001000; *var = 4; ``` It's notexactlythe same thing, but in most situations a perfect substitute. It will work with any compiler, not just GCC. If you use GCC, I assume you also useGNU ld(although it is not a certainty, of course) and ld has support for placing variableswherever you want them. I imagine letting the linker do that job is pretty common. Inspired by answer by @rib, I'll add that if the absolute address is for some control register, I'd addvolatileto the pointer definition. If it is just RAM, it doesn't matter.
I want to call a function of the business class after every 2 hours. I m not getting any way to implement same in C/C++ without using a while loop. My problem is that i cannot use while(1) as this does not retun back the control for further execution. Any pointer in this regards wud be helpful....:) thnaks
Boost.AsioprovidesTimers.
I think the question says it all. I want to send signals to a child after the child executes another program, but I am unsure if the child and parent still share signals after the image is destroyed and overlayed. I believe the parent and child still share signals and files, is this true?
Afterexecthe child will still have the same pid and you can send signals to that pid, but any handlers that existed are gone. The child would have to set up explicit handlers itself.
Is there an easier way inCto set an array to one value than using aforloop and going setting each value one by one?
If you're setting the array to all 0's, or if the array is an array of bytes, you can usememset ``` // Set myArray to all 0's memset(myArray, 0, numberOfElementsInMyArray * sizeof(myArray[0])); ``` If you need to set it to something other than 0 in units larger than a byte (e.g. set an array ofints to 1's), then there is no standard function to do that -- you'll have to write your own for loop for that.
I try realloc but it didn't work this is the code. thanks for your help ``` trial = malloc (4 * sizeof(int)); trial[0] = 1; trial[1] = 4;trial[2] = 7;trial[3] = 11; trial = (int*)realloc(trial, sizeof(int) * 5); trial[sizeof(trial)-1] = 23; int a; for(a = 0; a < sizeof(trial); a++){ printf("TRIAL %d \n", trial[a]); } ``` And the output look like this ``` TRIAL 1 TRIAL 4 TRIAL 7 TRIAL 23 ``` It should be ``` TRIAL 1 TRIAL 4 TRIAL 7 TRIAL 11 TRIAL 23 ```
The problem is thatsizeofdoes not tell you how many elements are in the array; it tells you how much space the pointer (which points to the first element) takes up. Sosizeof(trial) == sizeof(int*), and not the number of elements. You need to store the length separately.
Using winAVR for the following code. I got an 8-bit PIN here that I need to OR it with 00000010 or 0x02 to set the 7th bit. Now what I have to do is the following : Set Port B bit 7Wait for 1msClear port B bit 7wait 19ms BUT, I shouldn't change the other bits in these steps. So I have to : Read port BSet bit neededwrite the modified value back to the portClear bitsWrite back to Port B So my test code is : ``` B=PINB|0x02 Loop delay for 1ms BP=PINB&0x00 Loop for 19ms ``` But I think that the other bits are going to be altered in this process, my question is, HOW am I supposed to manipulate one bit of an 8 bit port without changing the other bits ? Thanks alot !!
You needBP=PINB & ~0x02The ~ operator is logical NOT. The and operator keeps only the bitsotherthan 2.
with other IDE, you can pass parameter to the program via the IDE (it save times instead of typing hello.c parameter1 parameter2 in the shell) Is there any way to pass parameters to the program trhough the Xcode IDE instead of just clicking on "RUN" then "CONSOLE" (which provide no arguments to the program) Thanks
Under "Executables" get info on your binary. Go to the "Arguments" tab, and add them there.
Am i right in thinking the only way to create a list which grows during run time in C, is to use a linked list?
You could use a combination of malloc and realloc. To first initialize a C array (malloc) and to grow it (realloc). However, you won't want to grow it by 1 element at a time if you are doing a lot of inserts. It's best to come up with a scheme to make the list grow as you need it (ie add 10 elements each time the list size reaches the allocated size).
I need to write a command line tool that records the boot process information in Linux, and then renders it in a chart format (a textual chart would do). How do I programmatically obtain the this boot process information? Languages that I am allowed to use are C and C++. Thanks in advance. :-)
Doesn't [link text][1] pretty much already do this? Or do you need to write an initlog replacement? I don't know what kind of "chart" you would make from such data, but have a look at gnuplot to help you with that part. edit: I had the wrong tool mentioned originally. [1]:http://linux.about.com/library/cmd/blcmdl1_initlog.htminitlog
I have a data struts like this: ``` category: subcategory: color:red name:pen ``` Is there any better method to store if i want to load such data in memcache? or Is there any other better memory database? Thanks!
You can save what you want in your Memcache, if it's Marshable. Your struts seems to be a Hash so it's really easy to do. You can try something like Redis to store that. Or even all Document oriented Database like MongoDB too.
I want to create a route server to proxy some clients(they may not in the same intranet) to access internet. I need to assign unique ip to the client and get the ip when packets response,so I can do some monitor task. i want to know if I use PPPoE server to deal with this case, how to through NAT ? thanks!
You can't. NAT routes packets in theTransport layer, but PPPoE operates in theData Link layer; NAT can't evenseePPPoE packets.
When you see code like this in C, what's the order of assignment? ``` int i = 0, var1, var2; ``` I don't understand the syntax...
Onlyiis assigned the value zero. var1andvar2are uninitialized.
I'm making a game gui api and I'm wondering how to implement tabs. I'm using freetype for text. When I try to render '\t' It looks like a square. I'm wondering how tabs are implemented because they are not a fixed width. Thanks
For a fixed-width font you could compute how many spaces to the next tab stop, but the general solution is to stop rendering when you hit a tab, move to the next tabstop, and then render the text that comes after the tab character starting from there. Where the tabstops are is up to you, but a good default is probably something like every 8 ems.
You would think this would be readily available, but I'm having a hard time finding a simple library function that will convert a C or C++ string from ISO-8859-1 coding to UTF-8. I'm reading data that is in 8-bit ISO-8859-1 encoding, but need to convert it to a UTF-8 string for use in an SQLite database and eventually an Android app. I found one commercial product, but it's beyond my budget at this time.
If your source encoding willalwaysbe ISO-8859-1, this is trivial. Here's a loop: ``` unsigned char *in, *out; while (*in) if (*in<128) *out++=*in++; else *out++=0xc2+(*in>0xbf), *out++=(*in++&0x3f)+0x80; ``` For safety you need to ensure that the output buffer is twice as large as the input buffer, or else include a size limit and check it in the loop condition.
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.Closed12 years ago. Guide me how to program in "C" to interface a microcontroller with a printer.?? Also explain me the procedure of how actually printing is related to a micro controller.??
Read the data sheet for the microcontroller. It will tell you everything you need to know about the microcontroller. As far as writing the actual device driver, it depends on what OS you're on. If you're on Linux, you can look up subject-matter related to writing Linux Device-Drivers. Without providing any more context, and without telling us what you've tried so far, there is not much we can do to help you.
Just like in the title, what is a contiguous memory block?
This is a contiguous memory block of five bytes, spanning from location 1 to location 5: It represents bytes (colored light blue) that are together in memory with no gap bytes (white) between them. This is a non-contiguous set of five bytes of interest: It is fragmented into three groups of bytes (colored yellow) with gap bytes at locations 4 and 6. Starting at location 1 there is a contiguous block of three bytes, spanning from locations 1 to 3. There are two more blocks of one byte each at locations 5 and 7, respectively. The unused block at location 0 as well as any subsequent blocks beyond location 7 can usually be ignored since they do interpose between the bytes of interest spanning from locations 1 to 7.
``` #include <stdio.h> enum bool { true, false }; typedef bool (*compare_fun) (int, int); ``` I get an error when I enter the above code. How do I make a function pointer that needs to return a boolean?
it should betypedef enum bool (*compare_fun)(int, int);:) Also make sure your implementation doesn't have predefinedbooltrueandfalse Note that in C++ when you define an enum, class or struct, say with name A, then you can declare a variable of type A like ``` A var; ``` or ``` class A var; //or struct A var; or enum A var; ``` in C, only the second syntax is valid. That's why they usually make a typedef. like this ``` typedef enum {true, false} bool; ``` in this case you can use your original syntax : ``` typedef bool (*p) (int, int); ``` HTH.
In windows APIs and various other libraries where I have seen multiple entry points to methods I have noticed the use of the Ex abbreviation in scenarios such as MyApiCall and MyApiCallEx. My assumption is that this stands for Extension or Extra could someone please confirm? Any history on why Ex was chosen rather then MyApiCall2 or similar would also be appreciated.
I was under the impression it stood for extended, as in a more detailed interface for that particular library. For example, CreateFile with 4 parameters is the typical version and CreateFileEx with 17 is the version offering more control and finer detail over how the file is opened, what occurs if it doesn't exist, etc, and is thus extended.
I am creating an event withg_timeout_addorg_timeout_add_secondswhich returns an event id; I can cancel the event by callingg_source_remove. However, at some point what I would like to do is see how much time is remaining until the event is fired. Is there a simple way to do this with the glib api, or do I need to manually store and compare timestamps withg_source_get_current_time?
There is no reasonable way to do this in GLib. The unreasonable way would be to get the GSource (g_main_context_find_source_by_id) and then invoke the source->source_funcs->prepare() operation on the GSource, which would return the time until the source should be dispatched. This is kind of sketchy: source_funcs is private, and prepare() isn't really intended to be used except internally by the main loop. Best I can tell it would work though. I haven't tried it.
I am trying to insert some data into the middle of a file. I have opened the file in append mode as: ``` file = fopen(msg->header.filename, "ab"); ``` I then tried a seek to the desired offset in the file as so: ``` fseek(file, msg->header.offset, SEEK_SET); ``` However, when I then try an fwrite as so: ``` int bytesWritten = fwrite(msg->message, 1, msg->header.length, file); ``` All the data is written to the end of the file instead of in the middle of the file. Is this because I am using append mode? I would open in write mode, but I need to keep the existing contents in the file.
Look at the specification of ANSI C function fopen for "a" (APPEND) mode:Allwrite operations take place at the end of the file. Your fseek will ignored.
From a C program I want to call a shell script with a filename as a parameter. Users can control the filename. The C is something like (initialization/error checking omitted): ``` sprintf(buf, "/bin/sh script.sh \"%s\"", filename); system(buf); ``` The target device is actually an embedded system so I don't need to worry about malicious users. Obviously this would be an attack vector in a web environment. Still, if there is a filename on the system which, for example, contains backquotes in its name, the command will fail because the shell will perform expansion on the name. Is there any to prevent command substitution?
Well, you could always reimplement system() using a call to fork() and then execv(). http://www.opengroup.org/onlinepubs/000095399/functions/system.html
I am playing withlibnetfilter_queueand am looking for a good C library to work with packets captured by libnetfilter_queue. I really like thedpktlibrary for python and some similar library for C would be wonderful. Any other workaround or example code for manipulating the packets are also welcome. with regards, raj
Netfilter's TPROXY target is available (even at *BSD) => setsockopt can be done from your python code without messing at C.
I have a very simple c programme: ``` int main() { return(1); } ``` and a simple Makefile: ``` all: gcc -ansi -pedantic -o tmp tmp.c ./tmp ``` However, when I typemakeI get the following error message: ``` $ make gcc -ansi -pedantic -o tmp tmp.c ./tmp make: *** [all] Error 1 ``` What obvious thing am I missing?
Make exits with an error if any command it executes exits with an error. Since your program is exiting with a code of 1, make sees that as an error, and then returns the same error itself. You can tell make to ignore errors by placing a - at the beginning of the line like this: ``` -./tmp ``` You can see more about error handling in makefileshere.
This question already has answers here:Closed12 years ago. Possible Duplicate:How to printf “unsigned long” in C? I have my number like so... ``` int unsigned long number = 600851475143; ``` I am trying to print it withprintf(). Every time I try, I get a warning by the compiler. I've tried%uld,%ldand Googling hasn't seemed to find me the answer. I'm learning C, but have not had to use along intbefore, so I'm not sure what I should be using. What is the specifier I am chasing?
I recommend using standard order (i.e. unsigned long int).%luis the format tag you're looking for. ``` printf("%lu", 5ul); ```
I wonder what languages are used in robots and electronics. Is it low level languages like Java, C, C++ etc? And if these robots and electronics could be controlled from another place, what protocol is used? It couldn't be HTTP Rest, could it? :)
Ada is also becoming a viable choice for programming language even for smaller platform. Ada has very good support for low-level operations, as well as high-level things. As examples of smaller platforms, Ada is available for the Atmel AVR (8-bit) as AVR-Ada. Seehttp://sourceforge.net/apps/mediawiki/avr-ada/index.php?title=Main_Page For LEGO MindStorms, Ada is available from GNAT as GPL version, which also support the Ravenscar tasking profile. Hence you can easily create multitasking applications on the MindStorms platform. Seehttp://libre.adacore.com/libre/tools/mindstorms/
Why are function arguments pushed on the stack in right to left order?
To enable the existence of functions with a variable number of arguments, like printf. The function can extract the first one or two arguments and then use their values to deduce the total number of arguments on the stack.
I have been spending some time in debugging a programme which gives segmentation fault. The bug is quite indeterministic and intermittent, which is annoying. I narrowed it down to the calling ofstrtok(). I suspect that it is the calling ofstrtok()to split string in two different threads that causes the segmentation fault. Can I callstrtok()in two different threads? Thanks.
strtok()is not reentrant so it should not be used from threaded applications, usestrtok_r()instead.
``` #include <stdio.h> enum bool { true, false }; typedef bool (*compare_fun) (int, int); ``` I get an error when I enter the above code. How do I make a function pointer that needs to return a boolean?
it should betypedef enum bool (*compare_fun)(int, int);:) Also make sure your implementation doesn't have predefinedbooltrueandfalse Note that in C++ when you define an enum, class or struct, say with name A, then you can declare a variable of type A like ``` A var; ``` or ``` class A var; //or struct A var; or enum A var; ``` in C, only the second syntax is valid. That's why they usually make a typedef. like this ``` typedef enum {true, false} bool; ``` in this case you can use your original syntax : ``` typedef bool (*p) (int, int); ``` HTH.
In windows APIs and various other libraries where I have seen multiple entry points to methods I have noticed the use of the Ex abbreviation in scenarios such as MyApiCall and MyApiCallEx. My assumption is that this stands for Extension or Extra could someone please confirm? Any history on why Ex was chosen rather then MyApiCall2 or similar would also be appreciated.
I was under the impression it stood for extended, as in a more detailed interface for that particular library. For example, CreateFile with 4 parameters is the typical version and CreateFileEx with 17 is the version offering more control and finer detail over how the file is opened, what occurs if it doesn't exist, etc, and is thus extended.
I am creating an event withg_timeout_addorg_timeout_add_secondswhich returns an event id; I can cancel the event by callingg_source_remove. However, at some point what I would like to do is see how much time is remaining until the event is fired. Is there a simple way to do this with the glib api, or do I need to manually store and compare timestamps withg_source_get_current_time?
There is no reasonable way to do this in GLib. The unreasonable way would be to get the GSource (g_main_context_find_source_by_id) and then invoke the source->source_funcs->prepare() operation on the GSource, which would return the time until the source should be dispatched. This is kind of sketchy: source_funcs is private, and prepare() isn't really intended to be used except internally by the main loop. Best I can tell it would work though. I haven't tried it.
I am trying to insert some data into the middle of a file. I have opened the file in append mode as: ``` file = fopen(msg->header.filename, "ab"); ``` I then tried a seek to the desired offset in the file as so: ``` fseek(file, msg->header.offset, SEEK_SET); ``` However, when I then try an fwrite as so: ``` int bytesWritten = fwrite(msg->message, 1, msg->header.length, file); ``` All the data is written to the end of the file instead of in the middle of the file. Is this because I am using append mode? I would open in write mode, but I need to keep the existing contents in the file.
Look at the specification of ANSI C function fopen for "a" (APPEND) mode:Allwrite operations take place at the end of the file. Your fseek will ignored.
From a C program I want to call a shell script with a filename as a parameter. Users can control the filename. The C is something like (initialization/error checking omitted): ``` sprintf(buf, "/bin/sh script.sh \"%s\"", filename); system(buf); ``` The target device is actually an embedded system so I don't need to worry about malicious users. Obviously this would be an attack vector in a web environment. Still, if there is a filename on the system which, for example, contains backquotes in its name, the command will fail because the shell will perform expansion on the name. Is there any to prevent command substitution?
Well, you could always reimplement system() using a call to fork() and then execv(). http://www.opengroup.org/onlinepubs/000095399/functions/system.html
I am playing withlibnetfilter_queueand am looking for a good C library to work with packets captured by libnetfilter_queue. I really like thedpktlibrary for python and some similar library for C would be wonderful. Any other workaround or example code for manipulating the packets are also welcome. with regards, raj
Netfilter's TPROXY target is available (even at *BSD) => setsockopt can be done from your python code without messing at C.
I have a very simple c programme: ``` int main() { return(1); } ``` and a simple Makefile: ``` all: gcc -ansi -pedantic -o tmp tmp.c ./tmp ``` However, when I typemakeI get the following error message: ``` $ make gcc -ansi -pedantic -o tmp tmp.c ./tmp make: *** [all] Error 1 ``` What obvious thing am I missing?
Make exits with an error if any command it executes exits with an error. Since your program is exiting with a code of 1, make sees that as an error, and then returns the same error itself. You can tell make to ignore errors by placing a - at the beginning of the line like this: ``` -./tmp ``` You can see more about error handling in makefileshere.
This question already has answers here:Closed12 years ago. Possible Duplicate:How to printf “unsigned long” in C? I have my number like so... ``` int unsigned long number = 600851475143; ``` I am trying to print it withprintf(). Every time I try, I get a warning by the compiler. I've tried%uld,%ldand Googling hasn't seemed to find me the answer. I'm learning C, but have not had to use along intbefore, so I'm not sure what I should be using. What is the specifier I am chasing?
I recommend using standard order (i.e. unsigned long int).%luis the format tag you're looking for. ``` printf("%lu", 5ul); ```
I wonder what languages are used in robots and electronics. Is it low level languages like Java, C, C++ etc? And if these robots and electronics could be controlled from another place, what protocol is used? It couldn't be HTTP Rest, could it? :)
Ada is also becoming a viable choice for programming language even for smaller platform. Ada has very good support for low-level operations, as well as high-level things. As examples of smaller platforms, Ada is available for the Atmel AVR (8-bit) as AVR-Ada. Seehttp://sourceforge.net/apps/mediawiki/avr-ada/index.php?title=Main_Page For LEGO MindStorms, Ada is available from GNAT as GPL version, which also support the Ravenscar tasking profile. Hence you can easily create multitasking applications on the MindStorms platform. Seehttp://libre.adacore.com/libre/tools/mindstorms/
Why are function arguments pushed on the stack in right to left order?
To enable the existence of functions with a variable number of arguments, like printf. The function can extract the first one or two arguments and then use their values to deduce the total number of arguments on the stack.
I have been spending some time in debugging a programme which gives segmentation fault. The bug is quite indeterministic and intermittent, which is annoying. I narrowed it down to the calling ofstrtok(). I suspect that it is the calling ofstrtok()to split string in two different threads that causes the segmentation fault. Can I callstrtok()in two different threads? Thanks.
strtok()is not reentrant so it should not be used from threaded applications, usestrtok_r()instead.
I understand there is aSecureZeroMemoryfunction in C. The function implementation is defined in<WinnNT.h>asRtlSecureZeroMemoryfunction. QNS: How canSecureZeroMemorybe used in Delphi? Did Delphi release a library that contains that function? I'm using Delphi 7.Windows.pasonly hasZeroMemorybut notSecureZeroMemory.
As far as I understand, the only difference betweenZeroMemoryandSecureZeroMemoryisSecureZeroMemoryis implemented as an inline function, ensuring it won't be optimised out by the compiler. I don't think Delphi performs the same level of compiler optimisation, soZeroMemorycalls shouldn't be optimised out.
debugging in MonoDevelop does not work for me. First of all, I have installed MonoDevelop, GNU Debugger plugin and ctags through Ubuntu software center and I'm using Ubuntu 10.10. When I press "Debug" it goes into debug mode but very quickly returns to "normal mode". My simple application contains somescanfso it should wait for input and I have also set a lot of breakpoints. My application works perfectly when I run it without debugging and it debugs fine if I usegdbmanually. Of cause, I've tried rebooting and installing multiple times. Any ideas on what goes wrong? Update:I have checked the MonoDevelop log and it goes like: ``` OnTargetEvent, type - TargetExited ... ``` Thanks, Lasse
I suggest youfile a bug. You might want to check for errors in the MD log (~/.config/MonoDevelop/log) and the debugger output pad. Also, are you using an external console?
scanf("%s",str) won't do it. It will stop reading at the first space. gets(str) doesn't work either when the string is large. Any ideas?
usefgetswith STDIN as the file stream. Then you can specify the amount of data you want to read and where to put it.
H! I have source in C, which is use thesocket(AF_INET, SOCK_STREAM, 0);C method. I use the NDK and make the jni. Everything is fine, but the application don't work correctly; The original C method return 5 in the console. In Android that value is -1. I try to add the C source file the #include < socket.h>, but this is not the solution. Something to add AndroidManifest.xml or the Android.mk? Thanks
I haven't used the NDK so I don't know if this is the same, but for a regular Android project you need to specify the "INTERNET" permission in the manifest, in order to use the sockets.
``` const struct sockaddr FAR* name, ```
It's an old extension from the era of segmented memory architectures. It basically means "this is a pointer that needs to be able to point at any address, not just things in the same segment as the code using it". See more or on thewikipedia page.
This question already has answers here:"static const" vs "#define" vs "enum"(17 answers)Closed7 years ago.The community reviewed whether to reopen this question1 year agoand left it closed:Original close reason(s) were not resolved In many programs a#defineserves the same purpose as a constant. For example. ``` #define FIELD_WIDTH 10 const int fieldWidth = 10; ``` I commonly see the first form preferred over the other, relying on the pre-processor to handle what is basically an application decision. Is there a reason for this tradition?
There is a very solid reason for this:constin C does not mean something is constant. It just means a variable is read-only. In places where the compiler requires a true constant (such as for array sizes for non-VLA arrays), using aconstvariable, such asfieldWidthis just not possible.
i am having trouble with this c language code: ``` char st[2]; printf("enter first value:"); scanf("%c", &st[0]); printf("enter second value:"); scanf("%c", &st[1]); ``` So my computer didn't ask me to enter the second value, I mean to say that it only print the firstprintfstatement then I enter a character and then it only prints the secondprintfstatement and program end without taking the second input. Please help. What's wrong with this code? -Thanks in advance.
Well it did. The character(s) produced by the ENTER key is present in the buffer already.
``` int x,y,m; for(;;){ m=scanf("%d %d",&x,&y); if (m!=2 || m==EOF){ break; } else{ printf("/%d/%d/\n",x,y); } } if (feof ( stdin )){ printf("End of input\n"); }else if(m!=2){ printf("There was an error\n"); } ``` Under linux ctrl+D indicates end of input , and for windows ctrl+z is supposed to do the trick, but it doesn't work. Any ideas?
Try pressing Enter after Ctrl+z If still no luck, please try the C++ version: ``` #include <iostream> int x, y; while ( std::cin >> x >> y ) std::cout << '/' << x << '/' << y << "/\n"; if ( std::cin.eof() ) std::cout << "End of input\n"; else std::cout << "There was an error\n"; ``` and see if it does better?
If I have a structure such as ``` typedef struct _people { char *name; bool *exists; struct _people **citizens; } PEOPLE; ``` How do I go about allocating memory so that people->citizens[0]->name is accessible? I've tried ``` info->citizens = malloc(sizeof(PEOPLE *)*numbPeople); ``` However when I try to access info->citizens->name I get the error message in GDB: ``` Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000008 ```
(I dislike typedefing structs in C for no reason) Let sizeof do the work for you. ``` info->citizens = malloc(numbPeople * sizeof *info->citizens) if (!info->citizens) { /* could not malloc - do something */ } int i; for (i = 0; i < numbPeople; ++i) { info->citizens[i] = malloc(sizeof *info->citizens[i]); if (!info->citizens[i]) { /* could not malloc - do something */ } } ```
I am coming across situations such as this: ``` if(x == NULL) { printf(" The value of X is Null, exiting.."); return -1; } ``` and this "situation" gets repeated many , many times..... laziness aside is there a better way to write this ? Cheers!
Going on your comment to @sbi, yes you can do this with a macro. ``` #define RETURN_MINUS_ONE_IF_NULL(x) \ do \ {\ if (x == NULL) \ { \ printf(#x " is null, exiting\n"); \ return -1; \ } \ } \ while (0) ``` Then you would call this as ``` signed int foo (int *x) { RETURN_MINUS_ONE_IF_NULL(x); /* ... */ } ``` HOWEVER, I would strongly advise against doing this - hiding a return from a function within a macro is very confusing to a casual reader.
There are many good packages for calculating the intersection of polygons. I have found the GPC library useful. I would like to compute intersections of polyhedra (piecewise linear boundaries) in 3D. Are there any good libraries in C/C++ for this?
So far, I've foundCGAL, but I haven't tried it out yet.
I unfortunately have several macros left over from the original version of my library that employed some pretty crazy C. In particular, I have a series of macros that expect certain types to be passed to them.Is it possible to do something along the lines of: ``` static_assert(decltype(retval) == bool); ``` And how? Are there any clever alternatives? Yes I'm aware macros are bad. I'm aware C++ is not C, etc. Update0 Here is somerelated code, and thesource file. Suggestions are welcome. The original question remains the same.
I found this to be the cleanest, using @UncleBenssuggestion: ``` #include <type_traits> static_assert(std::is_same<decltype(retval), bool>::value, "retval must be bool"); ```
I have been told by a professor that you can get a file's last modification time by usingutime.h. However, the man page seem to cite thatutime()only sets this value. How can I look up the last time a file was changed in C on a UNIX system?
This returns the file'smtime, the "time of last data modification". Note thatUnixalso has a conceptctime, the "time of last status change" (see alsoctime, atime, mtime). ``` #include <sys/types.h> #include <sys/stat.h> time_t get_mtime(const char *path) { struct stat statbuf; if (stat(path, &statbuf) == -1) { perror(path); exit(1); } return statbuf.st_mtime; } ```
``` int x; ``` Is this a declaration or a definition? As I write the following code, ``` #include <stdio.h> int main(void) { int x; printf("%p",&x); return 0; } ``` it prints some address. So as memory is allocated,int x;can't be just a declaration. So is it a definition?
From theC standard (n1256): 6.7 Declarations...5 A declaration specifies the interpretation and attributes of a set of identifiers. Adefinitionof an identifier is a declaration for that identifier that:— for an object, causes storage to be reserved for that object;— for a function, includes the function body;101)— for an enumeration constant or typedef name, is the (only) declaration of the identifier. In this case,int x;is a definition (or a defining declaration).
I have a struct with an array as a member, and am trying to set that array using arrow syntax. What I have: ``` typedef float Foo[3]; typedef struct { Foo foo; } Bar; Bar* f() { Bar* bar = malloc(sizeof(Bar)); bar->foo = {1.0, 1.0, 1.0}; return bar; } ``` gcc says: ``` error: expected expression before '{' token ``` on the linebar->foo = {1.0, 1.0, 1.0}; I'm at a loss why this doesn't work. Thanks in advance.
C99 allows it via compound literals: ``` Bar* f() { Bar* bar = malloc(sizeof(Bar)); if (bar) *bar = (Bar){{1.0, 1.0, 1.0}}; return bar; } ``` The “outer” curlies encapsulate the struct as a whole (if the struct had other members, you'd list them in the outer curlies), and the “inner” curlies are for the array.
Can we anyhow change the size of the pointer from 2 bytes so it can occupy more than 2 bytes?
Sure, compile for a 32 (or 64) bit platform :-) The size of pointers is platform specific, it would be 2 bytes only on 16-bit platforms (which have not been widely used for more than a decade - nowadays all mainstream[update](desktop / laptop / server)[/update]platforms are at least 32 bits).
The question is&str[2], if I writestr+2then it would give the address and its logical but where did I used pointer notation in it? Should I prefer writing&(*(str+2))?
You can use either ``` &str[2] ``` or ``` (str + 2) ``` Both of these are equivalent.
I have path to a folder for example /myfolder or in Windows: C:\myfolder and I want to get a list of all files in that folder. How shall I do so in C? Is it different in C++ or C99? How can I get a list of its folders? Any help is appreciated.
In POSIX operating systems, you can call opendir() and readdir(). In Windows you can call _findfirst() and _findnext(). With a little effort you can implement your own opendir() and readdir() as wrapper functions under Windows, so that your application code can use the same API everywhere. An example of that can be foundhere.
I have a char array of text, want to store the alphanumeric lowercase value in a pointer array. ie mystr should point to a char[] of "50sometexthere" ``` char[] myline = " 50 Some Text Here "; char *mystr = (char *)malloc(128 * sizeof(char)); char *tmp = myline; while (*tmp != '\0'){ if (isalnum(*tmp)) strcat(mystr,(char*) tolower(*tmp)); tmp++; } ``` What am I doing wrong?
``` char *myline = " 50 Some Text Here "; char *mystr = (char *)malloc(128); //sizeof char is always 1 char *tmp = myline; char *tmpdest = mystr; while (*tmp != '\0'){ if (isalnum(*tmp)) *tmpdest++ = tolower(*tmp); //this line is changed! tmp++; } *tmpdest = '\0'; ``` HTH
I need to allocate memory for a pointer which needs to be used as a 2d array.I know how to allocate memory for char pointers and int pointers I am confused how memory is allocated of a array of pointers.A pictorial representation of the reason would be very helpful,also is the code below fine? ``` char *names[5]; for(i=0;i<5;i++) { names[i]=(*char)malloc(sizeof(char)); } ```
No, this is not because you are allocating the array assuming a dimension of just 1 element of primitive type char (which is 1 byte). I'm assuming you want to allocate 5 pointers to strings insidenames, but just pointers. You should allocate it according to the size of the pointer multiplied by the number of elements: ``` char **names = malloc(sizeof(char*)*5); ``` You don't need to allocate them one by one with a loop. Note that you need to specify that it is a pointer-of-pointers by using**
what does this sybol means please? "<<" for example: if (1 << var) I want the name of the thing to study. Thank you.
It shifts the bits in the integer 1varpositions to the left. So in effect it calculates 2 to the power ofvar. Seethe article on bit shifts on wikipedia.
Just looking to be pointed in the right direction: Have standard input to a C program, I've taken each line in at a time and storing in a char[]. Now that I have the char[], how do I take the last word (just assuming separated by a space) and then convert to lowercase? I've tried this but it just hangs the program: ``` while (sscanf(line, "%s", word) == 1) printf("%s\n", word); ``` Taken what was suggested and came up with this, is there a more efficient way of doing this? ``` char* last = strrchr(line, ' ')+1; while (*last != '\0'){ *last = tolower(*last); putchar((int)*last); last++; } ```
If I had to do this, I'd probably start withstrrchr. That should get you the beginning of the last word. From there it's a simple matter of walking through characters and converting to lower case. Oh, there is the minor detail that you'd have to delete any trailing space characters first.
I was just doing my first app in C and i have thiswarning(edited) :unused variable pp ``` int compteur = 1; int *p = &compteur; int **pp = &p; ``` I was just trying to makepppointing on the adress of the variablep Forgive me if that's a stupid question, but in my book they don't talk about pointers on pointer. Thanks
That's perfectly legitimate. Your compiler is just informing you that you made a variable, then didn't do anything with it - normally indicating a programming error.
To learn more about a language I rewrite some of the core functions, or compare basic speeds of each set of functions per problem to see what is more suited in real world situations. Other than an ugly online line-graph generator which often only allows one or two series, I cannot find anything that would suit what I need. Do you know of any online service, or better a easy to use framework/graph software I could feed data in for my benchmark results? It can be more complex (I might look into graphvis if it is suitable), but other benchmarks on for example OS's have clean formats, using a script I just cannot find that renders it.
I recomment you to usePChart, there isexampleof graph output.
When I work on C currently, I use Xcode and just pressBuild & Runin the Debugger Console which shows all the program's output. I want to test iterating through command line arguments now. I tried to fake it with... ``` int main() { char *argv[] = {"echo","-n","hello world!"}; int argc = 3; } ``` But trying to iterate throughargvkept giving me an error... error: lvalue required as increment operand When I tried to++argv. So, I'm wondering, how can I give some command line arguments to my program when I run it this way, or do I need to compile and then run it with Terminal? Thanks!
Go toProject -> Edit Active Executableand add your arguments on theArgumentstab.
GTK+ 2.x has the follow states:NORMAL, PRELIGHT, ACTIVE, INSENSITIVE, SELECTEDfor use in GTK themes and I can do things like... ``` bg[NORMAL] = "#f6f6f6" ``` .. to change background color when inNORMALstate. Also, I can change the background image of a button (when the mouse is over it) by changing thePRELIGHTstate image. But I was not able to find a way to change the button background when the user cycle the focus using the TAB arrow (ie. when a dashed rectangle appears around the button). I want to do this using themes in gtkrc, is this possible ?
I don't think so. TheRC file documentationdoesn't even mention "focus", so I don't think it's possible to theme that in this way.
I am working on a C assignment for uni, and I've been coding in TextMate and compiling in the command line. But TextMate wont (or cant) format C code, as it would for say, HTML, Ruby or PHP (using SHIFT + CTRL + F). Is there a plugin or some other tool I can use to fix my indenting and curly braces for .c files?
I useastyle. It has a lot of options to customize according to your coding style, and I think it is included in the major linux distributions.
this is my struct : ``` struct Node { struct Node* data; struct Node* links[4]; } ``` assuming there is no padding, doesNode->links[-1]guaranteed to be pointing onNode::data?
No guarantee; this is undefined behaviour: Compiler-dependent structure paddingStandard only defines array indexing between 0 and length (inclusive)Possible strict-aliasing violation In practice, it's quite possible that you will end up pointing atdata, but any attempts to access it will result in UB.
I read that Left shifte1<<e2is equivalent toe1* 2e2. But for the code: ``` x=5; printf("%d",x<<3); ``` Output is40but according to me it should be30. and forx<<4it is80.(but expected40). Although forx<<1andx<<2outputs are10and20as expected. Please explain this logic.
00000101 = 4 + 1 = 5 00101000 = 32 + 8 = 40 Left shift is not successive multiplication by 2, 4, 6, 8 (i.e. x*2)—it's successive multiplication by 2, 4, 8, 16 (i.e. x^2).
How can you compare against multiple possibilities in one argument? Example: ``` if ((integer == 2) || (integer == 5)) if ((string == "hello") || (string == "dolly)) ``` Would save me a lot of code if you could write that like this: ``` if (integer == (2 || 5)) if (string == ("hello" || "dolly")) ```
First of all string comparasion doesn't work that way in C, I know nothing about objective-c, thought. For the comparison against compile time integral constants, in C you have the switch statement: ``` switch (integer) { case 2: ; case 5: ; /* do stuff here */ } ```
I have a problem regarding static variables. It is said that the life of the static variable is beyond the bounds of the function (if defined in a function). But a pointer to it must give the value if it exits. But it does not work. ``` #include<stdio.h> int *p; int main() { clrscr(); test(); printf("%d",*p); return 0; } void test(void) { static int chacha=0; p=&chacha; } ```
It doesn't look like you declaredpanywhere. Try this intest: ``` int* test(void) { static int chacha = 0; return &chacha; } ``` Now if your main is: ``` int main() { int *p; clrscr(); p = test(); printf("%d",*p); getch(); return 0; } ``` you'll see the behavior you expect.