question
stringlengths
25
894
answer
stringlengths
4
863
I don't want to use system() in my C program, because system(3) blocks and this is not what I want. What is the optimal way to do it?
I think that a quick and dirty action is to call sytem(command &). the & will spawn the new process.
What is the fastest way to count lines and words in a text file in pure ANSI C? A word is terminated by a space or period. Line is terminated by'\n'. This seems to be in C++.
Read the file inIterate over charactersincrement character counterCheck if space/end of lineincrement word counterRepeat second and third steps untilEOF
I'm currently trying to test astrcat()function that I wrote myself. Instead of printing the outputs and checking them line by line manually, I've decided to use assert from assert.h. The problem is that assert is showing errors even though the outputs look totally fine. The following is my code: ``` void mystrcat_tes...
strcmpreturns 0 if both strings are same.asserttakes 0 (false) as an indication that the test failed and will report error. So the test should be: ``` assert(strcmp(str, "") == 0); ```
Given a .so file and function name, is there any simple way to find the function's signature through bash? Return example: ``` @_ZN9CCSPlayer10SwitchTeamEi ``` Thank you.
My compiler mangles things a little different to yours (OSX g++) but changing your leading @ to an underscore and passing the result to c++filt gives me the result that I think you want: ``` bash> echo __ZN9CCSPlayer10SwitchTeamEi | c++filt CCSPlayer::SwitchTeam(int) ``` doing the reverse is trickier as CCSPlayer co...
I know when I have to print I usep->realand so on but what should I write when I am reading numbers usingscanf? ``` #include <stdio.h> typedef struct { int real; int imaginary; } complex; void read(complex*); void main() { complex c; read(&c); } void read(complex* p){ /*what to write in sc...
You can write: ``` scanf("%d %d", &p->real, &p->imaginary); ``` but that depends heavily on the format in which the numbers come.
Can we pass variable number of arguments to a function in c?
Hereis an example: ``` #include <stdlib.h> #include <stdarg.h> #include <stdio.h> int maxof(int, ...) ; void f(void); int main(void){ f(); exit(EXIT SUCCESS); } int maxof(int n_args, ...){ register int i; int max, a; va_list ap; va_start(ap, n_args); max = v...
I have been trying to use fflush to make a progress bar. To test fflush, I wrote the small code below. It works as it supposed to when I uncomment "sleep(1);" but it works in an unexpected way if it remains commented out. It prints the first dash, waits than prints all remaining 9 of them and quits. I don't under...
You need to setjback to zero after the while loop. The next iteration it will just skip over the while loop.
I'm new to C and still trying to grasp the concept of pointers. I know how to write a swap function that works...I'm more concerned as to why this particular one doesn't. ``` void swap(int* a, int* b) { int* temp = a; a = b; b = temp; } int main() { int x = 5, y = 10; int *a = &x, *b = &y; swap(a, b); printf...
You're missing*s in the swap function. Try: ``` void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } ``` That way, instead of just swapping the pointers, you're swapping theints that the pointers are pointingto.
If I open a file and use fscanf to read a file like this: 2 411 501 46.... How do I tell C to read the first number and store it as a variable, then the second as another variable, run a loop, then move on to the next set?
A loop like this is what you're after: ``` int type, stories; while (fscanf(buildingFile, "%d %d", &type, &stories) == 2) { printf("Got type=%d, stories=%d\n", type, stories); /* Do something with 'type' and 'stories' */ } if (ferror(buildingFile)) { perror("buildingFile"); } ```
I need to open a cash drawer using C/C++ or Java. It is a POS-X cash box with a USB connection. I've never done anything like this before. I noticed the cash box was linked to the "COM3" port. I know Java does not have a USB API so I turned to C/C++.
Forum post about ithere. In a nutshell, install the driver, change the COM3 baud rate to 9600, and send a "1" to the COM port. Check outjavax.commfor a method of communicating with a com port on java.
Lookign at:http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/ for string (%.Ns) precision. When I use sizeof or a #define length in the precsion it reads it as actual text. Why is this? What are the rules of this? Does it have to be an integer value only? i.e. - ``` buffer[50]; sprintf (buffer, "%.sizeo...
Anything inside quotation marks is part of the string, and the compiler won't even think of touching it. Instead, you can use a '*' to letsprintfknow your precision is an extra argument it can read. Also, you need the '.' before your precision, or otherwise it will be a pad-width instead. ``` sprintf(buffer, "%.*s"...
Can I call another function in a thread runner function, called by apthread_create()? Are there any restrictions on such functions?
Yes, you can (and doing so is fairly frequent). The main restriction is that you need to synchronize threads when two or more access the same data (at least if there's any chance that any of them might modify that data).
How do I write this C expression inJ? (wherexis input integer, andais temporary variable) ``` ((a= ~x & (~x >> 1)) ^= a ? 0 : (a ^ (a & (a - 1))) | (a ^ (a & (a - 1))) << 1); ``` . Edit: In a more readable form: ``` int a = (~x) & ((~x) >> 1); if (a == 0) return 0; int b = a ^ (a & (a - 1)); return ...
Without testing, the basic transcription would be something like this: ``` Shift =: (33 b.) And =: (17 b.) Not =: (26 b.) Xor =: (22 b.) Or =: (23 b.) BastardFunction =: 3 : 0 a =. (Not y) And (_1 Shift (Not y)) if. a do. b =. a Xor (a And a - 1) (1 Shift b) Or b else. 0 end. ) ``` But...
Is there a method to return the identifier string for a given element's numerical value? For instance, logging a UITouch's phase returns an int, but having the actual string value would be easier to read. I suppose I could write my own switch statement to do this, but I'm hoping there's a built-in means.
No. But if you're looking for a relatively-neat way of maintaining your own solution to this (e.g. a switch statement), you could investigate X-macros (see e.g.http://www.drdobbs.com/184401387).
I'm wondering what sort of algorithm could be used to take something like "4.72" into a float data type, equal to ``` float x = 4.72; ```
scanf,operator>>for istreams, andstrtofwould be the obvious choices. Thereisalsoatof, but, likeatoi, it lacks a way to tell you there was an error in the input, so it's generally best to avoid both.
Suppose I want to read an entire file in memory. I'd open it in binary mode, usefseekto get to the end of the file, then doftellto get its size. Then I would allocate a string with the same size as the file, and just read it in, right? The problem is thatftellreturns along int, andmallocshould receive asize_targument...
I think you want to use mmap() instead.
Actually I've (probably) a "simple" problem. So I don't know how to cast a signed integer to an unsigned integer. My code : ``` signed int entry = 0; printf("Decimal Number : "); scanf("%d", &entry); unsigned int uEntry= (unsigned int) entry; printf("Unsigned : %d\n", uEntry); ``` If I send the unsigned value to th...
``` printf("Unsigned : %u\n", uEntry); // ^^ ``` You must use the%uspecifier to tell theprintfruntime that theuEntryis anunsigned int. If you use%dtheprintffunction will expect anint, thus reinterpret your input back to a signed value.
Is it possible to change the number of bytes a long has in visual studio? Currently when compiling C code sizeof(int) and sizeof(long) are both equal to 4.
Since you're using Visual Studio, presumably your target platform (and the libraries you're using) target Windows. The Win64 platform uses an LLP64 model (http://msdn.microsoft.com/en-us/library/aa384083.aspx) whereintandlongare 32-bits. It would be futile I think to try to makelonga 64-bit type in that situation. U...
In C, is it possible to define a union within another union? If no, why is it not possible? Or if yes, where can it be used?
Suppose you want to define: ``` union myun { int x; sometype y; }; ``` wheresometypeis atypedefdefined by a library you're using. If the library happened to implement it as a union type, then this would be a union within a union, and it would make sense because you can't (from a good design standpoint) violate t...
I want to make some printf's to the windows console from my C program but want to make some of them different colours. Anyone know if this can be done easily? EDIT: Windows XP is my OS
SetConsoleTextAttribute()will let you set the color of subsequent text output. http://msdn.microsoft.com/en-us/library/ms686047.aspx You'll probably want to look at the complete set of Win32 console APIs to be able to get/set/restore and otherwise manipulate the console. http://msdn.microsoft.com/en-us/library/ms68...
From my lecture slides, it states: As illustrated in the code below an array name can be assignedto an appropriate pointer without the need for a preceding & operator. ``` int x; int a[3] = {0,1,2}; int *pa = a; x = *pa; x = *(pa + 1); x = *(pa + 2); a += 2; /* invalid */ ``` Why isa += 2;invalid? Can ...
a += 2gets translated toa = a + 2. Adding a number to an array is the same as adding a number to a pointer which is valid and yields a new pointer. The assignment is the problem - arrays are not lvalues, so you cannot assign anything to them. It is just not allowed. And even if you could there is a type mismatch here...
On my system, I get: ``` sizeof ( int ) = 4 sizeof ( long ) = 4 ``` When I checked with a C program, bothint&longoverflowed to the negative after: ``` a = 2147483647; a++; ``` If both can represent the same range of numbers, why would I ever use thelongkeyword?
inthas a minimum range of -32767 to 32767, whereaslonghas a minimum range of -2147483647 to 2147483647. If you are writing portable code that may have to compile on different C implementations, then you should uselongif you need that range. If you're only writing non-portable code for one specific implementation, th...
I've wrote CGI script for www. This script expects two parameters through GET method, multiply these numbers and write result into the file. ``` mult.cgi?m=1&n=2 ``` But now I want to use this script from console too. I'tried something like ``` ./mult.cgi?m=1&n=2 ``` But it didnt work, how can I send parameters t...
``` QUERY_STRING="m=2&n=4" ./mult.cgi ```
Can anyone give me an example of a Java program which has two native methods declared and defined in C and C++. Actually, I need a procedure as well as the code, so that I can run it and learn from it, thanks.
You can do it with JNI [Java Native Interface] Check this tutorial WIN env LinuxEnvironment :-) better one
The ISO C standard allows three encoding methods for signed integers: two's complement, one's complement and sign/magnitude. What's an efficient or good way to detect the encoding at runtime (or some other time if there's a better solution)? I want to know this so I can optimise a bignum library for the different pos...
You just have to check the low order bits of the constant-1with something like-1 & 3. This evaluates to for sign and magnitude,for one's complement andfor two's complement. This should even be possible to do in a preprocessor expression inside#if #elseconstructs.
Is it possible to change the number of bytes a long has in visual studio? Currently when compiling C code sizeof(int) and sizeof(long) are both equal to 4.
Since you're using Visual Studio, presumably your target platform (and the libraries you're using) target Windows. The Win64 platform uses an LLP64 model (http://msdn.microsoft.com/en-us/library/aa384083.aspx) whereintandlongare 32-bits. It would be futile I think to try to makelonga 64-bit type in that situation. U...
In C, is it possible to define a union within another union? If no, why is it not possible? Or if yes, where can it be used?
Suppose you want to define: ``` union myun { int x; sometype y; }; ``` wheresometypeis atypedefdefined by a library you're using. If the library happened to implement it as a union type, then this would be a union within a union, and it would make sense because you can't (from a good design standpoint) violate t...
I want to make some printf's to the windows console from my C program but want to make some of them different colours. Anyone know if this can be done easily? EDIT: Windows XP is my OS
SetConsoleTextAttribute()will let you set the color of subsequent text output. http://msdn.microsoft.com/en-us/library/ms686047.aspx You'll probably want to look at the complete set of Win32 console APIs to be able to get/set/restore and otherwise manipulate the console. http://msdn.microsoft.com/en-us/library/ms68...
From my lecture slides, it states: As illustrated in the code below an array name can be assignedto an appropriate pointer without the need for a preceding & operator. ``` int x; int a[3] = {0,1,2}; int *pa = a; x = *pa; x = *(pa + 1); x = *(pa + 2); a += 2; /* invalid */ ``` Why isa += 2;invalid? Can ...
a += 2gets translated toa = a + 2. Adding a number to an array is the same as adding a number to a pointer which is valid and yields a new pointer. The assignment is the problem - arrays are not lvalues, so you cannot assign anything to them. It is just not allowed. And even if you could there is a type mismatch here...
On my system, I get: ``` sizeof ( int ) = 4 sizeof ( long ) = 4 ``` When I checked with a C program, bothint&longoverflowed to the negative after: ``` a = 2147483647; a++; ``` If both can represent the same range of numbers, why would I ever use thelongkeyword?
inthas a minimum range of -32767 to 32767, whereaslonghas a minimum range of -2147483647 to 2147483647. If you are writing portable code that may have to compile on different C implementations, then you should uselongif you need that range. If you're only writing non-portable code for one specific implementation, th...
I've wrote CGI script for www. This script expects two parameters through GET method, multiply these numbers and write result into the file. ``` mult.cgi?m=1&n=2 ``` But now I want to use this script from console too. I'tried something like ``` ./mult.cgi?m=1&n=2 ``` But it didnt work, how can I send parameters t...
``` QUERY_STRING="m=2&n=4" ./mult.cgi ```
Can anyone give me an example of a Java program which has two native methods declared and defined in C and C++. Actually, I need a procedure as well as the code, so that I can run it and learn from it, thanks.
You can do it with JNI [Java Native Interface] Check this tutorial WIN env LinuxEnvironment :-) better one
The ISO C standard allows three encoding methods for signed integers: two's complement, one's complement and sign/magnitude. What's an efficient or good way to detect the encoding at runtime (or some other time if there's a better solution)? I want to know this so I can optimise a bignum library for the different pos...
You just have to check the low order bits of the constant-1with something like-1 & 3. This evaluates to for sign and magnitude,for one's complement andfor two's complement. This should even be possible to do in a preprocessor expression inside#if #elseconstructs.
For example if I write to a particular memory location (ex: DMA transfer) how does it get affected in my cache?
The cache is a CPU feature; if you write to memory via the CPU, the cache will be updated and will remain consistent. If you write to memory some other way (e.g. a DMA transfer, as you suggest) you will need to (possibly) flush the cache beforehand, and then tell the CPU that the cache is invalid. How you do this dep...
I want to forward packets by netfilter, so I want to get some c demos to get start, thanks
Did you look at thenetfiltersite? The documentation seems a bit dated, but there's a "Linux netfilter Hacking HOWTO" there. Then play with thesource:)
I'm making a game that will allow content development and I'd like it to be sort of a DLL based system. But, my game works for Linux (X86 arch) , Mac OSX and 32 bit Windows. Is there a way I could allow content developers to compile only one thing and have it work based on the platform? I fear it might get confusing i...
You can decide to use a cross-platform scripting environment like Lua for plugins. This is essentially what most cross-platform games do.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ...
The(long*)expression is a C style cast. It treates the memory pointed to bydataand treats it as a pointer to data of typelong
The following code (a function prototype): ``` void parse_ini(FSFILE *fp, void(*secFunc)(char*), void(*varFunc)(char*, char*)); ``` presents errors when compiled: ``` util\setup.c:38: error: syntax error before '*' token util\setup.c:38: error: 'parse_ini' declared as function returning a function util\setup.c:38: ...
I'd guess that you haven't included a header that declares/definesFSFILE.
Looking at the code: ``` int i = 5; if (i = 0) { printf ("Got here\n"); } ``` What does the C standard have to say about what will get printed? Or in more general terms does the assignment happen first or the comparison?
§6.8.4 says that the syntax for anifselection statement is: ``` if( expression )statement ``` Further in this section, it mentions that if the expression compares unequal to 0, thenstatementis executed. The expression must therefore be evaluated before it can be compared to 0.i = 0is an expression which evaluates to...
What do modern companies use to compile and link their projects? Especially with large projects, makefiles don't seem usable enough to be scalable. As far as I can tell, many companies use either in-house build systems or in-house scripts on top of existing build systems. Do large projects use make? Is pure Ant, Mav...
A lot useCMakethese days, which auto-generates makefiles for various platforms. UnfortunatelyCMakehas its own (weird) internal language, which is why I personally preferSCons- anything it can't do naturally can be easily added - after all it's just Python code. Take a look at thelist of OS projects using SCons. Many o...
What packages do i need to install in order to use a Makefile. I've already installed cmake, would i need ocamlmakefile? My problem is that whenever i type 'make' into the terminal, i'm told "make command not found".
You need GNU make. CMake and other make programs use other filenames generally.
I have an issue regarding freeing memory as under: ``` string points; // some points sequences char* charPoints = (char*)malloc((points.length() +1) * sizeof(char)); //do something free(charPoints); ``` Even then after freeing memory is leaked when checked with instruments
The pointer you pass tofreemust be the same one which returned bymalloc. If you pass a different pointer it will result in a undefined behavior. Take a copy of the pointer before you do the operation such as incrementing thecharPointsand then pass this original pointer tofreefunction to properly release memory.
It just occurred to me That I don't know how to initialize a pointer to pointer from a non pointer value with one statement in C++: ``` int a = 1; int** ppa = &&a; //Does not compile int** ppa = &(&a); //Does not compile int* pa = &a; //Works but is a int** ppa = &pa; //Two step solution ``` Am I missing something...
if you want a pointer to a pointer, the pointer that you want to point to must be located somewhere in memory, so I think there cannot be a "one step solution" because you need a pointer variable that you can point to. (Note: This sentence is not meant to be a linguistic trial to use "point" as often as possible in o...
I understand that there's no String data type in C. What I want to do is get an input string from the user and store it to a variable without having to define how many characters it needs to have. Can I do that using linked lists? I want to avoid putting it to a character array as much as possible so linked lists are ...
Youcoulddo it in a linked list, but a linked list of char will generally be an extremely inefficient data structure -- each node will have one char and (at least) one pointer. In a typical case, you're looking at 4 or 8 bytes for the pointer and one for the char, so you're imposing alotof overhead. My immediate recom...
I have a buffer of pixel values. Is it possible to display that buffer as an image using pixbuf in gtk. i will be using c language.
yes, have a look at the function: ``` gdk_pixbuf_new_from_data () GdkPixbuf * gdk_pixbuf_new_from_data (const guchar *data, GdkColorspace colorspace, gboolean has_alpha, ...
Addresses of 1d arrays are actually taken as ``` a[i]=*(a+i); ``` Are the addresses of 2d arrays calculated as ``` a[i][j]=**(a+i+j); ```
The other answers are not quite correct. It's more like: ``` *(*(a+i)+j) ```
I have to output a large number, a double precision number using the following code: ``` fprintf(outFile," %11.0f %d O(g(n))",factorialNotRecursive(index,factCount),factValue); ``` now the number gets so big that it jumps out of alignment further down the list of output. Once it gets past 11 digits, the ...
I think you cannot do it directly. You have to print to a string, then change the string. ``` /* pseudo (untested) code */ value = factorialNotRecursive(index, factCount); /* make sure buff is large enough (or use snprintf if available) */ n = sprintf(buff, "%11.0f", value); if (n > 11) { buff[10] = '+'; buf...
I have a problem here and need your help. I've been trying to capture keyboard strokes from a created window using cvWaitKey() function. The function works fine if I called the cvWaitKey from the same thread that created the window, but when I create the window from a thread and call cvWaitKey() from another thread it...
Yes, this cannot work. cvWaitKey() is implemented by calling the PeekMessage() API function. That can only see messages on the message queue which is associated with the thread. The thread you created doesn't have any windows. There is no obvious workaround for this, you have to call it on the thread that created ...
I've seen ``` for(;;) ``` and ``` for ( ; *s != '\0'; s++) ``` Why is it blank like that. Thanks.
Theforstatement works like: for (initialization; test-condition; update) And any or all of those three can be omitted (left blank). So: for (;;)is an infinite loop1equivalent towhile (true)because there is no test condition. In fact,for (int i=0; ;i++)would also be an infinite loop1.for ( ; *s != '\0'; s++)is a loo...
I need to compute a number (a/(2**b) using only bitwise operators such as ! & ^ ~ and shifts. I was given the following hint but I'm new to C and I dont know what the code means: ``` int bias = x>0 ? 0 : ((1<<n)-1); ``` Can anyone explain it to me? I thought a>>b would work but I dont think it works for negative nu...
That particular bit of code gives you a bias of 0 if x is positive. Otherwise it produces a mask of the lower n bits. Thex = a ? b : c;pattern is called theternary operator(technically the 'conditional operator', apparently) in C. ``` n (1<<n) (1<<n)-1 binary 0 0x01 0x00 00000000 1 ...
This one is for all you ALSA guys. I need a sanity check here. I am using the the alsa-lib api to play sounds and the function that I am using to write the data to the driver is ``` snd_pcm_sframes_t snd_pcm_writei (snd_pcm_t* pcm, const void* buffer, ...
According to the documentation, it's the amount of frames, not bytes. In the example you linked to the values just happen to be the same because it's using 8-bit samples and one channel, and one frame of one channel 8-bit data is one byte.
So I byte shift a integer into 4 bytes of data. ``` img[4] = (imagewidth >> 24) & 0xFF; img[5] = (imagewidth >> 16) & 0xFF; img[6] = (imagewidth >> 8) & 0xFF; img[7] = imagewidth & 0xFF; img[8] = (imageheight >> 24) & 0xFF; img[9] = (imageheight >> 16) & 0xFF; img[10] = (imageheight >> 8) & 0xFF; img[11] = imageheig...
``` imagewidth = img[4] << 24 | img[5] << 16 | img[6] << 8 | img[7]; imageheight = img[8] << 24 | img[9] << 16 | img[10] << 8 | img[11]; ```
I have an application (for which I do not have the source code). I know that it is designed to dynamically load a shared library, depending on the command line parameters. I know which library it should be loading and I've set up LD_LIBRARY_PATH to the appropriate directory. The application works on one server with...
Usestrace. You will see the libraries being searched etc., which will help you figure out what is happening.
Using the pthread library in C, is it possible to send a SIGSTOP signal to an individual thread? I want to ensure that even though I create N threads in a loop, all should start executing only when all of them have been created. I ask because the man page forpthread_kill()mentions: Signal dispositions are proc...
Barriers (seepthread_barrier_init) are an even easier way to accomplish what you need.
I write a demo with libnet, but get an error when call the function: ``` libnet_error(LIBNET_ERR_FATAL, "libnet_open_link_interface: %s\n", errbuf); ``` The error is "error: ‘LIBNET_ERR_FATAL’ undeclared (first use in this function)". my gcc command is: "gcc demo.clibnet-config --defines --cflags --libs", and run o...
It's the version problem, LIBNET_ERR_FATAL have been removed in 1.1!
I encountered this small piece of code inthis question, & wanted to know, Can therealloc()function ever move a memory block to another location, when the memory space pointed to is shrinked? ``` int * a = malloc( 10*sizeof(int) ); int * b = realloc( a, 5*sizeof(int) ); ``` If possible, under what conditions, can I ...
It's possible forreallocto move memory on any call. True in many implementations a shrink would just result in the change of the reserved size in the heap and wouldn't move memory. However in a heap which optimized for low fragmentation it may choose to move the memory around to a better fitting location. Don't dep...
AFAIK: A http POST request is sent to apache, then piped through stdin and into a CGI program. Does apache guarantee that the stdin stream will always have an EOF ?
EOF isn't a "character" or "marker" in the input; EOF is an error when attempting to read and not having more data available. Calls such asreadorfreadwill return this as an error, such as reporting less was read than was requested. (Thereisan EOF macro in C, but it's treated as an error code and isn't an actual char...
Simply, is ``` &someObject->someAttribute.someMember; ``` equivalent to ``` &(someObject->someAttribute.someMember); ``` or ``` (&someObject)->someAttribute.someMember; ``` or ``` (&(someObject->someAttribute)).someMember; ``` Or should you really put explicit parenthesis there just to be safe?
It is equivalent to: ``` &((someObject->someAttribute).someMember) ``` The->and.have equal precedence and are left-associative. The unary-&has lower precedence. If you have very complex expressions, then you should certainly use parentheses to group things and clarify your code. This isn't particularly complex, t...
I'm testing one code provided from my colleague and I need to measure the time of execution of one routine than performs a context switch (of threads). What's the best choice to measure the time? I know that is available High Resolution Timers like, ``` QueryPerformanceCounter QueryPerformanceFrequency ``` but how ...
``` LARGE_INTEGER lFreq, lStart; LARGE_INTEGER lEnd; double d; QueryPerformanceFrequency(&lFreq); QueryPerformanceCounter(&lStart); /* do something ... */ QueryPerformanceCounter(&lEnd); d = ((doublel)End.QuadPart - (doublel)lStart.QuadPart) / (doublel)lFreq.QuadPart; ``` d is time interval in seconds.
I've never worked with a language that didn't provide for some form of memory management, and thus managed to get by without ever really groking pointers. I can dabble inCI guess, as a result of coding inObjective-Cfor a little while.
Hmmm, maybe it's the single linked list. Try it:create, populate, reverse, releasea single linked list ``` struct node { int data; struct node *next; }; ```
how to get the value of an integerx, indicated byx!, it is the product of the numbers 1 to x. Example:5! 1x2x3x4x5 = 120. ``` int a , b = 1, c = 1, d = 1; printf("geheel getal x = "); scanf("%d", &a); printf("%d! = ", a); for(b = 1; b <= a; b++) { printf("%d x ", c); c++; d = d*a; } printf(" = %d", d...
how to get the som of an integer x, indicated by x!, is the product of the numbers 1 to x. Did you meanfactorialof x ? Changed = d*a;tod = d*binside the loop
When I run this bit of code through GCC I get this warning on the line where I set info to SDL_GetVideoInfo(). warning: initialization discards qualifiers from pointer target type ``` int main(int argc, char** argv) { SDL_Init(SDL_INIT_EVERYTHING); SDL_VideoInfo* info = SDL_GetVideoInfo(); int SCREEN_WI...
Thedocumentationsays that the function returns aconst SDL_VideoInfo *, so change your code to: ``` const SDL_VideoInfo* info = SDL_GetVideoInfo(); ``` Without theconst,infocould be used to change the value pointed to by it, but obviously, you can't do that.
I'm trying simple example - ``` #include <stdio.h> int main(void) { printf("Content-type: text/html\n\n"); printf("<html><title>Hello</title><body>\n"); printf("Goodbye Cruel World\n"); printf("</body></html>"); return 1; } ``` compiled and moved to apache docroot - but when i click on url - it comes as a po...
Unfortunately, unless you already have other CGI scripts running in the same place, this is harder than just plopping a file somewhere - some stuff has to be configured in the web server to make it possible: apache settings, the.htaccessfile, permissions, and so on. Make sure you read theApache Tutorial on CGIto be u...
I want to use my program like this: ``` ./program -I /usr/include/ /usr/bin/ /usr/local/include/ ... ``` Where the switch can go on and on like in a var args list. How could I do that in C99? Preferably get a something likechar **args_listorchar *args_list[]that contains all of the things like/usr/includeand/usr/bin...
The output of running the following code: ``` int main(int argc, char* argv[]) { for (int i = 1; i < argc; ++i) { printf("%s\n", argv[i]); } } ``` Executed byprogram -I /usr/include/ /usr/bin/ /usr/local/include/ Output: ``` -I /usr/include/ /usr/bin/ /usr/local/include/ ``` Note that in the c...
What happens in C when you create an array of negative length? For instance: ``` int n = -35; int testArray[n]; for(int i = 0; i < 10; i++) testArray[i]=i+1; ``` This code will compile (and brings up no warnings with -Wall enabled), and it seems you can assign totestArray[0]without issue. Assigning past that...
It's undefined behaviour, because it breaks a "shall" constraint: C99 §6.7.5.2: If the size is an expression that is not an integer constant expression... ...each time it is evaluated it shall have a value greater than zero.
This question already has answers here:Closed13 years ago. Possible Duplicate:Variable length arrays in C++? I am just curious, is there any particular reason why C++ does not allow variable length arrays?
Two reasons: C++ is based on C89 (the C standard as published in 1989). VLAs were only introduced in C99.C++ hasstd::vector<>and a whole bunch of other containers, which is why I believe that C++ will never bother with VLAs. It already had them when VLAs were invented for C.
AFAIK: A http POST request is sent to apache, then piped through stdin and into a CGI program. Does apache guarantee that the stdin stream will always have an EOF ?
EOF isn't a "character" or "marker" in the input; EOF is an error when attempting to read and not having more data available. Calls such asreadorfreadwill return this as an error, such as reporting less was read than was requested. (Thereisan EOF macro in C, but it's treated as an error code and isn't an actual char...
Simply, is ``` &someObject->someAttribute.someMember; ``` equivalent to ``` &(someObject->someAttribute.someMember); ``` or ``` (&someObject)->someAttribute.someMember; ``` or ``` (&(someObject->someAttribute)).someMember; ``` Or should you really put explicit parenthesis there just to be safe?
It is equivalent to: ``` &((someObject->someAttribute).someMember) ``` The->and.have equal precedence and are left-associative. The unary-&has lower precedence. If you have very complex expressions, then you should certainly use parentheses to group things and clarify your code. This isn't particularly complex, t...
I'm testing one code provided from my colleague and I need to measure the time of execution of one routine than performs a context switch (of threads). What's the best choice to measure the time? I know that is available High Resolution Timers like, ``` QueryPerformanceCounter QueryPerformanceFrequency ``` but how ...
``` LARGE_INTEGER lFreq, lStart; LARGE_INTEGER lEnd; double d; QueryPerformanceFrequency(&lFreq); QueryPerformanceCounter(&lStart); /* do something ... */ QueryPerformanceCounter(&lEnd); d = ((doublel)End.QuadPart - (doublel)lStart.QuadPart) / (doublel)lFreq.QuadPart; ``` d is time interval in seconds.
I've never worked with a language that didn't provide for some form of memory management, and thus managed to get by without ever really groking pointers. I can dabble inCI guess, as a result of coding inObjective-Cfor a little while.
Hmmm, maybe it's the single linked list. Try it:create, populate, reverse, releasea single linked list ``` struct node { int data; struct node *next; }; ```
how to get the value of an integerx, indicated byx!, it is the product of the numbers 1 to x. Example:5! 1x2x3x4x5 = 120. ``` int a , b = 1, c = 1, d = 1; printf("geheel getal x = "); scanf("%d", &a); printf("%d! = ", a); for(b = 1; b <= a; b++) { printf("%d x ", c); c++; d = d*a; } printf(" = %d", d...
how to get the som of an integer x, indicated by x!, is the product of the numbers 1 to x. Did you meanfactorialof x ? Changed = d*a;tod = d*binside the loop
When I run this bit of code through GCC I get this warning on the line where I set info to SDL_GetVideoInfo(). warning: initialization discards qualifiers from pointer target type ``` int main(int argc, char** argv) { SDL_Init(SDL_INIT_EVERYTHING); SDL_VideoInfo* info = SDL_GetVideoInfo(); int SCREEN_WI...
Thedocumentationsays that the function returns aconst SDL_VideoInfo *, so change your code to: ``` const SDL_VideoInfo* info = SDL_GetVideoInfo(); ``` Without theconst,infocould be used to change the value pointed to by it, but obviously, you can't do that.
I'm trying simple example - ``` #include <stdio.h> int main(void) { printf("Content-type: text/html\n\n"); printf("<html><title>Hello</title><body>\n"); printf("Goodbye Cruel World\n"); printf("</body></html>"); return 1; } ``` compiled and moved to apache docroot - but when i click on url - it comes as a po...
Unfortunately, unless you already have other CGI scripts running in the same place, this is harder than just plopping a file somewhere - some stuff has to be configured in the web server to make it possible: apache settings, the.htaccessfile, permissions, and so on. Make sure you read theApache Tutorial on CGIto be u...
I want to use my program like this: ``` ./program -I /usr/include/ /usr/bin/ /usr/local/include/ ... ``` Where the switch can go on and on like in a var args list. How could I do that in C99? Preferably get a something likechar **args_listorchar *args_list[]that contains all of the things like/usr/includeand/usr/bin...
The output of running the following code: ``` int main(int argc, char* argv[]) { for (int i = 1; i < argc; ++i) { printf("%s\n", argv[i]); } } ``` Executed byprogram -I /usr/include/ /usr/bin/ /usr/local/include/ Output: ``` -I /usr/include/ /usr/bin/ /usr/local/include/ ``` Note that in the c...
What happens in C when you create an array of negative length? For instance: ``` int n = -35; int testArray[n]; for(int i = 0; i < 10; i++) testArray[i]=i+1; ``` This code will compile (and brings up no warnings with -Wall enabled), and it seems you can assign totestArray[0]without issue. Assigning past that...
It's undefined behaviour, because it breaks a "shall" constraint: C99 §6.7.5.2: If the size is an expression that is not an integer constant expression... ...each time it is evaluated it shall have a value greater than zero.
This question already has answers here:Closed13 years ago. Possible Duplicate:Variable length arrays in C++? I am just curious, is there any particular reason why C++ does not allow variable length arrays?
Two reasons: C++ is based on C89 (the C standard as published in 1989). VLAs were only introduced in C99.C++ hasstd::vector<>and a whole bunch of other containers, which is why I believe that C++ will never bother with VLAs. It already had them when VLAs were invented for C.
What is the Delphi equivalent of ``` unsigned char** ' ``` in C i'm not sure if its a pointer to an array or a pointer to a pointer or if the two things are the same in C.
EDITIn C both pointer to an array and pointer to a pointer have different meaning to the compiler (thanks caf). In C arrays are simply block of memory. There is no such function likeLength(array),Low(array)orHigh(array)that you can use on Pascal arrays. For practical purpose to Pascal programmers C arrays can be usua...
While reading about printf(),I found that it can print numbers as positive or negative as desired by the user by following code(for -).But the code doesnt work and the output is a positive value.Please mention where the error is.Thanks ``` #include<stdio.h> int main() { printf (" %-d\n", 1977); return 0; } ```
From your comments it looks like you misreadthis page. The-and+specifiers do two completely different things, and neither does what you think '-' should do. As others have noted,-does left justification. The+specifier prints positive numbers with a leading plus sign (and negative numbers still get a leading minus sig...
This question already has answers here:Closed13 years ago. Possible Duplicate:Can you write object oriented code in C? Hi, can someone point me to a tutorial explain me how OOP concepts can be implemented in ANSI C: virtual functionsinheritancebest practice A book about OOP programming ANSI C would be great too.
Here is the link of a book on this topic:http://www.planetpdf.com/codecuts/pdfs/ooc.pdf(Object Oriented Programming in Ansi-C - exacty what you were looking for). Good luck and have patience. Writing OOP in C is not an easy task, but can be somewhat rewarding if you like extreme things ! Another starting point will ...
Is this possible? The idea is typing a password and it being translated to asterisks on the fly- pretty much like a password field on HTML. I've written this code, but it converts the input AFTER the user presses enter, not while he/she is typing. ``` #include <stdio.h> #include <string.h> #include <iostream> int m...
I don't think it is possible using standard io. You need a library for more advanced text user interface like ncurses.
This question already has answers here:Closed13 years ago. Possible Duplicate:“C subset of C++” -> Where not ? examples ? I'm aware that C++ is not a strict superset of C. What language features prevent C++ from being a superset of C?
The elephant in the room: the following is valid C but not valid C++. ``` int typename = 1; ``` Substitute your favorite C++ reserved word.
``` size_t pixelsWidth = (size_t)bitmapSize.width; ``` Or is it totally fine to do without the casting to size_t? bitmapSize is of type CGSize...
You should use the proper type, which is probably CGFloat. size_t is something int'ish and inappropriate.
This question already has answers here:How to get the return value of a program ran via calling a member of the exec family of functions?(6 answers)Closed9 years ago. I have this c code: ``` if(fork()==0){ execl("/usr/bin/fsck", "fsck", "/dev/c0d0p1s0", NULL); } ``` it callsexeclto runfsckfor checking the filesys...
Have the parent process wait for the child to exit: ``` pid_t pid = fork(); if (pid == -1) { // error, no child created } else if (pid == 0) { // child } else { // parent int status; if (waitpid(pid, &status, 0) == -1) { // handle error } else { // child exit code in status // use WIFEXITED,...
Could someone provide me an example of utilizing SECURITY_DESCRIPTOR inInitializeObjectAttributes()? I plan to use them with NtCreateKey(). I couldn't find any example on the Internet. Thanks in advance.
The last parameter ofInitializeObjectAttributes()can be just well documentedSECURITY_DESCRIPTOR. You can use for exampleConvertStringSecurityDescriptorToSecurityDescriptorto convertSecurity Descriptor String FormattoSECURITY_DESCRIPTOR. You can createSECURITY_DESCRIPTORwithout usage ofsecurity descriptor definition la...
I have a socket() function call in my code.(using C language): socket(AF_INET, SOCK_STREAM, 0)) I want that it should result in error.(INVALID_SOCKET) Do we have some way out so that above function call results in error. Like stopping some services,etc
Since you say this is in your code, you could define your own implementation ofsocketthat always returns INVALID_SOCKET: ``` int socket(int domain, int type, int protocol) { return INVALID_SOCKET; } ``` If you link with the object file that defines your version of socket before linking with the real version, the...
How is the debug information organized in a compiled C/C++ program? What does it contain? How is the debug information used by the debugger, e.g. gdb, and how can I read the debug information better than nm or objdump?
The debugging information depends on the operating system -gdbuses whatever the native format is. On many UNIX-like systems, debugging information is stored inDWARFformat. You can uselibdwarfanddwarfdumpto examine this information. EDIT: On Linuxreadelf -w a.outwill print allDWARFdebug info contained in the executa...
Is there any way to easily limit a C/C++ application to a specified amount of memory (30 mb or so)? Eg: if my application tries to complete load a 50mb file into memory it will die/print a message and quit/etc. Admittedly I can just constantly check the memory usage for the application, but it would be a bit easier i...
Read the manual page forulimiton unix systems. There is a shell builtin you can invokebeforelaunching your executable or (in section 3 of the manual) an API call of the same name.
What libraries for C do I need to play a wav file on a Win32 system? And what is the code to use those libraries?
Use the Win32 API:PlaySound Include library:Winmm.libHeader include:Mmsystem.h(includeWindows.h)Example: ``` PlaySound(TEXT("recycle.wav"), NULL, SND_FILENAME); ```
Given: ``` struct objStruct { int id; int value; }; typedef struct objStruct Object; ``` Is there a shortcut to allocate and initialize the object, something like a C++ constructor?It could even be a preprocessor macro. Whatever makes the code shorter and more readable than this: ``` Object *newObj = mallo...
In C I typically create a function in the style of a constructor which does this. For example (error checking omitted for brevity) ``` Object* Object_new(int id, int value) { Object* p = malloc(sizeof(Object)); p->id = id; p->value = value; return p; } ... Object* p1 = Object_new(id++, myValue); ```
e.g. one has a couple of arrays of ints or floats and a few integers to store. Is there a simplistic way to save them for later reloading without having to write a data format from scratch etc.?
netcdf (simpler interface)hdf5 (more powerful) they are not simple, however few hours investment is worth it
The template and cppIntegration examples in the CUDA SDK (version 3.1) use Externs to link function calls from the host code to the device code. However, Tom's commenthereindicates that the usage of extern is deprecated. If this the case, what's the correct structure for a CUDA project such as the template example o...
Depends what your host code is. If you end up mixing C and C++ you still need the externs. For details seethis guide. Update: the content from the above link has been moved [here] (https://isocpp.org/wiki/faq/mixing-c-and-cpp).
What is going on here? ``` #define CONSTANT_UNICODE_STRING(s) \ { sizeof( s ) - sizeof( WCHAR ), sizeof(s), s } . . . . UNICODE_STRING gInsufficientResourcesUnicode = CONSTANT_UNICODE_STRING(L"[-= Insufficient Resources =-]"); ``` This code is working. I need to see the pre-proces...
UNICODE_STRINGis defined in<winternl.h>as a type that has two sizes followed by a pointer to a string. ``` typedef struct _UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING; ``` The commas in the macro separate the values for the fields in the structure.
TheC-faqsays that the code: ``` int i = 7; printf("%d\n", i++ * i++); ``` prints 49. Regardless of the order of evaluation, shouldn't it print 56? When I ran this code on my Turbo C 3.0 compiler it gave me the output of 56. Why is there a contradiction?
There is no contradiction. The question was worded from a user perspective, and if you carefully read the answer, you will find the remark The behavior of code which contains multiple, ambiguous side effects has always been undefined. So it might print 49, or 56. Undefined behavior is, after all, undefined. This...
Are the following equivalent in C? ``` // #1 struct myStruct { int id; char value; }; typedef struct myStruct Foo; // #2 typedef struct { int id; char value; } Foo; ``` If not, which one should I use and when? (Yes, I have seenthisandthis.)
The second option cannot reference itself. For example: ``` // Works: struct LinkedListNode_ { void *value; struct LinkedListNode_ *next; }; // Does not work: typedef struct { void *value; LinkedListNode *next; } LinkedListNode; // Also Works: typedef struct LinkedListNode_ { void *value; st...
My professor and a couple of students are arguing about whetherargvis null terminated or not. My friend wrote a small program and it printed outnullbut another kid said that he is probably simply reading into blank memory. Can someone solve this discussion?
From the Standard: 5.1.2.2.1 Program startup...-- argv[argc] shall be a null pointer. So, yes; argv is null terminated
Here's some example code to give an idea of what I want. ``` int regular_function(void) { int x,y,z; /** do some stuff **/ my_api_call(); return x; } ... void my_api_call(void) { char* caller = get_caller_file(); int line = get_caller_line(); printf("I was called from %s:%d\n", caller,...
If you have compiled your binary with debug symbols, you may access it using special libraries, likelibdwarffor DWARF debug format.
``` /* strchr example */ #include <stdio.h> #include <string.h> int main () { char str[] = "This is a sample string"; char * pch; printf ("Looking for the 's' character in \"%s\"...\n",str); pch=strchr(str,'s'); while (pch!=NULL) { printf ("found at %d\n",pch-str+1); pch=strchr(pch+1,'s'); } r...
You don't need to index the string. You have a pointer to the character you want to change, so assign via the pointer: ``` *pch = 'r'; ``` In general, though, you index using[]: ``` ptrdiff_t idx = pch - str; assert(str[idx] == 's'); ```
Is it possible to have the array subscript before the variable name in declaration? For example, is it possible to have ``` char [10]data; ``` where the intended declaration is: ``` char data[10]; ``` I know that this might be stretching it a bit too much, but I have the variable type defined using#define, which ...
You might want to consider using a typedef for this: ``` typedef char TYPE[10]; ```
That is, why doesunsigned short var= L'ÿ'work, butunsigned short var[]= L"ÿ";does not?
L'ÿ'is of typewchar_t, which can be implicitly converted into anunsigned short.L"ÿ"is of typewchar_t[2], which cannot be implicitly converted intounsigned short[2].
For debugging reasons, how can one in a C program print some memory address? For instance, how should I do to print the content of address 0x611268 in form of a 4 byte float? I know I could use a debugger, but I mean, to print out in screen.
More correctly,printf("Value = %f\n", *((float*)0x611268)); Of course this assumes the address you've given is in the address space of the process running theprintf.