question
stringlengths
25
894
answer
stringlengths
4
863
This question already has answers here:How would I load a PNG image using Win32/GDI (no GDI+ if possible)?(5 answers)Closed9 years ago. Very simple question: how do I render a png image with GDI in C (including its transparencies)?
I went with GDI+ instead of GDI.
How do I compile 16-bit C code with GCC? I am trying to write a flat bootloader that just writes "Hello World!" to the computer and halts. ``` int main(int argc, char** argv) { char* value = "Hello World!"; __asm { mov si, value loop: lodsb cmp al, 0 halt: je halt ...
You don't. You can't. GCC doesn't generate 16-bit x86 code. Use Open Watcom C/C++ or the ancient Turbo C++ (v 1.01 is freely available online).
I have the following code to change the style of my window at runtime: ``` SetWindowLong(hwnd, GWL_EXSTYLE, WS_EX_APPWINDOW|WS_EX_WINDOWEDGE); ``` The only problem is, it does not have the desired effect until I start dragging the window's edge to resize it. Is there something I need to do to get this working? I ...
You need to use SetWindowPos with the SWP_FRAMECHANGED flag for the update to take affect. If you don't need the size or position changed OR SWP_NOMOVE and SWP_NOSIZE to SWP_FRAMECHANGED
What is the fastest way to zero out an unsigned int? I am currently just setting the value to 0, but I don't know if there are any tricks for zeroing out a variable? I need a few clock cycles back in my current project. I am using a standard 8051 processor and I have two different variables I need to get to zero if t...
The question is labelled 8051, so if the need is to zero out a register XORing the register with itself will be a faster way to zero it out, instead of moving a zero in it. One opcode fetch and decode vs opcode fetch decode and operand fetch. If you are using higher level language and not hand assembling or writing i...
What is the name of the signal that gets emitted when a user types some text at a gtk+ entry? I am using GTK+ 2.24 in c.
AGtkEntryis an instance of aGtkEditablewhich has three signals: Thechangedsignal is emitted at the end of a single user-visible operationThedelete-textsignal is emitted when text is deleted from the widget by the userTheinsert-textsignal is emitted when text is inserted into the widget by the user I assume you want ...
``` free(str); printf("%d\n", str->listeners); ``` The call to printf succeeds (as do any other calls to str's members). How is this possible?
Here's an analogy for you: imagine you're renting an apartment (that's the memory) and you terminate your lease but keep a duplicate of the key (that's the pointer). Youmightbe able to get back into the apartment later if it hasn't been torn down, if the locks haven't been changed, etc. and if you do it right away you...
Is there a way to tell (on UNIXes) which of a process's memory pages are in the RAM and which have been swapped out?
Not in a portable way. Even if it were possible, it would be mostly useless. A page you have checked is swapped in could very well be swapped out the moment you are ready to use it.
A quick google search yields at least one tutorial for writing aC++ "Hello World"for node.js, but it's unclear if it's possible to write such an extension using only C. Assuming it is possible, what challenges / limitations would I face?
You can write parts of your extension in C if you want, but you'll need at least a small bit of C++ code to glue together your C code with Node. As you will have seen in your HelloWorld, extensions rely on thev8.handnode.hheaders, which have all of the classes that Node expects. Without those, you won't be able to pr...
which kind of signal i've to handle in a AF_INET socket, both server and client side?
Depending on how you're doing what you're doing, youmayhave to handleSIG_PIPE, which can happen when the connection is arbitrarily broken. You should not have to handle any other signals. If you are usingselect()orpoll()or (personal preference)epoll()you should check for errors (eg,POLLHUP)beforeyou check for read/w...
After searching I couldn't find any example that a LKM uses a static or dynamic libraries. I want to create static and dynamic libraries (may be use standard C library or any other libraries), then develop a LKM that uses my own static and dynamic libraries. How to link a LKM (loadable kernel module) to static or dy...
I'm afraid you have a major misconception - Linux kernel modules cannot be linked with standard user space libraries, such as the C library, either static or dynamic. This is because the C library and the dynamic linker (that implements dynamic linking) actually calls the kernel to do its job. You can write a static ...
I want to read each of the 4 columns stored in a .txt file separated by a space into an array of their own. The text file may have hundreds of rows so reading until the end of file is desirable. Example: ``` 3.4407280e+003 6.0117545e+003 8.0132664e+002 2.5292922e+003 3.4163843e+003 5.9879421e+003 7.7792044e+002 2.50...
fscanfis your friend: ``` static const int MAX_FILE_ROWS = 200; double lines[MAX_FILE_ROWS][4]; FILE *file = fopen("myfile.txt", "r"); for (int i = 0; i < MAX_FILE_ROWS; i++) { if (feof(file)) break; fscanf(file, "%lf %lf %lf %lf", &(lines[i][0]), &(lines[i][1]), &(lines[i][2]), &(lines[i][3])); } ...
I am trying to develop a app that will use the devkitPro toolkit. How do I play Audio files on Wii? I can't seem to get them to play. I have tried over and over.
Doesn't look like this has been answered yet. devKitPro is a beautifully documented platform, so hopefully you'll find these examples useful. Check out:http://sourceforge.net/projects/devkitpro/files/examples/wii/ Within that tarball, you'll find examples for playing .mod, .ogg and .mp3 files. You're best off testi...
I'm looking for algorithm scroll number For example; I have an array which has the numbers 1,2,3,4. I want to make my new array 4,1,2,3. Does anyone know how to do this? But not just for D[4]; it can be 1,2,3,4,5,6,7
Using modular arithmetics is probably the most elegant way to do it. For example, you can do it like this: ``` int a[size]; int b[size]; for (int n=0; n<size; n++) b[(n+1)%size] = a[n]; ``` If you need to shift the elements for more than one position, you can change theb[(n+1)%size]tob[(n+2)%size]and so on.
I am creating a text editor in C using gtk+-2.0 gtksourceview-2.0. I am having trouble finding any information about how to comment a line or a block. I am finding plenty of information about how to highlight these commented lines, but nothing about actually creating these comments. I have searched google, devhelp, ...
That function doesn't exist. Seethis codefor an example if you don't want to reinvent the wheel; look at the functionsaction_comment_out_selection()andaction_uncomment_selection().
I'm attempting to write an AAC file from the output stream of an AUGraph, and on playback my file only plays a buzzing noise, and I get the errorExtAudioFileWriteAsync -50. I'd like to know what it means so that I can search for and destroy the problem. Thanks to any Core Audio ninjas that can hook a brother up.
In case anyone else has this problem, the-50 erroris akAudio_ParamError error, defined in CoreAudioTypes.h. Therefore, one of the parameters being passed toExtAudioFileWriteAsyncmust be faulty.
I have a good grip over recursive algorithms, however I usually stumble when designing recursive algorithms for binary search trees. If anyone could point to a tutorial they found useful, specifically on the design of recursive algorithms for binary search trees, it will be greatly appreciated. Note: I have already st...
Do you need tutorials about design of recursive algorithms for binary search trees? Here they are: Binary search tree - WikiEBTreeBinary Trees by Nick Parlante - StandfordBinary Search Trees - PrincetonBinary Search Tree C++ implementationBinary Tree TraversalsBalanced binary search tree on arrayMultidimensional Bina...
I have three questions which are causing me a lot of doubts: If one thread in a program callsfork(), does the new process duplicate all threads, or is the new process single-threaded?If a thread invokesexec(), will the program specified in the parameter toexec()replace the entire process including ALL the threads?Are...
Forexec, fromman execve: All threads other than the calling thread are destroyed during anexecve(). Fromman fork: The child process is created with a single thread — the one that calledfork().
I am trying to include a library file namedlibmathematica.ain gcc so it gets linked in the executableexample. I attempt to do this withgcc main.c libmathematica.a -o example Note: I have to do this with gcc, as ld won't link it properly with the correct system libraries But I get:fatal error: mathematica.h: No such...
A header file cannot bein the library. It has to be present at a certain location and you have to specify that location with the-Icompiler flag: ``` gcc -I/path/to/mathematica/include main.c libmathematica.a -o example ``` If the header file is in the directory where themain.cis or in a subdirectory, then be sure th...
I know what a buffer overflow is and I know that (without DEP), often stack return addresses are overwritten with an address pointing somewhere in data or code sections.. but what if the stack return address were overwritten with another stack address overwritten with executable code? Would DEP be still effective in t...
DEP prevents execution of code on the stack, as well as the heap. In other words, the stack is viewed as beingdata.
In iOS, you don't know the font file path(I mean, though you can see them at somewhere of /System, there is no API for you to get a font's path, they may be changed in future), the way to access font is by its name eg.[UIFont fontWithName...],CGFontCreateWithFontNameetc.. I need to use FreeType in my project, and I w...
I found a solution. Read out the tables of theCGFontRefto form a font, and use the data forFT_Face. Check here:https://gist.github.com/1892760.
I wonder if does: ``` void *ptr = NULL; printf("%p\n", ptr); ``` Will always gives(nil)output? Does it depend on standard library implementation, or it's a C99 standard specification?
On my system it yields(null)so I guess it's implementation defined. More generally, everything%pprints is implementation-defined: 7.21.6.1The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.
I've got two programs - one of them is generating some data and put them into FIFO and the other one reads this data from FIFO and do something with them. How to limit number of reading programmes? I've think of limiting FIFO's size or checking how many data is inside, but i haven't found anything interesting. Thanks ...
A fifo pipe is a system file and so the only way you can control access to it is by the usual means (ownership and permissions). But see alsoman flock. File locking is not enforceable on linux, ie, you can ignore it, but if you implement your readers to obey file locks, then problem solved. So: if the problem isunw...
I am looking to programatically mount a USB drive in Linux, so that I can write a text document using fprintf. I am having trouble finding out how to mount the drive. I have been searching the web for an answer, and I found many tutorials of how to do it via the command line, but none in C. Can someone please point me...
``` man 2 mount ``` e.g. ``` #include <sys/mount.h> if (mount("/dev/mmcblk0p1", "/mnt/sd", "vfat", MS_NOATIME, NULL)) { if (errno == EBUSY) { printf("Mountpoint busy"); } else { printf("Mount error: %s", strerror(errno)); } } else { printf("Mount successful"); } ```
From the shell I can activate the leds on my system like this: ``` #echo 1 > /sys/class/leds/NAME:COLOR:LOCATION/brightness ``` I want to do the exact same thing from a C program, but I have not been able to find a simple example on how to accomplish this?
Open the sysfs node like a file, write '1' to it, and close it again. For example: ``` #include <stdio.h> #include <fcntl.h> void enable_led() { int fd; char d = '1'; fd = open("sys/class/leds/NAME:COLOR:LOCATION/brightness", O_WRONLY); write (fd, &d, 1); close(fd); } ```
In c, we create a thread like so: ``` void * run(void * arg){ printf("hello world\n"); } int main(){ pthread_t thread; int a = pthread_create(&thread, NULL, run, (void*)0); } ``` But it will not work if I declare run as ``` void run(){} ``` On the other hand, if I cast it to(void *)in the parameter of...
The thread function must be declared to returnvoid *because the threading library expects such a return value, and will store it into a location given topthread_join()after the thread terminates. If you don't need the thread return value for anything, you can justreturn 0;.
Can anyone please point out why I get thesyntax error: expected expression before '{' tokenin ``` T[SIZE] = {NULL}; ``` in the code segment below? Thanks. ``` typedef struct SetObject{ int key; struct SetObject *prev; struct SetObject *next; } Node; Node *T[SIZE]; //global variable void initT(void) { ...
To assign a pointer value to an array element, use: ``` T[SIZE] = NULL; ``` The curly brackets aroundNULLare not needed. The second problem is thatSIZEis aninvalidindex into theTarray. The valid indexes range from0throughSIZE-1. Assigning toT[SIZE]will lead to undefined behaviour.
I over heard someone saying thatsystem()call fromlibcis not safe. One reason i can think of is that it launches shell utility e.g./bin/bashand ifsystem("rm -rf $input")is started and $input is un-sanitized user input then it can potentially wreck havoc if $input="/". What are the other reasons?
In general, "safe" is by comparison to theexecfamily of system calls (execve()being the lowest level standard one); involving a shell not only means problems with unsanitized data but also with$PATH(do youknowwhat you are executing?) and with$IFS(this is a fun one: if someone can change$IFSon you, the shell won't par...
I have this code where I want to read from a text file each line and then print it to the standard output. For no reason it only saves the last line of the file in that array of chars. Any tips why(some explanations are)? ``` 9 int main(){ 10 FILE * f; 11 char buffer[255]; 12 char * arr[255]; 13 i...
Your program only has one one buffer that gets overwritten with each line of the file EDIT: ``` char* buf; while(1){ buf = malloc(255); if(fgets(buf,255,f) != NULL ){ arr[i++] = buf; } else break; } ```
execvp is defined thus: ``` int execvp(const char *file, char *const argv[]); ``` Which precludes code such as this from being used: ``` const char* argv[] = {"/bin/my", "command", "here", NULL}; execvp(argv[0], argv); ``` Was this an accidental omission? Is it safe to const_cast around this? Or do some execvp i...
The POSIX spec says (http://pubs.opengroup.org/onlinepubs/009604499/functions/exec.html): Theargv[]andenvp[]arrays of pointers and the strings to which those arrays point shall not be modified by a call to one of the exec functions, except as a consequence of replacing the process image. I think the missing (or misp...
I have the following code, the struct declaration is before the main, so is the function declaration ``` struct stuff{ int sale_per_day[Kdays]; int max_sale; }; void set_max(); ``` and that part is in the end... ``` void set_max(struct stuff *point; int n = 0) { return; } ``` Now what exac...
It looks as if it just needs a comma instead of a semicolon: ``` void set_max(struct stuff *point, int n = 0) ```
I was asked a question in interview for sorting a double dimension array in O(n) time.How is it possible to do it in O(n).Can someone shed some light on it.. Thank you. Input: ``` 3 5 7 1 4 9 2 0 9 3 6 2 ``` Output ``` 0 1 2 2 3 3 4 5 6 7 9 9 ```
Don't know what did you actually mean by double dimension array, but there are sorting algorithms specific for some situations that can achieve O(n). An example of that isCounting sort, if you want to sort an array with 1000 integers in the range 1 to 1000, it can sort in O(n). EDIT:The fact that it's a multidimensio...
While trying to compile theMaze Generator/Solver in Cas present in rosettacode in Visual Studio 2010, I am facing issue during compilation. The following line ``` # define SPC " " wchar_t glyph[] = L""SPC"│││─┘┐┤─└┌├─┴┬┼"SPC"┆┆┆┄╯╮ ┄╰╭ ┄"; ``` is throwing an Error ``` 1>d:\projects\maze_cpp\maze_cpp\main.cpp(14)...
You need to escape the"s in the wide string literal: ``` wchar_t glyph[] = L"\"SPC\"¦¦¦-++¦-+++---+\"SPC\"?????? ??? ?"; ``` EDIT: I missed theSPCmacro (as already posted by Luchian and jrok): ``` #define SPC L" " wchar_t glyph[] = L"" SPC L"¦¦¦-++¦-+++---+" SPC L"?????? ??? ?"; ```
i have array unknown size i want to transfer to matrix[n][2].Example; ``` D[c]=1,2,3,4,5 D[c/2][2]= 1 2 3 4 5 0 ``` so if size of array odd i want add 0 last member of matrix.Here s my code but i dont know how to make 0 last member of matrix ``` if (c%2==1){c=c+1;} for(r=0; r<(c...
A possible solution would be to initialise the array to be all zeros: ``` int matris[4][4] = { 0 }; ``` Any not set during population would remain zero.
What is the direct alternative for thevsnwprintffunction on linux machines and what headers should be included to use it? Thanks for any advice
It depends on whatvsnwprintf()(sic)does and what is its parameter list. TheC99 Standarddescribesvswprintf()(in section 7.24.2.7). To use it you need to #include<stdarg.h>and<wchar.h>. The implementation should be in the Standard library.
I'm usingChan's FAT librarythat seems to provide a standard FAT filesystem API. The API doesn't seem to directly offer to list all the files in a given directory. What is the standard way to list all files in a directory given access to a standard FAT API? Is there a special file (some "directory table"?) that I can...
Have a look atf_opendirandf_readdir: The f_readdir function reads directory entries in sequence. All items in the directory can be read by calling f_readdir function repeatedly. When all directory entries have been read and no item to read, the function returns a null string into f_name[] member without any error. Wh...
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed4 years ago.Improve this question We need to write a C/C++ code that will check whether the memory allocated to the program...
If you are using the Linux/Unix based OS , you can involve the top utility ans see the difference.no need to reinvent the wheel. use this in your c code : ``` uint find_memory_usage() { sprintf(cmd, "/bin/top"); system(cmd); } ``` You can use exec family functions or system call as well for this. Thislinkon SO...
I'm trying to memset an array of ints that exist inside a structure: ``` typedef struct _xyz { int zList[9000]; } xyz; int dll_tmain(void) { xyz *Xyz = (xyz *) calloc(10, sizeof(xyz)); memset((&Xyz[0])->zList, 1, 9000); } ``` I've tried a lot of variations in the memset(), to no avail. Instead o...
Remember thatmemsetsets eachbyteof an array to the same value. So you are copying, to the first 9000 bytes of the array, the byte with value 1. Assuming 4 byte integers, that means you are assigning an int with value0x01010101. But, what's more, you are not assigning to the entire array, only the first 1/4 of it, agai...
I was debugging on a Single Board Computer, and I figured out that I never closed the ttyUSB in my program. Now the program will not get past the open() function. How can I manually close the line, or force it open? I would prefer not to shutdown the computer, and the USB device must remain in the SBC. The specific l...
At process termination the kernel automatically closes all filehandles. If the devices is still opened it means that the process is still running. Kill it.
I need to pass some arguments to my application,that include the - symbol. The problem is if I passgdb a.out -foo baa, the gdb understand that the arguments are for it, and not to my application. How to fix this?
gdb -q a.outinside gdb:run -foo baaTip: -q option for gdb suppresses the introductory copyright messages.
this is a simple question ... is there a way to convert astruct tm ct;to a long integer ? here's how my code look like: ``` struct tm ct; scanf("%d", &ct.tm_sec); scanf("%d", &ct.tm_min); scanf("%d", &ct.tm_hour); scanf("%d", &ct.tm_mday); scanf("%d", &ct.tm_mon); scanf("%d", &ct.tm_year);...
You can use themktime()function to convert astruct tminto atime_t, which is an integer value.
The subject says it - is there a reliable way to detect if a .lib static library (and a dynamic library also, if possible) was built against the debug version of MSVCRT? E.g. is there any import symbol that can be used to detect that? Basically I have an app that uses tons of dependency static libs, and at least one ...
for dll we can use dependsDependency Walker, if the dll depends on the MSVCRxxD.DLL it is linked with debug runtime. For more information seeUse Run-Time Library. If you have cygwin you can run for example strings xxx.lib | grep MSVCRT or strings xxx.dll | grep MSVCRT and see if the D version appears
``` { int *p=12; printf("%p",p); printf("\n%d",p); } ``` OUTPUT: 0000000C 12 Question: So is p assigned the address 0x0000000C? ``` { int *p=12; *p=22; } ``` But this one doesn't run. So what's actually happening?
``` int *p=12; ``` This declares a pointer and sets the address to which it points to12. ``` *p=22; ``` This de-references the pointer and writes 22 to theintat that memory address12. Since you did not allocate any memory and just set the pointer to point at a random address, it results in a runtime error. What i...
I am trying to run a simple RPC program which I have created using rpcgen. Its a simple factorial program. This is my first RPC program. The make works fine.Executables are also created. But when trying to run the executables, I get this error: ``` $sudo ./fact_server Cannot register service: RPC: Unable to recei...
First you check that portmapper is working or not, userpcinfoto check it. If you get any error then installportmap
I run a program with LD_PRELOADing a specific library. Like this. ``` LD_PRELOAD=./my.so ./my_program ``` How do I run this program withgdb?
Do the following. ``` gdb your_program (gdb) set environment LD_PRELOAD ./yourso.so (gdb) start ```
While trying to compile theMaze Generator/Solver in Cas present in rosettacode in Visual Studio 2010, I am facing issue during compilation. The following line ``` # define SPC " " wchar_t glyph[] = L""SPC"│││─┘┐┤─└┌├─┴┬┼"SPC"┆┆┆┄╯╮ ┄╰╭ ┄"; ``` is throwing an Error ``` 1>d:\projects\maze_cpp\maze_cpp\main.cpp(14)...
You need to escape the"s in the wide string literal: ``` wchar_t glyph[] = L"\"SPC\"¦¦¦-++¦-+++---+\"SPC\"?????? ??? ?"; ``` EDIT: I missed theSPCmacro (as already posted by Luchian and jrok): ``` #define SPC L" " wchar_t glyph[] = L"" SPC L"¦¦¦-++¦-+++---+" SPC L"?????? ??? ?"; ```
i have array unknown size i want to transfer to matrix[n][2].Example; ``` D[c]=1,2,3,4,5 D[c/2][2]= 1 2 3 4 5 0 ``` so if size of array odd i want add 0 last member of matrix.Here s my code but i dont know how to make 0 last member of matrix ``` if (c%2==1){c=c+1;} for(r=0; r<(c...
A possible solution would be to initialise the array to be all zeros: ``` int matris[4][4] = { 0 }; ``` Any not set during population would remain zero.
What is the direct alternative for thevsnwprintffunction on linux machines and what headers should be included to use it? Thanks for any advice
It depends on whatvsnwprintf()(sic)does and what is its parameter list. TheC99 Standarddescribesvswprintf()(in section 7.24.2.7). To use it you need to #include<stdarg.h>and<wchar.h>. The implementation should be in the Standard library.
I'm usingChan's FAT librarythat seems to provide a standard FAT filesystem API. The API doesn't seem to directly offer to list all the files in a given directory. What is the standard way to list all files in a directory given access to a standard FAT API? Is there a special file (some "directory table"?) that I can...
Have a look atf_opendirandf_readdir: The f_readdir function reads directory entries in sequence. All items in the directory can be read by calling f_readdir function repeatedly. When all directory entries have been read and no item to read, the function returns a null string into f_name[] member without any error. Wh...
I've come across some C code that I don't quite understand. The following compiles and runs just fine. 1) Why can I cast a char* to a struct* and 2) is there any advantage to using this idiom instead of a void* ? ``` struct foo { int a; int b; char *nextPtr; }; . . . // This seems wrong char *charPtr = ...
You can convert between pointer types because this is the flexibility the language gives you. However, you should be cautious and know what you are doing or problems are likely.No. There is an advantage to using the property pointer type so that no conversion is needed. If that isn't possible, it doesn't really matter...
I have this simple program ``` #include <stdio.h> int main(void) { unsigned int a = 0x120; float b = 1.2; printf("%X %X\n", b, a); return 0; } ``` I expected the output to be ``` some-value 120 (some-value will depend on the bit pattern of `float b` ) ``` But I see ``` 40000000 3FF33333 ``` Why is the value...
Firstly, it's undefined behaviour to pass arguments toprintfnot matching the format specifiers. Secondly, thefloatis promoted todoublewhen passed toprintf, so it's eight bytes instead of four. Which bytes get interpreted as the twounsignedvalues expected by theprintfformat depends on the order in which the arguments ...
Constraint : AS to be in C/C++ SO basically, the idea is to create my own window application (on a Linux environment) and load up (play) my swf file. Pretty "simple" question. I was thinking to go with Xlib without widgets (so no Qt, GITK, etc.) and I'm kind of wondering if any libraries exist to open swf... I have ...
Take a look at GameSWF http://en.wikipedia.org/wiki/GameSWF
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. I'm writing a program that receives...
There's no way to look at a C array and tell how many elements it contains, so you'll need to keep track. In fact, you likely need to keep track of 2 things: (1) how large the array you've created is (the maximum number of words you can handle), and (2) how many words you've actually seen so far.
I understand that casting from an unsigned type to a signed type of equal rank produces an implementation-defined value: C99 6.3.1.3:Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised. This means I don...
As you say in your question the result isimplementation-defined or an implementation-defined signal is raised- i.e. depends on the platform/compiler what happens.
I use fork()/exec()/wait() rather than system() when the command has user input as some of its arguments so the user can't put something like... ``` &rm -rf /home/* && echo HAHA ``` ... as an argument. I'm assuming popen is as dangerous as system() because it takes a single string and not a list of strings like the...
The safe way is to set up the necessary pipes yourself, using straightpipe()calls directly. That's whatpopen()does under the hood, but it also invokes the shell in order to run the child process. Skipping that step should make it safer.
This is just something I was wondering. Well here goes, Say I declare a variable in a function, I pass this variable as a pointer to another function. What happens with this variable when the first function (where the variable is declared) ends? Does it stay on the stack or does it get removed when the function ends? ...
When the function you define a variable returns the variable is destroyed,unlessyou declared it static. Check storage classes in C. Here is a pointer:http://aelinik.free.fr/c/ch14.htm
``` int a[2]={1210,15}; printf("%d",a[33] ); ``` OUTPUT ``` 1073828132 ``` Why it's not throwing error when i'm trying to printa[33]even though the array element doesn't exist
Because C does not do bounds-checking. You will just be reading an arbitrary location in yourcall stack.
In which section is constant volatile variable stored in c.? In micro-controllers we should put such kind of variables in RAM. Right?
Volatilehas noting to do with where the variable is stored. It just tells the compiler to read the variable from memoryevery timeto avoid any optimization that compiler might perform for that variable.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. I'm writing a program that receives...
There's no way to look at a C array and tell how many elements it contains, so you'll need to keep track. In fact, you likely need to keep track of 2 things: (1) how large the array you've created is (the maximum number of words you can handle), and (2) how many words you've actually seen so far.
I understand that casting from an unsigned type to a signed type of equal rank produces an implementation-defined value: C99 6.3.1.3:Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised. This means I don...
As you say in your question the result isimplementation-defined or an implementation-defined signal is raised- i.e. depends on the platform/compiler what happens.
I use fork()/exec()/wait() rather than system() when the command has user input as some of its arguments so the user can't put something like... ``` &rm -rf /home/* && echo HAHA ``` ... as an argument. I'm assuming popen is as dangerous as system() because it takes a single string and not a list of strings like the...
The safe way is to set up the necessary pipes yourself, using straightpipe()calls directly. That's whatpopen()does under the hood, but it also invokes the shell in order to run the child process. Skipping that step should make it safer.
This is just something I was wondering. Well here goes, Say I declare a variable in a function, I pass this variable as a pointer to another function. What happens with this variable when the first function (where the variable is declared) ends? Does it stay on the stack or does it get removed when the function ends? ...
When the function you define a variable returns the variable is destroyed,unlessyou declared it static. Check storage classes in C. Here is a pointer:http://aelinik.free.fr/c/ch14.htm
``` int a[2]={1210,15}; printf("%d",a[33] ); ``` OUTPUT ``` 1073828132 ``` Why it's not throwing error when i'm trying to printa[33]even though the array element doesn't exist
Because C does not do bounds-checking. You will just be reading an arbitrary location in yourcall stack.
In which section is constant volatile variable stored in c.? In micro-controllers we should put such kind of variables in RAM. Right?
Volatilehas noting to do with where the variable is stored. It just tells the compiler to read the variable from memoryevery timeto avoid any optimization that compiler might perform for that variable.
I tried this but it's not working for me: ``` char * remove_nl(char * newstr) { newstr = strdup(newstr); newstr[strlen(newstr)-1] = '\0'; return newstr; } ```
What you have now is fine, except: you have to make sure thatnewstrpoints to a valid string;check thatstrlen(newstr) > 0;check thatnewstr[strlen(newstr)-1]is indeed a newline before wiping it;make sure the callerfree()s the returned string.
I want to read numbers(integer type) separated by spaces usingscanf()function. I have read the following: C, reading multiple numbers from single input line (scanf?)how to read scanf with spaces It doesn't help me much. How can I read numbers with space as delimiter. For e.g. I have following numbers as input2 5 7 ...
I think by default values read by scanf with space/enter. Well you can provide space between '%d' if you are printing integers. Also same for other cases. ``` scanf("%d %d %d", &var1, &var2, &var3); ``` Similarly if you want to read comma separated values use : ``` scanf("%d,%d,%d", &var1, &var2, &var3); ```
I am new to programming, and so I do encounter basic issues. In the program I am building, I need to clear the screen at a certain point, but it does not acceptclrscr();orsystem("cls");what are other options available?? I have includedstdio.h&conio.h. If it helps, the compiler I am using is Visual studio 2010.
Visual Studio removed "common" conio.h functions, like clear screen, a long time ago. system() is in stdlib.h if you want to use it. However, if you want to do serious terminal output on Windows, check out something like this:http://www.projectpluto.com/win32a.htm
I tried making use of some OpenGL-functions in Eclipse C/C++. some "standard" functions as GlClear are recognized by eclipse, others like glBindBuffer() and glEnableVertexAttribArray() aren't. They are just underlined in red. However compilation is succesful, there's just this disturbing underlining.. I have linked ...
Try right-click your project and in the popup menu: Index > Rebuild
How to make multi line preprocessor macro? I know how to make one line: ``` #define sqr(X) (X*X) ``` but I need something like this: ``` #define someMacro(X) class X : public otherClass { int foo; void doFoo(); }; ``` How can I get this to work? This is only an example, the real macr...
You use\as a line continuation escape character. ``` #define swap(a, b) { \ (a) ^= (b); \ (b) ^= (a); \ (a) ^= (b); \ } ``` EDIT: As @abelenky pointed out in the comments, the\charactermust be the last character on ...
I come across the term 'decay' every now and then, for example when arrays passed in as function parameters decays to a pointer, or when functions decay to a function pointer. If I was writing a c compiler, where would I find the term 'decay' officially defined and where would all the cases of it occuring be documente...
The official terminology in the standard for this is "lvalue conversion". In the current version of the standard (C11) you find this in 6.3.2.1 p3.
I am using a Broadband Router on which multiple pcs use the same shared ip as the public ip. how can some other remote client get a specific IP address to connect to me? I was developing a Client/Server Chat Program using C. Thanks for considering.
They cannot. The broadband router is the only one with a public IP address. The usual solution to this problem is to have the router forward a specific port to one of your NAT'd internal machines. If that's not sufficient, you could investigate "hole punching" andSTUN.
I was checking Beej's guide toIPCand one line of code took my attention. In the particular page, the while loop inspeak.chas two conditions to checkwhile (gets(s), !feof(stdin)). So my question is how is this possible as I have seen while look testing only one condition most of the time. PS: I am little new to thes...
The snippet ``` while (gets(s), !feof(stdin)) ``` uses thecomma operator, first it executesgets(s), then it tests!feof(stdin), which is the result of the condition. By the waydon't use gets, it's extremely unsafe. Be wary of sources using it, they probably aren't good sources for learning the language. The code `...
I'm trying to print a pointer of char type in c , i'm able to see the values and it's memory address as below ``` char *ptr = "I am a string"; printf("\n value [%s]\n",ptr); printf("\n address [%d]\n",&ptr); ``` But when i print directly the pointer as below, it's showing error asSegmentation fault ``...
*ptris a char, not a char pointer, and%sexpects a char pointer (to a C-string). When treating the char as a pointer,printftries to access an invalid memory address, and you get a segmentation fault.
I have to load colours value from *.png file in c. Something like imread in matlab. I learned png file construction, tried to open file as binary and write to matrix, but I probably done something wrong. I alao tried to search, but I couldn't find suitable library. Any advice how can I do that or which library should...
You're going to need to decompress the zlib compression on the PNG first (if there is any) before you can get to the raw color values. The easiest way to do this is through the freelibpng. You will findmanyexampleshereand elsewhere on how to do just that.
I'm trying to get the body of a Mail with MailCore but it's always empty. My code is ``` CTCore *folder = [[CTCorefolder alloc] initWithPath:@"INBOX" inAccount:account]; for( CTCoreMessage *msg in [folder messageObjectsFromIndex : 0 toIndex:10] ){ if([msg.subject isEqualToString:@"test")]){ // no pb here,...
You must callfetchBodyon each message in order to retrieve it from the server.
While compilingglibc 2.11, I get the following error. Any idea how to solve this. ``` In file included from ../sysdeps/unix/sysv/linux/syslog.c:10: ../misc/syslog.c: In function ‘__vsyslog_chk’: ../misc/syslog.c:123: sorry, unimplemented: inlining failed in call to ‘syslog’: function body not available ../misc/syslog...
Apparently, this is aknown problem with buildingglibcon Ubuntu. In essence: glibcdoes not build with_FORTIFY_SOURCEenabled, and Ubuntu compiles stuff with-D_FORTIFY_SOURCE=2. You need to disable this by undefining_FORTIFY_SOURCE. i.e.append-U_FORTIFY_SOURCEto yourCFLAGS.
Canglibcbe compiled into one object file which can then be linked to any program. The main purpose is portability here. Because I don't require to install dynamic libraries this way. Can this be done? If so, how?
You can compileglibcto.afiles which can be linked into a static executable. The static libraries are built by default.
I am thinking of developing an application using Vala. I would like to write unit tests for my code - but I have not (as yet) found anyactively maintainedunit test frameworks for Vala (e.g. Valadate). Could anyone recommend a unit testing framework for use with Vala? As an aside, given the relative 'newness' of Vala...
There is a simple unit test facility already built into Vala:GLib.Test. Unity, the user interface for the Ubuntu desktop, is partly written in Vala (the rest is C++.)
I want to write a caculator that waits for the user to give it orders.for example:add 1 2sub 12 4What is the best way to find out what order the user gave and the token(s) given after that order?I'm writing my project in C on Windows and it's Console-Based.
You could usescanf ``` #include <stdio.h> int main () { char cmd[1024]; int a, b; printf ("Enter input: "); scanf ("%s %d %d",cmd, &a, &b); if(strcmp(cmd,"add")==0) { printf ("Result: %d\n", a + b); } else if(strcmp(cmd,"sub")==0) { printf ("Result: %d", a - b); } else ...
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen...
``` int add(int x, int y) { std::vector<int> v(x); std::vector<int> u(y); for(auto& n : u) { v.push_back(n); } return v.size(); } ```
I was looking into some old code in my product and i found following code. ``` #include <stdio.h> #include <string.h> int main ( int argc, char **argv) { const char *str = "abcdefghi"; int value = strcmp(str, "abcdefghi") == 0; } ``` What is the purpose ofint value = strcmp(str, "abcdefghi") == 0;of such cod...
It initializesvaluewith the result ofstrcmp(str, "abcdefghi") == 0which will be0or1depending on whatstrcmpreturns.
I have a doubt in pointers manipulation... ``` main() { int x=10; // extra line added... char *p=x; printf("%d", &p) printf("%d", &p[0]); printf("%d" , &p[1]); } ``` This code gives output Address of 10.. 10 11 how are the last two outputs are coming.. Can anyone explain it to me ..? Code changed...
This is Undefined Behavior.The pointer needs to point to something valid before some value can be added to that location. ``` char a = 10; char *p = &a; ```
How is the Custom Run sheet Program Input field used inCodeRunnersay for a C or Objective-C program?
The text entered in the Program Input text box will be sent to your program/script through the standard input. You can access the input in the same way that you would access the standard input using your language of choice. In C, you'd use the standardfread,fgets,fgetcetc functions. The following example will echo t...
I have many native libraries with a C API that contain functionality I want to use in a web app. What choices are out there (frameworks/languages) for doing this?
To call native C functions from C#, including ASP.Net, use P/Invoke. It exists for exactly that purpose. Tutorial Here:http://msdn.microsoft.com/en-us/library/aa288468(v=VS.71).aspx
I am currently working on a simple server implemented in C. Processing jpg files works fine, btu png's give me a segmentation fault. I never get past this chunk of code. Why this might be? ``` fseek (file , 0 , SEEK_END); lSize = ftell (file); rewind (file); ``` Thanks.
It's far more likely that you were accessing those arrays in a problematic fashion. Check the logic in your buffering code. Make sure you have your buffer sizes #define'd in a central location, rather than hardcoding sizes and offsets. You made it quit crashing, but if you missed an underlying logic error, you may run...
I'm trying to use a third-party .so, P4API.so, that calls clock_gettime defined in librt.so and would like users of my script not to have to set LD_PRELOAD. So in theinit.py file, I have: ``` import ctypes librt = ctypes.cdll.LoadLibrary('librt.so') ``` This loads the library fine, but running the script still emit...
You need to load it with ``` ctypes.CDLL('librt.so', mode=ctypes.RTLD_GLOBAL) ``` in order to make it available to other libraries.
If I write the code like this below? ``` int arr[] = {6, 7, 8, 9, 10}; int *ptr = arr; *(ptr++)+= 123; ``` what's the elements in the arr[] now? I originally thougt the arr[] now should be {6, 130, 8, 9, 10}, but actully the result is {129, 7, 8, 9, 10}, I don't know why? In my opinion, ptr++ is in the bracket, so...
Thevalue ofptr++is the value ofptrbefore any increment (the side-effect is incrementingptrat some time during the evaluation of the expression). That is the value that is dereferenced in*(ptr++). If you dereferenceptrin a subsequent expression, it points to the next element, the one with value7.
I did this for cscope to add Java capability ``` find ./ -name *.java > cscope.files ``` Yet when I do this and suppose I want to look for a symbol , I get all references to this symbol in java only. I also want it to display the references in the C code which is present in this project. no it only shows java refere...
Well it looks like you're only finding files with the .java extension for a start: How about: ``` find . -iname '*.java' -or \\ -iname '*.cpp' -or \\ -iname '*.c' -or \\ -iname '*.h' -or \\ > cscope.files ```
I want to draw a model withLWJGLand I know that on calling eachglVertexmethod, aJNIcall occurs, that is time consuming. Since I have the model in a file, I want to use just oneJNIcall (add a native method toLWJGLlibrary), and at the native side, get my model vertices from the file (using c language) and draw them all ...
Use Vertex Buffer Objects to store your vertex data, and make calls to draw as many vertices/triangles is practical with just one call toglDrawArrays,glDrawElementsor similar. This pageexplains how to use them in LWJGL. Note that the LWJGL version of the OpenGL docs is rather lacking. Check theOpenGL official sitef...
I need to run a command,but that don't lock my application until exit of it,like dosystem()function.
Usefork()to create a new process, andexec*()to replace it with a new application.
I'm using command line param Fo, command line is like this: ``` file1.c /ZI /nologo /W3 /WX- /Od /Oy- /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /Gm /EHsc /RTC1 /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd /analyze- /errorReport:queue /bigobj /FdDebug\vc100.pdb /FoDebug\ /FaDebug\ ``` But some ...
Those are files produced by thelinker. You'll need to run it separately or use the /link compiler option so you can control its output. Use the /OUT option to set the .exe and .ilk locations, the /PDB option to set the .pdb location.
``` #include <stdio.h> #include <string.h> int main() { char greeting[]="\nHello World!\n"; int a; for(int i=0; i<strlen(greeting); i++) greeting[i]^=111; for(int i=0; i<strlen(greeting); i++) greeting[i]^=111; printf("%s\n",greeting); scanf("%d",&a); } ``` Output: ``...
Because'o'is ASCII code 111, and XORing 111 with 111 yields 0,NUL, and terminates your string. Once this happens (even in the first loop, since you're evaluating it each time through the loop),strlenreports the string is much shorter, and the loops stop. Saving the string length before going through the XORs will sa...
I need to use pthreat but I dont need to pass any argument to the function. Therefore, I pass NULL to the function on pthread_create. I have 7 pthreads, so gcc compiler warns me that I have 7 unsued parameters. How can I define these 7 parameters as unused in C programming? If I do not define these parameters as unuse...
You can cast the parameter tovoidlike this: ``` void *timer1_function(void * parameter1) { (void) parameter1; // Suppress the warning. // <statement> } ```
in C, I have to send a bunch of datas with tcp/ip (~6.5mo) I'm using the "classic" send(). Do you think it's a good idea to give to the function the whole size of data to send in one part or should I prefer the chunk way (slices of, for example, 64ko...)
Give it the full size, and just call it again with the rest of the buffer (according to the return value). You deal with your logic, let the OS deal with the send logic.
I want to draw a model withLWJGLand I know that on calling eachglVertexmethod, aJNIcall occurs, that is time consuming. Since I have the model in a file, I want to use just oneJNIcall (add a native method toLWJGLlibrary), and at the native side, get my model vertices from the file (using c language) and draw them all ...
Use Vertex Buffer Objects to store your vertex data, and make calls to draw as many vertices/triangles is practical with just one call toglDrawArrays,glDrawElementsor similar. This pageexplains how to use them in LWJGL. Note that the LWJGL version of the OpenGL docs is rather lacking. Check theOpenGL official sitef...
I need to run a command,but that don't lock my application until exit of it,like dosystem()function.
Usefork()to create a new process, andexec*()to replace it with a new application.
I'm using command line param Fo, command line is like this: ``` file1.c /ZI /nologo /W3 /WX- /Od /Oy- /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /Gm /EHsc /RTC1 /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd /analyze- /errorReport:queue /bigobj /FdDebug\vc100.pdb /FoDebug\ /FaDebug\ ``` But some ...
Those are files produced by thelinker. You'll need to run it separately or use the /link compiler option so you can control its output. Use the /OUT option to set the .exe and .ilk locations, the /PDB option to set the .pdb location.
``` #include <stdio.h> #include <string.h> int main() { char greeting[]="\nHello World!\n"; int a; for(int i=0; i<strlen(greeting); i++) greeting[i]^=111; for(int i=0; i<strlen(greeting); i++) greeting[i]^=111; printf("%s\n",greeting); scanf("%d",&a); } ``` Output: ``...
Because'o'is ASCII code 111, and XORing 111 with 111 yields 0,NUL, and terminates your string. Once this happens (even in the first loop, since you're evaluating it each time through the loop),strlenreports the string is much shorter, and the loops stop. Saving the string length before going through the XORs will sa...
I need to use pthreat but I dont need to pass any argument to the function. Therefore, I pass NULL to the function on pthread_create. I have 7 pthreads, so gcc compiler warns me that I have 7 unsued parameters. How can I define these 7 parameters as unused in C programming? If I do not define these parameters as unuse...
You can cast the parameter tovoidlike this: ``` void *timer1_function(void * parameter1) { (void) parameter1; // Suppress the warning. // <statement> } ```
in C, I have to send a bunch of datas with tcp/ip (~6.5mo) I'm using the "classic" send(). Do you think it's a good idea to give to the function the whole size of data to send in one part or should I prefer the chunk way (slices of, for example, 64ko...)
Give it the full size, and just call it again with the rest of the buffer (according to the return value). You deal with your logic, let the OS deal with the send logic.
I have the code below. I would like to write all new data line by line, how can I do it? My code works fine but it writes the data next to each other. ``` //////////////////////////////////// char timedate[13]; char USERID[] ="100050"; char *p; p=fetch_time(); //the function returns a string (char[13]) strcpy(timeda...
You create your string without a linebreak: ``` sprintf(log_sensor_event, "%s %s",timedate, USERID); ``` Try this: ``` sprintf(log_sensor_event, "%s\n %s",timedate, USERID); ```