question
stringlengths
25
894
answer
stringlengths
4
863
I want to get the list of all mapped pages (allocated memory) in a Linux Process at runtime. How can I do that?
From inside the process, on Linux, you can read and parse/proc/self/maps; trycat /proc/self/mapswhich will show you the memory map of the process running thatcat From another process, for the map of the process of pid 1234, you can read/proc/1234/maps And there is also/proc/self/smapsetc. The Linux specificdladdrfu...
This question already has answers here:Closed11 years ago. Possible Duplicate:Meaning of U suffix I'm going through code that has a bunch of defines that look like: #define HEX_NUMBER (0x000000FFu) What is the trailing u? I've tried compiling with and without it and I don't see any difference.
Appendinguto any integral constant makes the compiler interpret it as unsigned.
What is the easiest and simplest way to create a decrementing timer in seconds? Im using an 8bit microcontroller and cannot use float points or intensive processes. I need a very efficient timer.
time(2)is a standard C function for obtaining the current time in seconds since the epoch (midnight on January 1, 1970 UTC). To make a decrementing timer, you could do something like this: ``` time_t startTime = time(NULL); time_t timerDuration = 10; // 10 second timer time_t endTime = startTime + timerDuration; w...
I have been asked this question once or twice in interviews. I am not sure whether it's possible or not. Maybe structures in C are a way out? Can anyone elaborate on this further?
If the two values are inside a structure, then you can use the function's return value instead of passing by reference: ``` struct twoNumbers { int first; int second; }; struct twoNumbers swapNumbers(struct twoNumbers src) { int tmp = src.first; src.first = src.second; src.second = tmp; return src; } /*...
Using x86 platform , I want to start my application named myapp through this method:execl("./myapp","");It's OK! But failed when I'm using ARM platform + embedded linux. Why ? Any help will be appreciated. Thanks in advance.
Your invocation is wrong:execl()'s argument list MUST be terminated withNULL. The fact that it works at all on x86 is a miracle ;)
1) Is it possible for an android application to share UID with an non-android application written in C? 2) Is it possible to add an Android application to a group? Thanks!!
1) Is it possible for an android application to share UID with an non-android application written in C? Do you mean native code bundeled with your app (NDK) then yes, to share UID with someting in the platform NO, this is part of the Android security model. 2) Is it possible to add an Android application to a grou...
example: ``` int foo(void) { static volatile int data; data = 0xaaa; /* something to assure cache flushing */ if (data == 0xaaa) return 1; return 0; } ``` the question is what can assure that flushing. thanks.
VxWorks provides cacheLib which enables you to perform certain cache operations, flushing as well. You'll have to check the reference manual for your Version of VxWorks. Anyway, from version 5.4: ``` STATUS cacheFlush ( CACHE_TYPE cache, /* cache to flush */ void * address, /* virtual address */ siz...
Lets say I have a 32bbp pixel array, but I am using only the blue channel/component from the pixels. I need to upload this pixel array to a texture in a grayscale/luminance format. For example if a have a color (a:0,r:0,g:0,b:x) it needs to become (0,x,x,x) in the texture. I am using Opengl v1.5
OpenGL up to version 2 had the texture internal format GL_LUMINANCE, which does exactly what you want. In OpenGL-3 this was replaced with the internal format GL_R (GL_RED), which is a single component texture. In a shader you can use a swizzle like ``` gl_FrontColor.rgb = texture().rrr; ``` But there's also the opt...
Using visual studio, is there a way to define all the function of the winapi to treat all the strings as UNICODE?
The MS libraries are organized by macros. Use the name of the API methods without the appende "A" or "W".Wrap your string definitions in _T() macro. By doing this way defining "_UNICODE" in Preprocessor will build unicode build. ``` CreateFile(_T("C:\out.txt"),GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMA...
My first programming language learned was Actionscript, and I'm having a hard time understanding pointers and references. What is the purpose of pointers when I can just use references? I read one use case for pointers is when giving a large variable to another function instead of copying it, but can't I just add a &...
There is no difference in a pointer and the &-Construction. A pointer is a variable which stores the value of &... ``` int a; int *b = &a; ```
I am trying to port tcmalloc to uclibc. Tcmalloc has a definition for sbrk function, which in turn calls the __sbrk from libc. Uclibc on the other hand does not have __sbrk function, but has sbrk. Any ideas about how I can call uclibc sbrk from tcmalloc sbrk?
sbrkis a (old)system call, but most memory allocators are built abovemmap. See alsothis question You should use the syscall, not emulate it. And I would prefer usingmmap, notsbrk Doing a system call (usuallymmap) is the only way to get more memory from thelinux kernel. From the application's (or library's) point of...
ERRORS: 1) _counter already defined error 2) one or more multiply defined symbols found structure.h: ``` extern int counter = 0; ``` List.c: in one method i increment the counter. ``` ++counter; ``` in another method i set the counter to a value within an object llist->taskID = counter; Messages.c: use count...
Your header filestructure.hshould only have a declaration (not a definition), like: ``` extern int counter; ``` One (only) of the implementation files, conventionally the*.cfile containingmain, should have a definition like ``` int counter = 0; ```
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. How to use decimal point covert t...
Use printf with some good filters. Please see this example: http://stahlforce.com/dev/index.php?tool=csc02
This question already has answers here:Closed11 years ago. Possible Duplicate:Double Negation in C++ code While reading one code I read: ``` flush = ! !(flags & GST_SEEK_FLAG_FLUSH); ``` I am not getting what does!!mean here . what does this sentence do? EDIT: I got it its adouble-negative.trick to convert non-b...
It's a double-negative. It's a way of converting an otherwise-non-bool expression (such asflags & GST_SEEK_FLAG_FLUSH) to abool. I personally prefer: flush = (flags & GST_SEEK_FLAG_FLUSH) != 0;
Currently, I'm working on TCP client/server implementation in C. In that, I found that I can give any random number as a port number for my PC. Is it correct procedure? Or is there any standard port number for my PC?
I don't know the standard, but I say it's not. At least, I don't like to do it like that. You can check occupied ports by parsing the outputs of programs likenetstatand avoid using those. You can also use the method that attempts connecting on one port, and upon failure, tries another port. Unless you're really reall...
Recently I experienced very strange situation by my C program. Usually my program works fine, but if I add just a few lines to check elapsed time, the result changes. The code of which result changed is: ``` while (!feof(pfInputFile) && (c = fgetc(pfInputFile)) != EOF){ for(i = 1 ; i < SEED_SIZE ; i++){ pcSe...
Not enough details but I'll take a wild guess. You returned a pointer to a local variablepcSeq. Then in another function you calltime(&start)with the result that thestartvariable now shares the same stack address thatpcSeqhad, so it got overwritten.
i am trying to create a Model FAT16 file system in a file with the ability to create, view, delete and copy files and directories,but i new to programming anyone with ideas on how i can go about it?i want something like this below ``` type TFileRec = Packed Record ID: WORD; //id of item ParID: WORD; //pare...
Look atCompound File implementationby SO user Primoz Gabrijelcic. It is not FAT16, but very close to what you are looking for.
So when a child dies parent getsSIGCHLDbut if parent dies before doing wait(), the child is reparented toinit. At this point in time the child is azombiei.e.<defunct>. What happens next? Doesinitdo wait() on that child? if yes, when does it do it? Any guarantees regarding time-limit?
Yes,initwill immediately reap all children. If you make a process which ignoresSIGCHLDand accumulates many zombies you can get rid of them by killing that parent via the mechanism you describe. For reference here is the main loop ofinitwhile in multi user mode.requested_transitionis set by signallinginit(e.g. the cl...
I am going through some examples in a book I have and I have come to something I've never seen before nor understand: ``` scanf("%d-%d-%d-%d-%d", &prefix, &group, &publisher, &item, &check_digit); ``` This code is part of a program that asks the user to enter their ISBN number of a book and later on breaks down the ...
"Pattern matching". If the input doesn't fit the specified pattern (also called format), it fails. So if you input anything else thanINT-INT-INT-INT-INT(whereINTis a placeholder for an integer you input), the input would be considered invalid.
I know that it can be either of these. But I always see that the child executes first on my UNIX terminal. Also, why don't the parent and child execute in parallel. They seem to be executing serially. Is this because they share the same terminal?
In general, nothing can be said about the relative order of their execution. Now, let's consider your specific problem. If: both processes take a non-trivial amount of time to run, andyou're saying that one runs to completion before the other makesanyprogress, andthere are unused CPU cycles, andthis happens every ti...
sys_errlist is indexed by errno and contains the appropriate error message. Where can I see the contents of this list?
Probably in some system header file included somehow by<errno.h>. If you want to print its full content you can easily do it with a small program: ``` #include <errno.h> #include <stdio.h> int main() { for(int i=0; i<sys_nerr; i++) printf("sys_errlist[%d] = \"%s\"\n", i, sys_errlist[i]); return 0; } ...
In real world cube root for a negative number should exist:cuberoot(-1)=-1, that means(-1)*(-1)*(-1)=-1orcuberoot(-27)=-3, that means(-3)*(-3)*(-3)=-27 But when I calculate cube root of a negative number in C usingpowfunction, I getnan(not a number) ``` double cuber; cuber=pow((-27.),(1./3.)); printf("cuber=%f\n",cu...
7.12.7.1 Thecbrtfunctions Synopsis ``` #include <math.h> double cbrt(double x); float cbrtf(float x); long double cbrtl(long double x); ``` Description Thecbrtfunctions compute the real cube root ofx. If you're curious,powcan't be used to compute cube roots because one-third is not expressible as a floating-poi...
This question already has answers here:Closed11 years ago. Possible Duplicate:Is this undefined C behaviour? ``` #include<stdio.h> int main() { int a=5; printf("%d %d %d",a++,a++,++a); return 0; } ``` Output: In gcc: ``` 7 6 8 ``` In TURBO C: ``` 7 6 6 ```
Because the order of evaluation of arguments to a function isunspecifiedand may vary from compiler to compiler. An compile may evaluate function arguments from:left to right orright to left orin any other pattern. This order is not specified by the C standard. Reference: C99 Standard 6.5 "The grouping of operators...
I know that I am asking an incredibly low level question, but I am unfamiliar with C and am trying to convert an expression to Objective-C. What does this mean? ``` double (*x)[2] ``` Thanks.
With a semicolon at the end, it declares and defines a pointer (namedx) to a array of 2 doubles. If it's a function (or method) argument, its type is the same: a pointer to an array of 2 doubles.
I am trying to share a workspace in Eclipse. To test it I copied my current workspace to a different directory. Then when eclipse loads it pops up a dialog box to select a workspace. When I changed the workspace to the one I copied it did not work. It did not load the workspace I copied and loaded the default scree...
I solved this by exporting a project archive. Then importing the project as an archive in a new workspace.
In my signal.h file I have added a signal handler like this: ``` #define SIG_WPG ((__sighandler_t)3) ``` and then implemented it in signal.c like this: ``` if (ka->sa.sa_handler == SIG_WPG) { unsigned long ul_cr2 = current->tss.cr2; unsigned long ul_eip = (unsigned long) regs->eip int ul_cr2...
You can use thesignal()method to register a callback for that exception: ``` //callback prototype void Handler(int sig); //register the callback for the specific signal signal(SIGSEGV,&Handler); ```
I am unable to allocate memory using the following code: ``` int *h_VC = (int *)malloc(sizeof(int)*SIZE); //SIZE is 19200 if(h_VC==NULL) { printf("Memory Not avaialble"); } ``` My code uses the above block in a while loop and is run several times. I have 8GB memory. I am monitoring the free memory at the same time...
Anything could be the problem. Replace theprintfwith ``` perror(""); ``` to get a hint.
Looking for a way to speed up reading and processing a large text file (basically csv; stream_lf). Should I bypass RMS? Solution may be asynchronous or synchronous. Current implementation is synchronous, but is too slow. Implementation is in HP Pascal, and using the pascal run-time library (OPEN/READLN/EOF/CLOSE). ...
For seqeuntial files: Take a look into the WASD or VWCMS code (look athttp://www.vsm.co.au/wasd). I know these bypass RMS as well in favour of speed for web services, but I don't know in whar sources that is done. For relative files, take sequence into account. Records could be non-exixtant (empty?) For indexed files:...
The standard predefined macro__FILE__available in C shows the full path to the file. Is there any way to shorten the path and get just the filename? I mean instead of ``` /full/path/to/file.c ``` I see ``` to/file.c ``` or ``` file.c ```
Try ``` #include <string.h> #define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__) ``` For Windows use '\\' instead of '/'.
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed11 years ago.Improve this question Having involved in C++ projects for more than ten years, it is really a big question for me that why Objective-C has been ...
There is no philosophy per sé, Apple bought Next Computer and their Operating System NeXTSTEP, which provided an objective-c API. Mac OS X is based on on the NeXTSTEP system, and in turn, iOS is based on OS X, so it's a natural progression. This also explains why a whole bunch of classes start with NS.
I am New to audio programming.I want to create small application which is capable of playing and gives volume control . I am using alsa-lib. I want to know what is the purpose of switch (ex.Master Playback switch), enum in mixer elements and what value should i set to those switchs . Please suggest me some tutorial ...
Just collecting some here, that have example code: ALSA Programming HOWTO v.1.0.0 [alsamodular.sourceforge.net]A tutorial on using the ALSA Audio API [equalarea.com]2002A close look at ALSA [volkerschatz.com]ALSA API - Sample Programs With Source Code By Aquiles Yanez2005Introduction to Sound Programming with ALSA | ...
I've been tasked with recoding a MATLAB script into C or C++, and I'm having a little difficulty wrapping my head around this filter function (filter(a, b, x)). Does anyone know of a simple way to do this, or an existing C library that accomplishes the same thing? Thanks!
Just implement the filter function as describedhere. This resembles just a tapped delay-line filter, wherebandaare coefficients andxis the input data: ``` a[1]y[n] = b[1]x[n]+b[2]x[n-1]+...+b[N]x[n-B+1]-a[2]y[n-1]-...-a[N]y[n-N+1] ``` You only have to take care about not-yet-existing indices, which are denoted by th...
How to swap the nibble bit positions of a number? For example: 534, convert it into binary, the rightmost 4 bits has to be interchanged with the leftmost 4 bits and then make a new number with that. Anyone know how to do this?
Sean Anderson's bit twiddling guidehas the following: ``` // swap nibbles ... v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4); ``` under the entry forReverse an N-bit quantity in parallel in 5 * lg(N) operations.
How do you write native (C/C++) code with Libgdx that works for Android and desktop? Thanks.
According to their github projectlibgdx is a "Cross-platform Java game development framework based on OpenGL ES". I've just searched for "libgdx with c++" and ended up at theirmain sitewhich says it's written in Java/C++/C — but that doesn't mean it's available as a C/C++ library, and I can't see anything to that effe...
I am trying to share a workspace in Eclipse. To test it I copied my current workspace to a different directory. Then when eclipse loads it pops up a dialog box to select a workspace. When I changed the workspace to the one I copied it did not work. It did not load the workspace I copied and loaded the default scree...
I solved this by exporting a project archive. Then importing the project as an archive in a new workspace.
In my signal.h file I have added a signal handler like this: ``` #define SIG_WPG ((__sighandler_t)3) ``` and then implemented it in signal.c like this: ``` if (ka->sa.sa_handler == SIG_WPG) { unsigned long ul_cr2 = current->tss.cr2; unsigned long ul_eip = (unsigned long) regs->eip int ul_cr2...
You can use thesignal()method to register a callback for that exception: ``` //callback prototype void Handler(int sig); //register the callback for the specific signal signal(SIGSEGV,&Handler); ```
I am unable to allocate memory using the following code: ``` int *h_VC = (int *)malloc(sizeof(int)*SIZE); //SIZE is 19200 if(h_VC==NULL) { printf("Memory Not avaialble"); } ``` My code uses the above block in a while loop and is run several times. I have 8GB memory. I am monitoring the free memory at the same time...
Anything could be the problem. Replace theprintfwith ``` perror(""); ``` to get a hint.
Looking for a way to speed up reading and processing a large text file (basically csv; stream_lf). Should I bypass RMS? Solution may be asynchronous or synchronous. Current implementation is synchronous, but is too slow. Implementation is in HP Pascal, and using the pascal run-time library (OPEN/READLN/EOF/CLOSE). ...
For seqeuntial files: Take a look into the WASD or VWCMS code (look athttp://www.vsm.co.au/wasd). I know these bypass RMS as well in favour of speed for web services, but I don't know in whar sources that is done. For relative files, take sequence into account. Records could be non-exixtant (empty?) For indexed files:...
The standard predefined macro__FILE__available in C shows the full path to the file. Is there any way to shorten the path and get just the filename? I mean instead of ``` /full/path/to/file.c ``` I see ``` to/file.c ``` or ``` file.c ```
Try ``` #include <string.h> #define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__) ``` For Windows use '\\' instead of '/'.
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed11 years ago.Improve this question Having involved in C++ projects for more than ten years, it is really a big question for me that why Objective-C has been ...
There is no philosophy per sé, Apple bought Next Computer and their Operating System NeXTSTEP, which provided an objective-c API. Mac OS X is based on on the NeXTSTEP system, and in turn, iOS is based on OS X, so it's a natural progression. This also explains why a whole bunch of classes start with NS.
I am New to audio programming.I want to create small application which is capable of playing and gives volume control . I am using alsa-lib. I want to know what is the purpose of switch (ex.Master Playback switch), enum in mixer elements and what value should i set to those switchs . Please suggest me some tutorial ...
Just collecting some here, that have example code: ALSA Programming HOWTO v.1.0.0 [alsamodular.sourceforge.net]A tutorial on using the ALSA Audio API [equalarea.com]2002A close look at ALSA [volkerschatz.com]ALSA API - Sample Programs With Source Code By Aquiles Yanez2005Introduction to Sound Programming with ALSA | ...
I've been tasked with recoding a MATLAB script into C or C++, and I'm having a little difficulty wrapping my head around this filter function (filter(a, b, x)). Does anyone know of a simple way to do this, or an existing C library that accomplishes the same thing? Thanks!
Just implement the filter function as describedhere. This resembles just a tapped delay-line filter, wherebandaare coefficients andxis the input data: ``` a[1]y[n] = b[1]x[n]+b[2]x[n-1]+...+b[N]x[n-B+1]-a[2]y[n-1]-...-a[N]y[n-N+1] ``` You only have to take care about not-yet-existing indices, which are denoted by th...
How to swap the nibble bit positions of a number? For example: 534, convert it into binary, the rightmost 4 bits has to be interchanged with the leftmost 4 bits and then make a new number with that. Anyone know how to do this?
Sean Anderson's bit twiddling guidehas the following: ``` // swap nibbles ... v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4); ``` under the entry forReverse an N-bit quantity in parallel in 5 * lg(N) operations.
How do you write native (C/C++) code with Libgdx that works for Android and desktop? Thanks.
According to their github projectlibgdx is a "Cross-platform Java game development framework based on OpenGL ES". I've just searched for "libgdx with c++" and ended up at theirmain sitewhich says it's written in Java/C++/C — but that doesn't mean it's available as a C/C++ library, and I can't see anything to that effe...
Iwant to transfer a file to a particular directory on FTP server . If it does not exists on the server then it has to be created there and file will be placed . Platform : Linux , gcc compiler Thanks .
Start with theftpuploadexample inlibcurl.
Is it possible to use a regular expression to alter an array index in emacs? e.g. for some C code change: ``` int my_array[4]; my_array[0] = 1; my_array[1] = 2; my_array[2] = 3; ``` to: ``` int my_array[4]; my_array[1] = 1; my_array[2] = 2; my_array[3] = 3; ``` a sort of replace[i]with[i+1]operation?
Something like that ? ``` M-x query-replace-regexp my_array\[\([0-9]+\)\] RET my_array[\,(1+ \#1)] ``` \, in replacement string can be replaced by any lisp expression. (last edit: using\#1in place of(string-to-int \1))
I have some type1 types in /usr/share/fonts/type1/gsfonts/, and even more after installing msttcorefonts. But in that diversity of fonts, i dont know which one is verdana or arial or else. And no verdana entries was found in /usr/share/fonts/X11/Type1/fonts.dir. Here my code to load font: ``` font_name = HPDF_LoadTy...
msttcorefonts are TTF, not Type1.
``` int main(void) {   char name[] = "t2.txt"; FILE *datei; datei = fopen(name, "a+"); fprintf(datei, "Hello"); fclose(datei); getchar(); return 0; } ``` This program writes the word "hello" in the t2.txt file. to see this I should always open the file by myself. But I want to mak...
That depends on your platform. For windows, you could use the system method: ``` int system ( const char * command ); ``` with ``` system("notepad t2.txt"); ```
Why it is said to keep very frequently used variables always at the top of the structure. I know it is something to do with performance. But If someone explains in detail or give a URL hit, would be very much appreciated.
A member in a structure is normally accessed by the compiler by having a base address, and then adding an offset to get the member. Some (especially older) CPU architectures could not use large offsets, so if the structure was large or contained arrays it would have used slower access methods. On modern CPU architectu...
I have some logic that I would like to store as an integer. I have 30 "positions" that can be either yes or no and I would like to represent this as an integer. As I am looping through these positions what would be the easiest way to store this information as an integer?
You can use a 32 bit uint: ``` uint32_t flags = 0; flags |= UINT32_C(1) << x; // set x'th bit from right flags &= ~(UINT32_C(1) << x); // unset x'th bit from right if (flags & UINT32_C(1) << x) // test x'th bit from right ```
I have a long integer (ie 10001000110...) and an array with double values (ie {.5,.76,.34,...}) and I would like to loop through the binary representation of my integer and multiply each each digit with its corresponding place in my array and add it all together (matrix multiplication): so like: 1*.5+0*.76+0*.34........
Something like this? ``` int n = n_doubles; double result = 0.0; while (n--) { if ((long_integer>>n)%2) result += doubles[n_doubles - n]; } ```
I need to write a little program in C, which recives only numbers. As a part of this program I need to create a validation that user input will be only numbers, otherwise the program should display an error. I have read about theisdigit()function, but it's not working for me. Do you have other solutions for me? hour...
You will need to check every character of the input to determine if they are digits or not: ``` for(int i = 0; i < strlen(hours); i++) { if(!isDigit(hours[i])) { printf("invalid time\n"); break; } } ```
What's the best way to find the number of threads that will be used for an ompparallel for? I want to allocate enough memory for use with all the threads, but can't make use ofomp_get_num_threadsuntil I'm inside the parallel section. For instance: ``` int thread_count = ? float *data = (float*)malloc(thread_count * d...
You could use a call toomp_get_max_threads().
I try to compile a erlang nif plugin on windows using the cygwin gcc. It compiles fine but the linker issues some errors: undefined reference to `_enif_get_int' I'm currently linking against ei.lib and erl_interface.lib. None of these contain the required symbols. Did I miss something?
It looks rather like you have a windows module (which expects symbols starting with underscore) linking against cygwin libraries (which typically don't export symbols with underscore).
Is there a resonably easy way to in C convert atreestruct such as the below to JSON? For easy read and write to files and store between executions? Or in another format perhaps (I only choose JSON because I am more experienced with it). ``` struct node { datatype data; // whatever data is inside the node struct ...
Sure: serialize a null pointer asnull, pick an appropriate representation fordata(let's call thatdata_repr), then serialize anodeas (pseudocode) ``` { "left" : <serialize(left)>, "right" : <serialize(right)>, "data" : <data_repr>} ```
I am looking for a way to delete an entry from an array in C. Also delete an entry in a structure. I am pretty new to C, any idea how to do it? UPDATE: Found a code that is supposed to delete an entry from a structure: ``` void removeEntry(student *st, int *nr, char nu[50]) { int k=0,i,j; for(i=0;i<*nr;i++...
To delete an entry in a dynamically allocated array (replaceTby the actual type stored in the array): ``` // delete element i in array a of size n T *delete(T *a, size_t n, size_t i) { memmove(&(a[i]), &(a[i+1]), n - i - 1); return realloc(a, sizeof(T) * (n - 1)); } ``` If order doesn't matter, then replace ...
I got a pcap file with voip conversation, how i can separate RTP packets from the other packets? I can obtain sip packets, but I can't differenciate the RTP packets from the rest.
Search for RTP headers as defined inRFC3550within your file. Or better use pcap-filter, for instance withthiswiki (look for "Q: What is a good filter for just capturing SIP and RTP packets?").
This question already has answers here:Why dividing two integers doesn't get a float? [duplicate](7 answers)Closed5 years ago. Please do flog me for this really basic question, but I still can not get why this happen. I read that for printing several value behind coma, I should use %.f in C. So I have this problem,...
The problem is that you are doing integer division. 90/100 = 0 in integer terms. If you want to get 0.9, do : 90.0/100.0
For a C project I'm writing I need to use the GMP library, which I have untarred into my Home directory (using OpenBSD OS with bash). I'm working with others over git, so I can't change the headers to relative files and at the moment the GCC is giving errors about not being able to find it. I don't have root privelidg...
When compiling use the argument-Ito tell GCC where to look for header files, and-Lto tell GCC where to look for libraires. For example: ``` $ gcc -I/location/of/library/headers -c foo.c -o foo.o $ gcc -L/location/of/library/libs foo.o -o foo -llibrary ```
Iwant to transfer a file to a particular directory on FTP server . If it does not exists on the server then it has to be created there and file will be placed . Platform : Linux , gcc compiler Thanks .
Start with theftpuploadexample inlibcurl.
Is it possible to use a regular expression to alter an array index in emacs? e.g. for some C code change: ``` int my_array[4]; my_array[0] = 1; my_array[1] = 2; my_array[2] = 3; ``` to: ``` int my_array[4]; my_array[1] = 1; my_array[2] = 2; my_array[3] = 3; ``` a sort of replace[i]with[i+1]operation?
Something like that ? ``` M-x query-replace-regexp my_array\[\([0-9]+\)\] RET my_array[\,(1+ \#1)] ``` \, in replacement string can be replaced by any lisp expression. (last edit: using\#1in place of(string-to-int \1))
I have some type1 types in /usr/share/fonts/type1/gsfonts/, and even more after installing msttcorefonts. But in that diversity of fonts, i dont know which one is verdana or arial or else. And no verdana entries was found in /usr/share/fonts/X11/Type1/fonts.dir. Here my code to load font: ``` font_name = HPDF_LoadTy...
msttcorefonts are TTF, not Type1.
``` int main(void) {   char name[] = "t2.txt"; FILE *datei; datei = fopen(name, "a+"); fprintf(datei, "Hello"); fclose(datei); getchar(); return 0; } ``` This program writes the word "hello" in the t2.txt file. to see this I should always open the file by myself. But I want to mak...
That depends on your platform. For windows, you could use the system method: ``` int system ( const char * command ); ``` with ``` system("notepad t2.txt"); ```
Why it is said to keep very frequently used variables always at the top of the structure. I know it is something to do with performance. But If someone explains in detail or give a URL hit, would be very much appreciated.
A member in a structure is normally accessed by the compiler by having a base address, and then adding an offset to get the member. Some (especially older) CPU architectures could not use large offsets, so if the structure was large or contained arrays it would have used slower access methods. On modern CPU architectu...
I need to write a little program in C, which recives only numbers. As a part of this program I need to create a validation that user input will be only numbers, otherwise the program should display an error. I have read about theisdigit()function, but it's not working for me. Do you have other solutions for me? hour...
You will need to check every character of the input to determine if they are digits or not: ``` for(int i = 0; i < strlen(hours); i++) { if(!isDigit(hours[i])) { printf("invalid time\n"); break; } } ```
I was just wondering whether it was possible to do something like this: ``` char yn; scanf("%79/6ec",yn); ``` so yn can only become either y (0x79) or n (0x6e)
No , but you could use scanf to read a char ``` scanf("%c" , &yn ); ``` after that you have to check whether it is y/n or illegal input. ``` if ( yn == 'y' ) { ... } ```
Is there a way to get the length of an Array when I only know a pointer pointing to the Array? See the following example ``` int testInt[3]; testInt[0] = 0; testInt[1] = 1; testInt[2] = 1; int* point; point = testInt; Serial.println(sizeof(testInt) / sizeof(int)); // returns 3 Serial.println(sizeof(point) / sizeof...
The easy answer is no, you cannot. You'll probably want to keep a variable in memory which stores the amount of items in the array. And there's a not-so-easy answer. There's a way to determine the length of an array, but for that you would have to mark the end of the array with another element, such as-1. Then just l...
Having read tutorials and books on C, I am trying hard to connect my knowledge of UTF (as the text format for roman letters and all sorts of other alphabets/scripts) with C, as a programming language used all over the world. C seems to take ASCII characters. So if I wanted to write a program with input/output in Chi...
You would be using "wide char"wcharinstead ofchar. http://en.wikipedia.org/wiki/Wide_characterhttp://pubs.opengroup.org/onlinepubs/007908799/xsh/wchar.h.htmlhttp://msdn.microsoft.com/en-us/library/aa242983(v=vs.60).aspx There are also specialized libraries likeiconvthat help on some platforms.
I compile the application for 64 bit Windows operating system. The application should save 64 bit addresses, I have to decide about variable type, to save them. I thought to save them in long. Butsizeof(long) == 4.Where and how can I save the addresses
You should store memory addresses in pointers: ``` void *myaddr = 0x0123456789ABCDEF; // memory address int *myaddr2 = 0x0123456789ABCDEF; // pointer to int in memory, dereferencable ``` You can get the address of a variable like this: ``` int myvar; int *addrofmyvar = &myvar; printf("%p", addrofmyvar); // use %p t...
How do I format a time_t structure to something like this year-month-day h:m:s, I have already tried using ctime: ``` time_t t = time((time_t*) NULL); char *t_format = ctime(&t); ``` but it doesn't give me the desired results example : 2011-11-10 10:25:03. What I need is a string containing the result so I can writ...
Usestrftimefromtime.hlike so: ``` char tc[256]; strftime(tc, 256, "%Y-%m-%d %H:%M:%S", tm); ```
I'm currently trying to solve the problem when I need to load rows from the file and then sort them in the right order. If I manually assign lettes to the array of wint_t and then sort them, everything from just fine with any encodinghttp://pastebin.com/85eycH15. But if I read the very same letters from file and the...
I assume that the only encoding with which you get your expected result is the one used for your data file. Re-encode the data file in another encoding, you'll get your expected result for the new encoding and not others.
I've got this code, which I don't understand why it doesn't compile: ``` typedef struct { uint32_t serial_number; uint32_t ieee_address[6]; } FACTORY_CONFIG; ... // Unlock flash (only the portion we write on) error = FLASHD_Unlock ( writeaddress, writeaddress + sizeof ( FACTORY_CONFIG.serial_number ), 0, 0...
You can't just access members of types in C like that. You can, however, takesizeoffrom actual objects. And sincesizeofis a compile-time construct, these objects don't even have to be valid. So the following will work: ``` sizeof(((FACTORY_CONFIG *)0)->serial_number) ``` If you use this a lot, or just for readabilit...
How can i change current state of a windows service from a C/C++ program ?? for example say, Mysql is running as a service and its current status is 'Started'... how can I check the status and how can i change its status from a c/c++ program? like if I want to change its status from 'Started' to 'Stopped' - how can i...
QueryServiceStatuscan be used to determine the status of a service. Look at the otherService functionsto change the status. There is even a completeStarting a Serviceexample (and the matchingStopping a Servicecode).
I'm new to NetBeans.I am using NB on my PC.I just cleaned & built a project and the output was: ``` CLEAN SUCCESSFUL (total time: 1s) make: Nothing to be done for `all'. BUILD SUCCESSFUL (total time: 1s) ``` Now I can't seem to find any executable.How do I set the IDE to create an EXE file output from the project? ...
After you build, the executable should be in a path like PROJECT/dist/PLATFORM/project.exe (dist or build can't remember exactly)
I saw a piece of code like this and wondered whether this is thread-safe: ``` int savedErrno = errno; //call some function that may modifies errno if (errno == xxx) foo(); errno = savedErrno; ``` I don't think this is thread-safe, am I correct? But I saw people write code like this, so I am not sure... Can a...
Each thread has its own (thread specific) copy of errno so that looks like it should be safe. From man (3) errno: errno is defined by the ISO C standard to be a modifiable lvalue of type int, and must not be explicitly declared; errno may be a macro. errno is thread-local; setting it in one thread does not affect i...
I was given the following struct definitions for an assignment revolving around queues and stacks: ``` struct entry { bool operation; char op; int num; }; struct node { bool operation; char op; int num; entry * next; }; ``` The assi...
Something is off. Your node can point to a "next" element but this "next" element can't point to anything else. I suspect it should actually look like this: ``` struct entry { bool operation; char op; int num; }; struct node { struct entry *entry; struct node *next; }; ```
From time to time, I'll have an off-by-one error like the following: ``` unsigned int* x = calloc(2000, sizeof(unsigned int)); printf("%d", x[2000]); ``` I've gone beyond the end of the allocated region, so I get an EXC_BAD_ACCESS signal at runtime. My question is: how is this detected? It seems like this would jus...
The memory system has sentinel values at the beginning and end of its memory fields, beyond your allocated bytes. When you free the memory, it checks to see if those values are intact. If not, it tells you.
I am using a variation of GCC that is specific to ARM microprocessors, and I am trying to figure out what this macro is doing in stdint.h. ``` #if defined(__GNUC__) && \ ( (__GNUC__ >= 4) || \ ( (__GNUC__ >= 3) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ > 2) ) ) /* gcc > 3.2 implicitly defines the valu...
gcc's option-dMspits you all macros that are defined internally. Something like ``` gcc -xc -dM -E /dev/null | sort | less ``` should do the trick.
``` #include <stdio.h> #include <string.h> int main() { char* p = new char[10]; memset(p,0,10); printf("%c",*p); } ``` I supposememsetset every byte startingpto0. I'm a little surprised to see nothing at all printed out. What on earth was happening formemset?
memsetdoes set all the bytes to 0; thus, when you dereferencep, you get acharwith value 0 (the NUL byte), and on most systems, printing such acharproduces no visible output. If you want to print the numeric value of the byte instead, useprintf("%d", *p);.
If a thread is waiting for data from the network, it is de-scheduled by the kernel to let other threads use the CPU. Once data have been provided by the network device, this thread must be scheduled again if its priority is greater than the running thread. Who is responsible for re-running the scheduler, the device d...
Both. The drivers and kernel are essentially an interrupt-handler that can decide to return-from-interrupt to a different thread than the one that was interrupted. The driver handles the interrupt, signals that the waiting thread has become ready and jumps/calls to the OS entry point so that the scheduler may change...
If I have enums like: ``` enum EnumA { stuffA = 0 }; enum enumAA { stuffA = 1 }; ``` What happens here when you refer tostuffA? I thought you would refer to them likeEnumA.stuffAandEnumB.stuffAas in Java, but that doesn't seem to be the case in C.
enumsdon't introduce new scope. In your example, the secondenumwouldn't compile due to thestuffAname clash. To avoid name clashes, it is a common practice to give the elements of anenuma common prefix. Different prefixes would be used for different enums: ``` enum EnumA { EA_stuffA = 0 }; enum EnumAA { EAA_stuf...
I am writing a program to do some analysis on DNA sequences. Everything works fine except for this thing. I want to declare a 2D array of size m*n where m and n are read from an input file. Now the issue is that if m and n goes too large. As an example if m = 200 and n = 50000 then I get a seg fault at the line where ...
Probably you are running out of stack space.Can you not allocate the array dynamically on heap usingmalloc? You may want to have a look atthisanswer if you do not know how to do that.
I have function in C that assumes stdin is open. I want to add an assertion in front of it to make sure stdin is not closed by anyone. How can I check that stdin isn't closed by anyone? ``` assert(is_open(stdin)); ```
You can't find out whether aFILE*has been closed.fclosemightfreetheFILEobject it points to, so that object's contents may be undefined afterfclose. This is true even ofstdin. The solution I proposed previously was wrong. Sorry about that. The best you can do on a POSIX platform is something like ``` bool stdin_open(...
I have C program ( program.c ) that calls a shell script ( command.sh ). command.sh returns an output (a password), i need to get this output in my program.c. usingsystem(command);, i can't get hold of the output. is there any other way in C to solve my problem?
Not in pure C. You want POSIX. Specificallypopenfunction. The specification has a nice example, that you can just copy 1:1http://pubs.opengroup.org/onlinepubs/009604499/functions/popen.html
I want to convert an array of int to an array of char and then back again, for serialization purposes. It does not need to work cross-platform. I came up with ``` //sample int array int arr[] = {1,2,3,4,100}; char char_arr[sizeof(arr)]; //int arr to char arr memcpy(char_arr, arr, sizeof(arr)); int newar...
The third argument tomemcpyis number of bytes*, not number of elements. So your secondmemcpycall is incorrect. * Number ofchars, technically.
I would like to know if it's possible to free the memory allocated byg_thread_init(NULL) here is my code : ``` int main(void) { g_thread_init(NULL); g_thread_exit(NULL); } ``` and the valgrind output : ``` ==1944== HEAP SUMMARY: ==1944== in use at exit: 8,910 bytes in 119 blocks ==1944== tot...
g_thread_init()is a run-once function that does setup for the multithreading support in GLib. The memory it allocates is never freed. In newer versions of GLib (>= 2.32),g_thread_init()is effectively a no-op, and you don't need to call it at all -- all of the multithreading setup is done automatically when your prog...
I need to write a variadic macro in C which must take zero or more arguments. In gcc, that can be achieved by adding "##" after the comma, e.g.,##____VA_ARGS____as answered inVariadic macros with zero arguments. However, the compiler in my build system (beyond my control) does not understand the,##syntax and so does...
Yes, gcc swallowing the comma is non standard and you should not rely on that. With C99 conforming preprocessors you may achieve a similar effect by testing for a macro arguments that is the empty token. For the ideas of how this works you could seehere, for a whole set of preprocessor macros that ease the programmin...
Is there a tool toautomaticallygenerate Fortanbindingsfrom C library header, using intrinsiciso_c_bindingsmodule from Fortran 2003 standard? I am not interested intranslatingC to Fortran, but only generating bindings.
An automatic tool was used to get thegtk-fortranbindings. It is a Python scriptcfwrapper.py. You might be able to adapt it to for your needs, although for my small problems I finally chose to make the bindings by hand.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question I have a set of statements for tracing across the code. Is there any way to get rid of these set of statem...
Usually trace is performed in a way similar to this (oversimplified here): ``` #ifdef DISPLAY_TRACES #define TRACE(x) printf(x) #else #define TRACE(x) #endif ``` Then compile with or without-DDISPLAY_TRACESdepending on whether you want traces.
Consider the following scenario: I am opening a tar file (say abc.tar.gz), writing the data, andbeforeclosing the file descriptor, I am trying to extract the same file. I am unable to do so. But if I extract the file after having closing the fd, it works fine. I wonder what could be the reason.
All files has apositionwhere data is read or written. After writing to the file, the position is at the end. Trying to read will attempt to read from that position. You have to change the position to the beginning of the file with a function likelseek. Also, you did open the file in both read and write mode? Edit A...
Have two files with struct definitions. Header: ``` typedef struct _InputData InputData; extern InputData input_data; ``` and source file: ``` struct _InputData{ char const*modification_l; char const*amount_l; char const*units_l; }; InputData input_data = {...}; ``` When i try to use input_data from ot...
You have do define the complete structure in the header file. Otherwise there is no way to know what fields it have, i.e. it's incomplete.
I believe I have carefully read the entireprintf()documentation but could not find any way to have it print out, say, the elements of a 10-element array offloat(s). E.g., if I have ``` float[] foo = {1., 2., 3., ..., 10.}; ``` Then I'd like to have a single statement such as ``` printf("what_do_I_put_here\n", foo)...
you need to iterate through the array's elements ``` float foo[] = {1, 2, 3, 10}; int i; for (i=0;i < (sizeof (foo) /sizeof (foo[0]));i++) { printf("%lf\n",foo[i]); } ``` or create a function that returns stacked snprintfand then prints it with ``` printf("%s\n",function_that_makes_pretty_output(foo)) ```
If this is possible: ``` #include <stdio.h> #include <process.h> #define SIZE 5 void PassingArray(int arr[]) { int i=0; for(i=0 ; i<SIZE ; i++) { printf("%d, ", arr[i]); } printf("\n"); } main() { int myIntArray[5] = {1, 2, 3, 4, 5}; PassingArray(myIntArray); system("PAUSE...
You're not returning an int, but you're returning the array. This is the same value as&myIntArray[0].int ReturningArray()[]is not a valid function prototype.
I need to create a string on the heap, I was wondering if there is something similar already included in the standard libraries, or do I have to implement it myself (using malloc())?
You could usemalloc(),calloc()orstrdup()(the latter is POSIX, not standard C). It is not totally clear what you mean by "implement it myself (usingmalloc())" -- what exactly is there to implement?
I have a number that is "significant byte", it may be 0 or 255. Which means 0 or -1. How to convert 255 to -1 in one time. I have a function that doesn't works for me: ``` acc->x = ((raw_data[1]) << 8) | raw_data[0]; ```
Assuming that every 8th bit set to 1 means negative (254 == -2) then a widening conversion fromsignedtypes should do: ``` int n = (signed char)somebyte; ``` so ``` unsigned char rawdate[2] = ...; int msbyte = (signed char)rawdata[1]; acc->x = (msbyte << 8) | (raw_data[0] & 0xFF); ```
I have a string, ``` char* str = "HELLO" ``` If I wanted to get just theEfrom that how would I do that?
``` char* str = "HELLO"; char c = str[1]; ``` Keep in mind that arrays and strings in C begin indexing at 0 rather than 1, so "H" isstr[0], "E" isstr[1], the first "L" isstr[2]and so on.
I have OSX Lion, which comes with Postgres, but I'd rather us MySQL. But either way, I'm pretty lost. How would I go about interfacing C with MySQL, so I can just #include "mysql.h" (or maybe some other library) and go from there. Assume that all I've done so far is download the latest MySQL version. Thank you.
You are on the right track, just include the headers and link against the client libraries. Documentation for the C API is here:http://dev.mysql.com/doc/refman/5.1/en/c.html
Ok so I get this code to do the averaging : (written in C ) ``` . . int sum[3]; int j; int avg; for(;;) //infinite loop { for(j=0;j<3;j++){ i = ReadSensor(); // function that keeps saving sensor values as int i sum[j]=i; } avg=sum[0]+sum[1]+sum...
Looks like your script only capturesthreevalues (j=0, j=1, j=2), then divides by four.
From time to time, I'll have an off-by-one error like the following: ``` unsigned int* x = calloc(2000, sizeof(unsigned int)); printf("%d", x[2000]); ``` I've gone beyond the end of the allocated region, so I get an EXC_BAD_ACCESS signal at runtime. My question is: how is this detected? It seems like this would jus...
The memory system has sentinel values at the beginning and end of its memory fields, beyond your allocated bytes. When you free the memory, it checks to see if those values are intact. If not, it tells you.
I am using a variation of GCC that is specific to ARM microprocessors, and I am trying to figure out what this macro is doing in stdint.h. ``` #if defined(__GNUC__) && \ ( (__GNUC__ >= 4) || \ ( (__GNUC__ >= 3) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ > 2) ) ) /* gcc > 3.2 implicitly defines the valu...
gcc's option-dMspits you all macros that are defined internally. Something like ``` gcc -xc -dM -E /dev/null | sort | less ``` should do the trick.