question
stringlengths
25
894
answer
stringlengths
4
863
satuation is ..... i've stored many mac addresses (one by one) in the buffer(*buff[]), now i want to extract the MAC addresses one by one and write it to a FILE seperated by COMMA in c. HELP!!! THNXXX!!
If they're strings, you can just use something like: ``` FILE *fout = fopen ("output.txt", "w"); if (fout != NULL) { char *sep = ""; for (int i = 0; i < sizeof (buff) / sizeof(*buff); i++) { fprintf (fout, "%s%s", sep, buff[i]); sep = ","; } fclose (fout); } ``` If they'renotstrings, you should probably specify the data in greater detail. In any case, the logic is the same, the only thing that will change is the way in which you output the MAC address. And if the array isn't full, then make sure you use a count variable to control the loop rather than the array size.
If a char array needs to be declared before it is used, how does one declare one so that is can be used to store input? e.g. The user enters a sentence or series of words. How is this stored so that it can be manipulated? What is the correct way rather than just declaring an array which is large enough to handle expected input?
If you are talking aboutconsole input, you have no choice but to have a FIXED SIZE buffer and use asecurefunction not allowing more thanFIXED_SIZEto be stored on your buffer. An example would be: ``` char buff[1024]; fgets(buff, 1024, stdin); // to read from standard input ``` You must warn your user that any characters beyond 1023th will be ignored. If you want to access last character the user entered: ``` printf("%c", buff[strlen(buff)-1]); ```
I have a file with some of user1's data. I want to use the same file for user2 by clearing the content of the file. My idea is that when a new user comes, data of the previous user should be clear and the same file should be ready for the new user.
As @stefan said usingfopen()with "w" mode will do the job for you. When you open a file with "w" flag it creates an empty file for writing. If a file with the same name already exists its contents are erased and the file is treated as an empty new file. If the file is already open you can usefreopen()function from stdio.h with "w" mode as it will first close the file and then reopen it for writing erasing whatever was in the file previously.
This question already has answers here:Closed12 years ago. Possible Duplicate:Code convert from C++ to C Two months ago, my instructor have asked one question, I have searched to looking for answer but I could not find it. question : ``` From c++ code, how can one generate c code just using console ( with g++ ) . ``` How can I do this ?
g++ compiles C++ directly to machine code, it does not first compile to C then compile that. There may be some compilers that compile to C code first. I do not know of any if you really need the code. It is not the most efficient way to do it though. I think that is what your instructor was trying to ask you, i.e. if there is a compiler switch to generate C code. Is there any particular reason why you need to generate C code. Creating a C interface can be useful and there are ways to do this.
I worked with numbers ( int, float, double, long, unsigned ), but when I put other character to console ( such as^[[A, or*). Therefore, my program is crashing How can I protect my program from this erroneous input ? Note : I know some library function namelyisdigitorisallnum, but they don't help so much
The way to do this in C as well as C++, is to read all inputs as strings, then parse the string. This is one reason why you should never use scanf("%d") or cin>>integer for any other purposes than debugging / student / hobbyist programs.
I want after I do some calculation create an array inCwould u please help me? ``` int len_arr = (sizeof inputs)/(sizeof inputs[0]); int half_arr = len_arr / 2; if(len_arr%2 != 0) half_arr++; int m[half_arr][half_arr]; ```
I'm assuming you wish to create a matrix with row/column size ofhalf_arr. ``` int i; int len_arr = (sizeof inputs)/(sizeof inputs[0]); int half_arr = len_arr / 2; if(len_arr%2 != 0) half_arr++; int **m = malloc(half_arr * sizeof(int)); for (i = 0; i < half_arr; i++) *m = malloc(half_arr * sizeof(int)); ``` You should then be able to accessmusingm[row][column]orm[column][row].
While coding very simple program for removing blanks, tabs, newlines I came across something I don't actually catch on first; even thoughifcondition is true only when tab, space or newline doesn't exist it's still executed with the mentioned for some reason.. here is the code ``` #include <cstdio>#include <cstring> ``` ``` #include <stdio.h> #include <string.h> #define LGT 100 void rem(char s[]) { int i; for(i=(strlen(s)-1);i>=0;i--) if(s[i]!=' ' || s[i]!='\t' || s[i]!='\n') break; s[i+1]='\0'; } int main(void) { char v[LGT]={"sdsfg\t"}; rem(v); printf("%s\n",v); getchar(); } ```
s[i]!=' ' || s[i]!='\t' || s[i]!='\n'isalwaystrue. A character can't be equal to both a space, a tab and a newline.
I find myself needing a hash table container in a C project which includes Lua. I am wondering if it is possible to use the hash table in Lua as a generic container. I have looked atltable.hand all of the functions require a Lua state and seem tied to the Lua environment so I am guessing this is not practical if the data needs to be independent of Lua.
It is possible and the easiest way is just to use the official C API for Lua. No need to dig into the innards of ltable.h.
It seems that some autoconf projects use aconfigure.infile to generate aconfigurescript, and some useconfigure.ac. What is the difference/advantage between using one or the other?
Its just a matter of style. Historically autoconf files were namedconfigure.in. Nowconfigure.acis the preferred naming scheme. Its also discussed in thedocumentation.
I'm trying to format a number that has a value from 0 to 9,999. I would like the 2 most significant digits to always display, i.e. 5000 -> 500000 -> 00 If either of the least significant digits are non-zero they should be displayed, i.e. 150 -> 015101 -> 0101 It can be done with some hackery, but can C's printf do this directly?
Yes you can useprintffor this ``` int v = 5000; if ((v % 100) != 0) printf("%04d", v); else printf("%02d", v/100); ```
Can Instruments be used as a replacement for valgrind If one wants to check for memory leaks using instruments can it be used from the terminal?
Instruments has a command line interface: ``` $ instruments -h ``` Example usage: ``` $ instruments -t mytemplate -a myapp.app ``` For leaks, try theLeaks.tracetemplate. To see all available templates, use-s. There is another executable, just calledleaks. You can inspect any running application by givingleaksits PID: ``` $ echo $$ 620 $ leaks 620 leaks Report Version: 2.0 Process: bash [620] Path: /bin/bash Load Address: 0x100000000 ... Process 620: 37983 nodes malloced for 1123 KB Process 620: 0 leaks for 0 total leaked bytes. ``` Read more about leaks in the Apple developerreference library.
Anyone please tell me where the main() function of the 'C' language returns its value?
C'smainfunction returns an int... that int goes to the program which executed it (the parent process, if you will) as an exit status code. Specifically, on most operating systems, a 0 exit code signifies a normal run (no real errors), and non-zero means there was a problem and the program had to exit abnormally.
Working on a project that sends multicast data packets, and the receivers can opt in/out of the group as necessary. I noticed there are two ways of joining/leaving the groups: IP_ADD_MEMBERSHIP/IP_DROP_MEMBERSHIP and IP_ADD_SOURCE_MEMBERSHIP/IP_DROP_SOURCE_MEMBERSHIP. Couldn't get anything out the man pages here, so throwing this one out to the SO gurus. What's the difference, if any, and can you give an example of when to use one instead of the other?
IP_ADD_SOURCE_MEMBERSHIP and IP_DROP_SOURCE_MEMBERSHIP are for SSM (source specific multicast) support.
satuation is ..... i've stored many mac addresses (one by one) in the buffer(*buff[]), now i want to extract the MAC addresses one by one and write it to a FILE seperated by COMMA in c. HELP!!! THNXXX!!
If they're strings, you can just use something like: ``` FILE *fout = fopen ("output.txt", "w"); if (fout != NULL) { char *sep = ""; for (int i = 0; i < sizeof (buff) / sizeof(*buff); i++) { fprintf (fout, "%s%s", sep, buff[i]); sep = ","; } fclose (fout); } ``` If they'renotstrings, you should probably specify the data in greater detail. In any case, the logic is the same, the only thing that will change is the way in which you output the MAC address. And if the array isn't full, then make sure you use a count variable to control the loop rather than the array size.
If a char array needs to be declared before it is used, how does one declare one so that is can be used to store input? e.g. The user enters a sentence or series of words. How is this stored so that it can be manipulated? What is the correct way rather than just declaring an array which is large enough to handle expected input?
If you are talking aboutconsole input, you have no choice but to have a FIXED SIZE buffer and use asecurefunction not allowing more thanFIXED_SIZEto be stored on your buffer. An example would be: ``` char buff[1024]; fgets(buff, 1024, stdin); // to read from standard input ``` You must warn your user that any characters beyond 1023th will be ignored. If you want to access last character the user entered: ``` printf("%c", buff[strlen(buff)-1]); ```
I have a file with some of user1's data. I want to use the same file for user2 by clearing the content of the file. My idea is that when a new user comes, data of the previous user should be clear and the same file should be ready for the new user.
As @stefan said usingfopen()with "w" mode will do the job for you. When you open a file with "w" flag it creates an empty file for writing. If a file with the same name already exists its contents are erased and the file is treated as an empty new file. If the file is already open you can usefreopen()function from stdio.h with "w" mode as it will first close the file and then reopen it for writing erasing whatever was in the file previously.
This question already has answers here:Closed12 years ago. Possible Duplicate:Code convert from C++ to C Two months ago, my instructor have asked one question, I have searched to looking for answer but I could not find it. question : ``` From c++ code, how can one generate c code just using console ( with g++ ) . ``` How can I do this ?
g++ compiles C++ directly to machine code, it does not first compile to C then compile that. There may be some compilers that compile to C code first. I do not know of any if you really need the code. It is not the most efficient way to do it though. I think that is what your instructor was trying to ask you, i.e. if there is a compiler switch to generate C code. Is there any particular reason why you need to generate C code. Creating a C interface can be useful and there are ways to do this.
I worked with numbers ( int, float, double, long, unsigned ), but when I put other character to console ( such as^[[A, or*). Therefore, my program is crashing How can I protect my program from this erroneous input ? Note : I know some library function namelyisdigitorisallnum, but they don't help so much
The way to do this in C as well as C++, is to read all inputs as strings, then parse the string. This is one reason why you should never use scanf("%d") or cin>>integer for any other purposes than debugging / student / hobbyist programs.
Please give me a sample C program to produce the euro sysmbol. I'm using windows keyboard and program needs to be compiled in linux. Update: Actually I need Euro symbol as a string and need to concatenate it with amount string. I'm having Dell Latitude D620 laptop and tried using Alt+4, Alt+5, etc.. None of them prints the euro sysmbol.
This is entirely character encoding specific. This question should sum up why there is no straight answer to your question: Hex representation of Euro Symbol €
Is there an easy way, on *nix platforms(Linux specifically) to get the IP address of a hostname, while supplying a custom DNS server to use in place of the system's configured one? I want to access this information from a C program.
You will need to use your own resolver, directly sending DNS packets, instead of relying on the system's resolver andgethostbyname. You would probably want to use a library, such asadns.
Is this: ``` *(1 + &foo) ``` the same as this? ``` *(&foo + 1) ``` '+' and '&' have the same precedence and they are evaluated right-to-left. However you can't interpret the second case like this: ``` *(&(foo + 1)) ``` ...because you can only use '&' with an l-value (it won't even compile if you write it like that). So will it be garbage? Or will it safely figure out what you meant?
Yes, they are equivalent (the third one obviously is not). Theunary&operator has higher precedence than thebinary+operator (as all unary operators do), so&foo + 1parses as(&foo) + 1. What you are thinking of when you say they have the same precedence is theunary+operator (which is a different operator)has the same precedence asunary&.
``` int x = 0; x^=x || x++ || ++x; ``` and the answer for x at last is 3. How to analysis this expression? little confused about this. Thanks a lot.
This is undefined behaviour. The result could be anything. This is because there is nosequence pointbetween the++xand thex ^=, so there is no guarantee which will be "done" first.
So being new to the C language i want to program a simple window or GUI. are there any good web pages or books i could get to learn how to do this? I've searched around on the net and haven't come up with anything! or if someone could send me on the right track like what to #include and maybe some important commands that i will need that would be awesome! thanks!
Check outGTK. You didn't say what OS you are using. GTK is cross platform, but easiest to use on Linux.
I need a C function which returns the final length of a formatted string so I can properly allocate the target string, rather than calculate the length myself. There issnprintfwhich does just this upon inability to write the entire string, but unfortunately there is no wide char alternative for it. swprintfreturns -1 in case of error, not the needed length (why not the same behaviour ?!?) The title mentionedasprintfseems to be of no help also, as it provides a non-wide version only. _vscwprintfcan be used on windows, but I need a crossplatform, standard version, or at least a Linux version and I'll #ifdef the code. Any ideas? Thanks!
POSIX 2008 added theopen_wmemstreamfunction which, along withvfwprintf, does exactly what you need. It was formerly a GNU extension, so it's been available on GNU systems for a long time. This can easily be used to construct aawprintfwrapper.
I was wondering if it was possible to read the keyboards input, on OSx from somewhere, such as GNU/Linux with the /dev/input files. The purpose of this is to make a very simple keylogger, (learning purpose), or if there is a function that i could call in C. Thanks.
Since not all readers have good intentions as you, I won't get into details, but rather point you to the right direction. As you may know, the WindowServer works over two environments: Carbon (old) and Cocoa (new). These are the respective APIs: Carbon →InstallEventHandler(link is broken due to age? Anyway, the referenced book isLearning Carbon, Chapter 6 - Carbon Events)Cocoa →addGlobalMonitorForEventsMatchingMask
``` file * fp = fopen() file * fd = ???? ``` I want to use*fdto write file which*fpopened before. How can I do it? Add some, the key of this question is use another pointer to do it. See, *fd is the different pointer. Wish i made this clear.
``` file* fd = fp; ``` If I understand you correctly, of course.
I have a program that executes various shell commands viasystem()and occasionally prints tocout. I want to redirect all output coming fromsystem()calls to a log file so they don't clutter up the normal output. Can I do this without having to append> logto all my system commands?
Looks like you can usepopen
This question already has answers here:Closed12 years ago. Possible Duplicate:Best algorithm to count the number of set bits in a 32-bit integer? Hello, Is there a more compact way of counting the number of ones in a byte without using a loop? I don't want to do the following if I don't have to. Thanks. ``` char myValue = 0x0F; int counter = 0; while (myValue > 0) { if (myValue & 0x01) { counter ++; } myValue = myValue >> 1; } ```
``` ((i>>3)&1)+((i>>2)&1)+((i>>1)&1)+(i&1) ``` Or use assembly (SSE/MMX).http://gurmeet.net/puzzles/fast-bit-counting-routines/
How can I modify/rotate an axis angle from world coords to object coords? See below: ``` void RotateMatrix4(float *m, float angle, float *axis); //This function rotates a matrix in object space void RotateLocal(float angle, float *axis) { RotateMatrix4(m, angle, axis) } void RotateGlobal(float angle, float *axis) { //Do something to axis here RotateMatrix4(m, angle, axis) } ```
You found the answer yourself - that is simply a multiplication between a tranformation matrix and a vector - you are simply transforming the axis vector into object coords. Look atTransformation Matrixfor more information on Transformation matrices. (I would comment on your answer - but my rank is not yet high enough...)
This question already has answers here:Closed12 years ago. Possible Duplicate:Difference between 'global' and 'static global' What is the difference between statements 1 and 2 :- ``` #include <stdio.h> //In the global declaration area static int a; // 1. int b; // 2. ``` Thanks for help.
Astaticglobal variable is local to thetranslation unitit is defined in. So, if you definestatic int a;in two different translation units, this will create two independent variables. If you define a non-static global variableint b;in two translation units, you will experience a linker error (but you can useextern int b;in one of the two translation units to tell the linker that it should use the global variable from the other translation unit).
Compare the two: ``` if (strstr(a, "earth")) // A1 return x; if (strstr(a, "ear")) // A2 return y; ``` and ``` if (strstr(a, "earth")) // B1 return x; else if (strstr(a, "ear")) // B2 return y; ``` Personally, I feel thatelseis redundant and prevent CPU from branch prediction. In the first one, when executing A1, it's possible to pre-decode A2. And in the second one, it will not interpret B2 until B1 is evaluated to false. I found a lot of (maybe most of?) sources using the latter form. Though, the latter form looks better to understand, because it's not so obviously that it will callreturn yonly ifa =~ /ear(?!th)/without the else clause.
Your compiler probably knows that both these examples mean exactly the same thing. CPU branch prediction doesn't come into it. I usually would choose the first option for symmetry.
i want to do some modification and development for VLC. i download its source code, vlc-1.1.5. and it is written by C. so usually which development environment should i use, xcode or some others? thx...
I thought VLC was developed inQt. Do you see the class names starting with Q? In case it is developed in Qt,Qt CreatororKDevelopwould be a good choice of development environment.
I have one IP packet, which includes IGMP packet. I want to simulate this using RAW socket programming. the checksum field of IP packet is e1c9, now how to assign this value in programming. I tried iphdr->iph_chksum="e1c9"; also iphdr->iph_chksum=57801; is the above thing right? it is not working properly, please tell me the exact way?
The C syntax for hexadecimal values is0xe1c9in this case. you should however ensure that you are using the correct byte order, you will probably need to pass the value throughhtons
im trying to read newline terminated strings using windows api and saw that the serialport class has a serialport.newline member. i want to know if it is possible to use the serialport class in c and how
In (Microsoft) C, you'd need to callCreateFileto get a handle to the serial port, and_open_osfhandle(handle, _O_TEXT)to convert it to a file descriptor. You can get aFILE*from that file descriptor with_fdopen. After that,fscanfwill read lines.
``` error: expected ‘)’ before ‘[’ token error line is - void display(ptr[i]); ``` this is the error which i get after compilation, what does it mean, i have written a simple program in C
I can only imagine you are missing a ')' on the line above that line. But more source code would help in identifying the problem.
I need some fast, thread safe memory pooling library. I've googled a lot, but fast solutions don't have thread safety, while others are really big. Any suggestions?
Both nedmalloc and ptmalloc are C based thread caching memory managers, based around doug lea's malloc(the core of most linux allocators). They are both under good licences as well, unlike hoard, which requires payment for commercial use, last I looked. Googles tcmalloc also has C bindings iirc, and is built from the ground up as a thread caching allocator, as well as some built in heap and cpu profiling tools, it is however build for massive memory usage(the example they give is 300mb+ per thread), and as such many not work as well as expected for smaller scale apps
Does anyone know what the weakest family of widely-used parsing algorithms is that can parse C code? That is, is the C grammar LL(1), LR(0), LALR(1), etc.? I'm curious because as a side project I'm interested in writing a parser generator for one of these families and would like to ultimately be able to parse C code for another side project.
It seems thatBison uses an LALR(1)parser. LALR parsers are more robust than LL parsers, but are also more complex. From this I suspect that LALR(1) is probably the weakest parsing algorithm which can parse C code. Unless you're really set on rolling your own recognizer.ANTLRwould probably be your best bet to do this. ANTLR uses an LL* algorithm (which is, effectively, LALR).
``` #include <stdio.h> int main(void) { long long x = test(); printf("%lld\n", x); return 1; } long long test() { return 1111111111111111111; } ``` The output is 734294471 . If I replace the call totest()by a the number, the output is as I expect. I checked the value of x using a debugger and it wasn't set the to value returned by the function. What is going wrong? I am using Visual Studio 2010 with the Visual C++ compiler.
You need to declaretestbefore you call it, otherwise C assumes it returnsint.
I have to use C and Fortran together to do some simulations. In their course I use the same memory in both programming language parts, by defining a pointer in C to access memory allocated by Fortran. The datatype of the problematic variable is ``` real(kind=8) ``` for Fortran, and ``` double ``` for C. The results of the same calculations now differ in the respective programming languages, and I need to directly compare them and get a zero. All calculations are done only with the above accuracies. The difference is always in the 13-14th digit. What would be a good way to resolve this? Any compiler-flags? Just cut-off after some digits? Many thanks!
Floating point is not perfectly accurate. Ever.Evencos(x) == cos(y)can be false ifx == y. So when doing your comparisons, take this into account, and allow the values to differ by some small epsilon value.
``` #include <stdio.h> #include <limits.h> int main(void){ printf("Type Size Min Max\n----------------------------------------------------------------------\n"); printf("%-20s%-10d%-20ld%-20ld\n", "long", sizeof(long), LONG_MIN, LONG_MAX); printf("%-20s%-10d%-20lu%-20lu\n", "unsigned long", sizeof(long), 0, ULONG_MAX); return 0; } ``` wheredouble? i.e. variableLONG_MINbe in filelimits.h. in which type double? ``` int i, min, max; for (i = 1.0; i > 0; ++i) { max = i; }; min = i; printf ("int: min: %d max: %d \n", min, max); ``` How to do that for float and double? How is min calculated for this variable? sorry bad english
The limits for floating point types are defined infloat.hnot limits.h
In the following piece of code, to calculate strlen, ``` int s(const char* str) { int count=0; while(*str++) count++; return count; } ``` You can see that the argument str is const. But, the compiler does not complain when I do a str++. My question is When passing pointers as arguments to a C function, if is is qualified with const, How can I still perform pointer arithmetic on it? What is const in the above function?
``` const char* str; ``` means a non-const pointer to a const data. ``` char* const str; ``` means a const pointer to a non-const data. ``` const char* const str; ``` means a const pointer to a const data. The reason for this is that in C++ the variable type declarations are parsed from right to left, which results in that the word "const" always defines the constness of the thing that it's closest to.
I am trying to learn the fundamentals of C, but I cannot figure out why this code doesn't work. The while loop in reverse() causes a bus error. I found almost identical code in a programming interview book as a valid solution, but neither this nor other similar methods I have seen posted here work for me without a bus error. ``` #include <stdio.h> void reverse(char* str) { char* end = str; char tmp = 0; if(str) { while(*end) { end++; } --end; while(end>str) { tmp = *end; *end-- = *str; *str++ = tmp; } } } int main() { char* a = "12"; puts(a); reverse(a); puts(a); return 0; } ```
The problem is that you're trying to reverse a constant literal string, which is read only. Change the declaration ofainmaintochar a[] = "12";to make it a writable char array instead
I have a problem, I'm working on a C++ project (I'm using Eclipse as my IDE). Now I want to make use of a C/C++ library, for example libcurl, so I download curl and don't know what to do next. Must I only include the .h and .c files I need or must I compile it before?
A typical way to use a library (this, of course might differ from library to library) is to include all of the header files from the library, include them as needed, use functions that they provide. Then, when building the application, link the objects with the library object (.a, .lib, whatever the extension). If you don't have the .a or .lib file, then you should build that independently
I'm trying to write a program in functional style with C as much as possible. I know fine compilers like GCC/Clang do tail call optimization silently, but it's not guaranteed. Is there any option to force tail call optimization on the compilers? (Of course when only it's called at the end of itself)
Clang 13 "musttail" attribute to force tail call optimization in tail recursive functions even if optimizations are disabled. https://clang.llvm.org/docs/AttributeReference.html#musttail usage: ``` int f(int x) { ... __attribute__((musttail)) return f(x-1); } ```
I understand there is no sequence point here before the semicolon, but is there a plausible explanation for the dereferenced pointer to use the old value 2 in the expression? Or can it be simply put down as undefined behaviour? ``` int i=2; int *x=&i; *x+=*x+=i+=7; ``` Result: ``` i= 13 ```
It is "simply" undefined behavior. That said, the compiler probably emits code that reads the value ofionce then performs all the arithmetic, then stores the new value ofi. The obvious way to find out the real explanation would be to go look at the assembly generated by the compiler.
I'm trying to write a number to two decimal places usingprintf()as follows: ``` #include <cstdio> int main() { printf("When this number: %d is assigned to 2 dp, it will be: 2%f ", 94.9456, 94.9456); return 0; } ``` When I run the program, I get the following output: ``` # ./printf When this number: -1243822529 is assigned to 2 db, it will be: 2-0.000000 ``` Why is that? Thanks.
What you want is%.2f, not2%f. Also, you might want to replace your%dwith a%f;) ``` #include <cstdio> int main() { printf("When this number: %f is assigned to 2 dp, it will be: %.2f ", 94.9456, 94.9456); return 0; } ``` This will output: When this number: 94.945600 is assigned to 2 dp, it will be: 94.95 See here for a full description of the printf formatting options:printf
What are the differences between usingscanfwith the following format specifiers, when the input being scanned is123456versus when it's123: %6d%-6d%0d What are the differences in the output?
I ended up just trying it with GCC 4.3.4, and got the following: %6d: Works fine; only reads 6 characters (so if you try to read123456789it will only read123456)%-6d: Emits the warning:warning: unknown conversion type character '-' in formatDoesn't read anything, and the int being written to is unmodified%0d: Emits the warning:warning: zero width in scanf formatReads as though there were no width in the format specifier (%d) I haven't checked the spec to see if those results are mandated or just how GCC handles it (EDIT:AndreyT found it)
for example: ``` void f(void *p) { p = malloc(1); printf("%i\n", p); } void main(int argc, char *argv[]) { void *p = malloc(1); printf("%i\n", p); f(p); printf("%i\n", p); } ``` would produce something like this: ``` 5513696 5513728 5513696 ``` Why passing by address and allocating wouldn't change pointer address? p.s. where can be something like realloc (maybe even recursive realloc by recusrive function call)
When you pass a pointer to a function you are copying by value, hence you are assigning a different pointer, which until you malloced, pointed to the same place as the original.
I have an unsigned char array with 2 elements that represents a signed integer. How can I convert these 2 bytes into a signed integer? Edit: The unsigned char array is in little endian
For maximum safety, use ``` int i = *(signed char *)(&c[0]); i *= 1 << CHAR_BIT; i |= c[1]; ``` for big endian. Swapc[0]andc[1]for little endian. (Explanation: we interpret the byte atc[0]as asigned char, then arithmetically left shift it in a portable way, then add inc[1].)
I am looking for a comprehensive record of secure coding practices in C. Since i haven't found such a list existing here already we might as well make this into a community wiki, for further reference. I am looking for solutions to security issues like stack and heap based buffer overflows and underflows, integer overflows and underflows, format string attacks, null pointer dereferencing, heap/memory inspection attacks, etc.. NB: Besides coding practices, secure libraries that defend against these kind of attacks are worth mentioning too. LE: As seen in this questionSecure C++ coding practicesbut for C only.
The CERT C "de facto" standard is fairly well-known and addresses these issues at some extent: SEI CERT C Coding Standard There should be several static analyzers on the market that supports CERT C.
I have read in a lot of places but I really can't understand the specified behavior in conditionals. I understand that in assignments it evaluates the first operand, discards the result, then evaluates the second operand. But for this code, what it supposed to do? ``` CPartFile* partfile = (CPartFile*)lParam; ASSERT( partfile != NULL ); bool bDeleted = false; if (partfile,bDeleted) partfile->PerformFileCompleteEnd(wParam); ``` The partfile in the IF was an unnecessary argument, or it have any meaning?
In this case, it is an unnecessary expression, and can be deleted without changing the meaning of the code.
``` typedef struct { int hour; int min; int sec; } counter_t; ``` And in the code, I'd like to initialize instances of this struct without explicitly initializing each member variable. That is, I'd like to do something like: ``` counter_t counter; counter = {10,30,47}; //doesn't work ``` for 10:30:47 rather than ``` counter.hour = 10; counter.min = 30; counter.sec = 47; ``` Don't recall syntax for this, and didn't immediately find a way to do this from Googling. Thanks!
Initialization: ``` counter_t c = {10, 30, 47}; ``` Assignment: ``` c = (counter_t){10, 30, 48}; ``` The latter is called a "compound literal".
Is there any way to check the granularity of gettimeofday() function provided by POSIX?
Instead ofgettimeofday(), consider usingclock_gettime()(specifying theCLOCK_REALTIMEclock). This is also POSIX, and supports aclock_getres()function to obtain the resolution.
``` typedef struct { int hour; int min; int sec; } counter_t; ``` And in the code, I'd like to initialize instances of this struct without explicitly initializing each member variable. That is, I'd like to do something like: ``` counter_t counter; counter = {10,30,47}; //doesn't work ``` for 10:30:47 rather than ``` counter.hour = 10; counter.min = 30; counter.sec = 47; ``` Don't recall syntax for this, and didn't immediately find a way to do this from Googling. Thanks!
Initialization: ``` counter_t c = {10, 30, 47}; ``` Assignment: ``` c = (counter_t){10, 30, 48}; ``` The latter is called a "compound literal".
I am looking for a comprehensive record of secure coding practices in C. Since i haven't found such a list existing here already we might as well make this into a community wiki, for further reference. I am looking for solutions to security issues like stack and heap based buffer overflows and underflows, integer overflows and underflows, format string attacks, null pointer dereferencing, heap/memory inspection attacks, etc.. NB: Besides coding practices, secure libraries that defend against these kind of attacks are worth mentioning too. LE: As seen in this questionSecure C++ coding practicesbut for C only.
The CERT C "de facto" standard is fairly well-known and addresses these issues at some extent: SEI CERT C Coding Standard There should be several static analyzers on the market that supports CERT C.
I have read in a lot of places but I really can't understand the specified behavior in conditionals. I understand that in assignments it evaluates the first operand, discards the result, then evaluates the second operand. But for this code, what it supposed to do? ``` CPartFile* partfile = (CPartFile*)lParam; ASSERT( partfile != NULL ); bool bDeleted = false; if (partfile,bDeleted) partfile->PerformFileCompleteEnd(wParam); ``` The partfile in the IF was an unnecessary argument, or it have any meaning?
In this case, it is an unnecessary expression, and can be deleted without changing the meaning of the code.
``` typedef struct { int hour; int min; int sec; } counter_t; ``` And in the code, I'd like to initialize instances of this struct without explicitly initializing each member variable. That is, I'd like to do something like: ``` counter_t counter; counter = {10,30,47}; //doesn't work ``` for 10:30:47 rather than ``` counter.hour = 10; counter.min = 30; counter.sec = 47; ``` Don't recall syntax for this, and didn't immediately find a way to do this from Googling. Thanks!
Initialization: ``` counter_t c = {10, 30, 47}; ``` Assignment: ``` c = (counter_t){10, 30, 48}; ``` The latter is called a "compound literal".
Is there any way to check the granularity of gettimeofday() function provided by POSIX?
Instead ofgettimeofday(), consider usingclock_gettime()(specifying theCLOCK_REALTIMEclock). This is also POSIX, and supports aclock_getres()function to obtain the resolution.
I'm trying to develop a GTK desktop application. I want to display an image and make some clickable areas on the image. For this reason, I'm using GtkFixed container to put the image and clickable areas(GtkEventBox is used for areas). After the user clicks on a GtkEventBox, I want to display a box in the clicked area. For this reason, I have thought to use GtkVBox to make a box to display. The problem is that GtkVBox is not visible inside a GtkFixed container parent. So I am stuck at that point. Is it possible to use GtkVBox inside GtkFixed? If not, what is the proper method of doing this job?
I found the answer, it was a mistake that I usedgtk_widget_showto make container visible instead ofgtk_widget_show_all. It works now
Suppose I lock a mutex calledwfg ``` pthread_mutex_lock(&wfg); //and then I return from the function return 0; ``` Would the mutex remain locked?
The mutex remains locked untilpthread_mutex_unlockis called on it from the thread that obtained the lock. Functions have nothing to do with it. You could have something like ``` pthread_mutex_t wfg; ... void razzle() { pthread_mutex_lock(&wfg); } void dazzle() { pthread_mutex_unlock(&wfg); } ... razzle(); ... do stuff ... dazzle(); ``` And that would be fine (but silly).
Assuming the definition: ``` int i = 10; int *p = &i; ``` Why is *p a valid lvalue here: ``` *p+=10; ``` Shouldn't *p evaluate to the value of the int stored at &i, ie. 10, and hence generate a "Not an lvalue" error?
Anlvalueis an expression that refers to a region of storage that can be manipulated. *pis such an expression that refers to a region of storage. This is different than say10+=10;because10doesn't refer to a region of storage like a variable would.
POSIX'smutexis equivalent to Win32'sCRITICAL_SECTION-- its scope is limited to a single process. Win32's mutex (Actually called a "mutant" in NT land) serves as a cross process locking mechanism. What is pthreads' equivalent for cross-process locks?
It's a pthread_mutex_t with apsharedattribute set to PTHREAD_PROCESS_SHARED . However, you're responsible to place such a mutex in shared memory, that all processes can access - so it's not as simple as the win32 api. Perhaps closer to win32 is aposixor sysv semaphore. Traditionally, synchronization across processes has also been done using file locks e.g. flock orlockf(this is in no way as slow as it might sound)
How do I set a fixed window size for a GTK+ app? I have: ``` gtk_window_set_default_size(GTK_WINDOW(mainWindow), 400, 300); gtk_window_set_policy (GTK_WINDOW(mainWindow), FALSE, FALSE, FALSE); ``` but the window gets very small. There are no widgets yet.
Usegtk_window_set_resizablefunction for this purpose ``` gtk_window_set_default_size(GTK_WINDOW(mainWindow), 400, 300); gtk_window_set_resizable (GTK_WINDOW(mainWindow), FALSE); ```
I am trying to update a binary file that has inside some of these structures: ``` typedef struct _test{ char question[100]; char answer[100]; }test; ``` At some point, I want to update one of the answers that is kept inside of a file to another answer (writing back again the answer to the file), still, everytime I update the file it will erase everything and write only the new test structure (tried in fopen with modes wb, wb+ and even wa+ and settinng the cursor with fseek but no luck). How can I edit the file so it doesn't wipe the entire file?
Usefopen("myfile.txt", "r+b").
``` #include <stdio.h> #include <stdio.h> int main () { printf ("hello world"); return 0; } ``` when I compile this, the compiler doesn't give any warning/error for includingstdio.htwice. Why is it so? Aren't the functionsscanf,printfetc. declared and defined twice now? Thanks, in advance
Typically, header files are written similar to the below example to prevent this problem: ``` #ifndef MYHEADER #define MYHEADER ... #endif ``` Then, if included more than once, then 2nd instance skips the content.
I'm trying to create a console pong game but have run into the following issue. I have the following: ``` int main() { while(1) { clearScreen(); std::stringstream sstr; for(int i = 0; i < 20; ++i) { sstr << "Mooooooo \n"; } printf(sstr.str().c_str()); restThread(50); } return 0; } ``` The output I would expect is for Moo to be written 20 times and for the contents of the screen to never actually change. However it flickers from time to time. I suspect this is because the output is shown to the screen before it is fully drawn. Is there a way around this? eg, not showing the user anything until all the characters have been drawn to the screen? Thanks
There's the curses/ncurseslibrary, which requires you to refresh the screen before anything is displayed. It's pretty ubiquitous in terms of platform support.
i used to get a list of processs under linux by enumerating the /proc file system, since it had plain-text files that i can read data from (stat, status, exe link....) but thats not the case on solaris, i tried porting my tools to Oracle Solaris 11 (my first solaris) but it wont work, i tried accessing the /proc folder manually, but couldn't find anything readable, butps -fu userworks ! is it possible that someone can point me on how to get a list of processes uneder solaris? im coding in gcc btw. thanks.
Unlike Linux, Solaris /proc is providing binary data, not text one. Solaris has an extensive and detailed manual pageproc(4)describing what the different files under a process number hierarchy contain, how to access them and what structures to use in order to get their content. This manual page is of course also accessible locally withman -s 4 proc
As C does not have boolean types, how can I write a function like this in C: ``` bool checkNumber() { return false; } ```
Thebooltype is defined in the<stdbool.h>header, and is available under the name_Boolotherwise (assuming you're using a C99 compiler). If you don't have C99, you can always invent your own bool type like this: ``` typedef enum {false, true} bool; ```
For anybody using the cufft library from cuda (or somebody that knows their stuff)- what is the most efficient way to recover data from the interleaved data type cufftComplex? Data is added to the structure as follows: ``` cufftComplex SomeData; /*...a loop...*/ SomeData[i].x=1.0f; SomeData[i].y=0.0f; ``` So now if I cast&(SomeData[0].x&as a pointer to a float, I have data in the form "1 0 1 0 1 " Because the x/y data is interleaved. I want to correctly type it so that I get "1 1 1 1 " ect. Is there a way to recast this type without using a loop and directly assigning the elements? Thanks for any info. As I previously mentioned this is part of the CUDA sdk.
You can't do it just by casting - the underlying data is interleaved and there is no way around that. If you really do need a contiguous stream of e.g. real-only data then you will have to de-interleave the data, which you can do either in place or out-of-place.
I would like to create a file of arbitrary size using the Windows C/C++ API. I am using Windows XP service pack 2 with a 32 bit virtual address memory space. I am familiar with CreateFile. However CreateFile does not have a size arument, The reason I want to pass in a size argument is to allow me to create memory mapping files which allow the user to access data structures of predetermined size. Could you please advise of the proper Windows C/C++ API function which allow me to create a file of arbritrary predetermined size? Thank you
YouCreateFileas usual,SetFilePointerExto the desired size and then callSetEndOfFile.
I am trying to call GetFileInformationByHandle on the executable of my own running program. This means I'll need to get a file handle to the .exe that started my program. Is there any way to do this? Failing that, is there any way to get the nFileIndexHigh and nFileIndexLow for a running executable?
``` DWORD WINAPI GetModuleFileNameEx( __in HANDLE hProcess, __in_opt HMODULE hModule, __out LPTSTR lpFilename, __in DWORD nSize ); ``` Second parameter should be NULL and you will get the name of the current executable. EDIT: Then open the file.
I am trying to update a binary file that has inside some of these structures: ``` typedef struct _test{ char question[100]; char answer[100]; }test; ``` At some point, I want to update one of the answers that is kept inside of a file to another answer (writing back again the answer to the file), still, everytime I update the file it will erase everything and write only the new test structure (tried in fopen with modes wb, wb+ and even wa+ and settinng the cursor with fseek but no luck). How can I edit the file so it doesn't wipe the entire file?
Usefopen("myfile.txt", "r+b").
``` #include <stdio.h> #include <stdio.h> int main () { printf ("hello world"); return 0; } ``` when I compile this, the compiler doesn't give any warning/error for includingstdio.htwice. Why is it so? Aren't the functionsscanf,printfetc. declared and defined twice now? Thanks, in advance
Typically, header files are written similar to the below example to prevent this problem: ``` #ifndef MYHEADER #define MYHEADER ... #endif ``` Then, if included more than once, then 2nd instance skips the content.
I'm trying to create a console pong game but have run into the following issue. I have the following: ``` int main() { while(1) { clearScreen(); std::stringstream sstr; for(int i = 0; i < 20; ++i) { sstr << "Mooooooo \n"; } printf(sstr.str().c_str()); restThread(50); } return 0; } ``` The output I would expect is for Moo to be written 20 times and for the contents of the screen to never actually change. However it flickers from time to time. I suspect this is because the output is shown to the screen before it is fully drawn. Is there a way around this? eg, not showing the user anything until all the characters have been drawn to the screen? Thanks
There's the curses/ncurseslibrary, which requires you to refresh the screen before anything is displayed. It's pretty ubiquitous in terms of platform support.
i used to get a list of processs under linux by enumerating the /proc file system, since it had plain-text files that i can read data from (stat, status, exe link....) but thats not the case on solaris, i tried porting my tools to Oracle Solaris 11 (my first solaris) but it wont work, i tried accessing the /proc folder manually, but couldn't find anything readable, butps -fu userworks ! is it possible that someone can point me on how to get a list of processes uneder solaris? im coding in gcc btw. thanks.
Unlike Linux, Solaris /proc is providing binary data, not text one. Solaris has an extensive and detailed manual pageproc(4)describing what the different files under a process number hierarchy contain, how to access them and what structures to use in order to get their content. This manual page is of course also accessible locally withman -s 4 proc
As C does not have boolean types, how can I write a function like this in C: ``` bool checkNumber() { return false; } ```
Thebooltype is defined in the<stdbool.h>header, and is available under the name_Boolotherwise (assuming you're using a C99 compiler). If you don't have C99, you can always invent your own bool type like this: ``` typedef enum {false, true} bool; ```
For anybody using the cufft library from cuda (or somebody that knows their stuff)- what is the most efficient way to recover data from the interleaved data type cufftComplex? Data is added to the structure as follows: ``` cufftComplex SomeData; /*...a loop...*/ SomeData[i].x=1.0f; SomeData[i].y=0.0f; ``` So now if I cast&(SomeData[0].x&as a pointer to a float, I have data in the form "1 0 1 0 1 " Because the x/y data is interleaved. I want to correctly type it so that I get "1 1 1 1 " ect. Is there a way to recast this type without using a loop and directly assigning the elements? Thanks for any info. As I previously mentioned this is part of the CUDA sdk.
You can't do it just by casting - the underlying data is interleaved and there is no way around that. If you really do need a contiguous stream of e.g. real-only data then you will have to de-interleave the data, which you can do either in place or out-of-place.
I would like to create a file of arbitrary size using the Windows C/C++ API. I am using Windows XP service pack 2 with a 32 bit virtual address memory space. I am familiar with CreateFile. However CreateFile does not have a size arument, The reason I want to pass in a size argument is to allow me to create memory mapping files which allow the user to access data structures of predetermined size. Could you please advise of the proper Windows C/C++ API function which allow me to create a file of arbritrary predetermined size? Thank you
YouCreateFileas usual,SetFilePointerExto the desired size and then callSetEndOfFile.
I am trying to call GetFileInformationByHandle on the executable of my own running program. This means I'll need to get a file handle to the .exe that started my program. Is there any way to do this? Failing that, is there any way to get the nFileIndexHigh and nFileIndexLow for a running executable?
``` DWORD WINAPI GetModuleFileNameEx( __in HANDLE hProcess, __in_opt HMODULE hModule, __out LPTSTR lpFilename, __in DWORD nSize ); ``` Second parameter should be NULL and you will get the name of the current executable. EDIT: Then open the file.
``` #include <stdio.h> #include <stdio.h> int main () { printf ("hello world"); return 0; } ``` when I compile this, the compiler doesn't give any warning/error for includingstdio.htwice. Why is it so? Aren't the functionsscanf,printfetc. declared and defined twice now? Thanks, in advance
Typically, header files are written similar to the below example to prevent this problem: ``` #ifndef MYHEADER #define MYHEADER ... #endif ``` Then, if included more than once, then 2nd instance skips the content.
I'm trying to create a console pong game but have run into the following issue. I have the following: ``` int main() { while(1) { clearScreen(); std::stringstream sstr; for(int i = 0; i < 20; ++i) { sstr << "Mooooooo \n"; } printf(sstr.str().c_str()); restThread(50); } return 0; } ``` The output I would expect is for Moo to be written 20 times and for the contents of the screen to never actually change. However it flickers from time to time. I suspect this is because the output is shown to the screen before it is fully drawn. Is there a way around this? eg, not showing the user anything until all the characters have been drawn to the screen? Thanks
There's the curses/ncurseslibrary, which requires you to refresh the screen before anything is displayed. It's pretty ubiquitous in terms of platform support.
i used to get a list of processs under linux by enumerating the /proc file system, since it had plain-text files that i can read data from (stat, status, exe link....) but thats not the case on solaris, i tried porting my tools to Oracle Solaris 11 (my first solaris) but it wont work, i tried accessing the /proc folder manually, but couldn't find anything readable, butps -fu userworks ! is it possible that someone can point me on how to get a list of processes uneder solaris? im coding in gcc btw. thanks.
Unlike Linux, Solaris /proc is providing binary data, not text one. Solaris has an extensive and detailed manual pageproc(4)describing what the different files under a process number hierarchy contain, how to access them and what structures to use in order to get their content. This manual page is of course also accessible locally withman -s 4 proc
As C does not have boolean types, how can I write a function like this in C: ``` bool checkNumber() { return false; } ```
Thebooltype is defined in the<stdbool.h>header, and is available under the name_Boolotherwise (assuming you're using a C99 compiler). If you don't have C99, you can always invent your own bool type like this: ``` typedef enum {false, true} bool; ```
For anybody using the cufft library from cuda (or somebody that knows their stuff)- what is the most efficient way to recover data from the interleaved data type cufftComplex? Data is added to the structure as follows: ``` cufftComplex SomeData; /*...a loop...*/ SomeData[i].x=1.0f; SomeData[i].y=0.0f; ``` So now if I cast&(SomeData[0].x&as a pointer to a float, I have data in the form "1 0 1 0 1 " Because the x/y data is interleaved. I want to correctly type it so that I get "1 1 1 1 " ect. Is there a way to recast this type without using a loop and directly assigning the elements? Thanks for any info. As I previously mentioned this is part of the CUDA sdk.
You can't do it just by casting - the underlying data is interleaved and there is no way around that. If you really do need a contiguous stream of e.g. real-only data then you will have to de-interleave the data, which you can do either in place or out-of-place.
I would like to create a file of arbitrary size using the Windows C/C++ API. I am using Windows XP service pack 2 with a 32 bit virtual address memory space. I am familiar with CreateFile. However CreateFile does not have a size arument, The reason I want to pass in a size argument is to allow me to create memory mapping files which allow the user to access data structures of predetermined size. Could you please advise of the proper Windows C/C++ API function which allow me to create a file of arbritrary predetermined size? Thank you
YouCreateFileas usual,SetFilePointerExto the desired size and then callSetEndOfFile.
I am trying to call GetFileInformationByHandle on the executable of my own running program. This means I'll need to get a file handle to the .exe that started my program. Is there any way to do this? Failing that, is there any way to get the nFileIndexHigh and nFileIndexLow for a running executable?
``` DWORD WINAPI GetModuleFileNameEx( __in HANDLE hProcess, __in_opt HMODULE hModule, __out LPTSTR lpFilename, __in DWORD nSize ); ``` Second parameter should be NULL and you will get the name of the current executable. EDIT: Then open the file.
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.Closed10 years ago. I want to start learning game programming on windows platform using Visual studio C++ can anybody guide me how to start how to develop a simple game what other libraries i need to add and other tools can any one guide me ?? hoping for quick and positive response
Start here :http://nehe.gamedev.net/ It's about OpenGL. Then read other gamedev.net sections :D
Can anyone please create a c function which formats like below example by taking string anand padding lenth as input. The string should be center aligned and length of padding (dash) is constant (say 45) and string len won't exceed pad length. example #1 --------------ABOUT------------ example #1 ----------MY PAYMENTS----------
Spoiler alert! Here's a different approach. Work out where to stick it, then stick it in. ``` char sBase[] = "---------------------------------------------"; char sInsert[] = "ABOUT"; int nStart = (strlen (sBase) - strlen (sInsert)) / 2; // Centre of sInsert goes in centre of sBase if (nStart >= 0) // Make sure sInsert isn't bigger than sBase { memcpy (&sBase [nStart], sInsert, strlen (sInsert)); // Stick it in } ```
This question already has answers here:Closed12 years ago. Possible Duplicate:C Analog To STL Is there something like STL for C.
You can have a look at theglib, which provides lots of interesting features
I need a good implementation of a (thread safe) cyclic buffer written in c. Does anybody know where i can get it? thanks!
Have you looked atthiswikipedia record? They give an example, and have more external links. As for thread-safe access just wrap the object with your own if needed, and throw a lock() / unlock() at it.
I am writing C functions for Lua. I have many calls like lua_gettable, lua_touserdata, etc My C function may receive complex structures like table with tables as fields. It is hard for me to program stacked machine. Is there way to write Lua script that would be converted to C code. Or some other tools that may help me to code such C functions for lua scripts. Thanks. PS Here is example:- ``` local data = {} data.x = {} data.x.y = 1 myCfunc(data) ``` ``` int myCfunc(lua_State * L){ lua_pushstring(L, "x"); lua_gettable(L, 2); lua_pushstring(L, "y"); lua_gettable(L, -2); double y = lua_tonumber(L, -1); lua_pop(L, 2); } ``` instead of ``` function myCfunc(data) y = data.x.y end ``` My real code is much more complex and I am looking for some automated code generation that will help me.
TryLuaToCee.
Is there a way i can send a notification/message to another PC in C/C++? I think something like net send, but i don't know if there is another way to send a notification/message. I created an application which will run on every PC, and i want, that if my application has finished it should send a notification to my PC, that it has finished running. I don't know if there is a solution for my question, but if yes, could someone tell me, how to do that? Thanks, kampi
How about using sockets? http://www.alhem.net/Sockets/tutorial/
I want to copy folder A and paste to desktop. I am currently using C++ so preferably an OO interface if available.
On Windows (Win32), you could useSHFileOperation, eg: ``` SHFILEOPSTRUCT s = { 0 }; s.hwnd = m_hWnd; s.wFunc = FO_COPY; s.fFlags = FOF_SILENT; s.pTo = "C:\\target folder\0"; s.pFrom = "C:\\source folder\\*\0"; SHFileOperation(&s); ```
If you have a client/server application and you want to duplicate the same series of random numbers that the rand() function produces on the client, but on a server, what is the algorithm/pseudo code? The client and server would be given the same seed (srand() on the client). Thank you! Please note: Is this not known? If so, please stateCan it be reverse engineered? If so, please post, unless any license agreements would prevent you from doing so. In other words, don't do anything illegalI am not interested in design suggestions for the client/server applicationI understand that there are better and more recent ways to generate rand numbers
From Apple's Darwin source code,here is the Mac implementation ofrand(), which should be the same as the one used on iOS.Herealso is therandom()implementation. They both appear to be drawn from FreeBSD.
I am currently running a Lua script with a hook attached usingLUA_MASKCALLand the hook function implemented as follows: ``` void LuaHook(lua_State *L, lua_Debug *ar) { switch(ar->event) { case LUA_HOOKCALL: lua_getinfo(L, ">n", ar); //breakpoint here... } break; default: break; } } ``` I would like to get the name of the called function, but am not sure I am doing it correctly since it never seems to give me anything (the breakpoint is hit at the appropriate times though). The functions that are called are bound C functions that do have names so that seems weird. Overalllua_getinfois a complete mystery to me and the documentation does not clear things up either so any help would be greatly appreciated on this one.
lua_getstackdid the trick so never mind
There is a Ruby process and has a string var named "switch", and the "switch" will be updated by user. There are also 2 C daemon process, which need to access the "switch" in a loop and decide the logic in runtime, how to deal with this case ? thanks!
A socket (or a common file) can be used as a pipe between them.
This was my previous question: Can someone give me simple example in C, of usingpipe()system call to and use ssh to connect to a remote server and execute a simplelscommand and parse the reply. Thanks in advance, [...] I got an answer for that, but I need something more. I would like to ask how to use a pipe and connect to a remote server using ssh, then open mysql and execute a simple query likeSELECT * FROM tables;. Thanks in advance!
Are you doing this for a challenge?, if yes that's cool because you are doing a hard thing to the end, if notderobertsuggestion is the best solution in case you want to communicate with the MySQL server.
I remember having read a very good guide to writing collections. By that I mean, it described using macros to generate types with type parameters, kind of like C++ templates. I'm not sure if it was written by Rusty Russell, but it was someone I recognized. It was posted on hackernews or proggit... I wanted to write a new C library and has searched google for the past 30 min for this guide to no avail. Anybody remember?
This guide fits your description: Collections in Cby Armin Ronacher.
if anyone could answer me why this works, it would be greatly appreciated. The exercise (chapter 4, ex 7 and 8) says that if you have the expression: 9 - ((total - 1) % 10) then, you could be tempted to simplify it like this: 10 - (total % 10) But this would not work. Instead he offers the alternative: (10 - (total % 10)) % 10 Now, I understand how he got to the first simplification, but not why it's wrong, or why does the second one works. Thanks in advance
x %m has a range of (-m, m) in most C implementations. Mathematically it is generally defined from (0, m). Hence by adding m the modulo again will convert the C to the mathematical one.
The reason I'm asking: ``` #include <string.h> using namespace std; int main() { unsigned char file[512000]; unsigned char key[512000]; for(int i = 0; i < 512000; i++) file[i] = key[i]; return 0; } ``` When I compile this with cl.exe on windows I get an executable that is about 31kb in size. The buffers themselves are 500kb each. How does this make sense? Will part of it be allocated on the heap? If I initialized them with data then would the size be correct?
In this case, the buffers will be allocated on the program'sstack spaceat runtime. There's no need for them to be statically built into theexefile.