question
stringlengths
25
894
answer
stringlengths
4
863
``` #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);.
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)) ```
My compiler(gcc) is showing the warning ``` #include<stdio.h> struct s{ unsigned char *p; }; int main() { struct s a = {"??/??/????"}; //warning printf("%s",a.p); return 0; } ``` warning: pointer targets in initialization differ in signedness please help me to why is this warning comes.
String literals are not of typeunsigned char*. You probably meant to typeconst char*in your struct. If not, you probably do not want to assign a string literal to it without making itconst, because it is illegal to modify the memory in which string literals reside.
I want to typecast afloatas anint. However, this does not do a bit by bit copy. Is it possible to typecast afloatinto anintwhile maintaining all the bits (sign, exponent, mantissa)?
It's not possible to do this in a completely C-compliant way, but you could use unions: ``` union{ int i; float f; } u; u.f = 123.456; // Your value. // Read u.i. ``` This should still work on nearly all systems today. And of course assumes thatfloatandintare the same size. The alternative is to use po...
I wish to know what happens to FILE pointer after the file is closed. Will it be NULL? Basically, I want to check if a file has already been closed before closing a file. For example as follows: ``` FILE *f; if(f!=NULL) { fclose(f); } ``` Can I do this or is there any other way to go about it?
Since arguments are passed by value there is not wayfclosecould set your file pointer toNULL. Sincefcloseprobably destroys theFILEyou have to Manually set the file pointer toNULLafter doing afclose(won't work if you close it in a different function unles you useFILE **)Don't end up in a situation where you "forget" w...
My compiler (GCC) is giving me the warning: warning: implicit declaration of function Why is it coming?
You are using a function for which the compiler has not seen a declaration ("prototype") yet. For example: ``` int main() { fun(2, "21"); /* The compiler has not seen the declaration. */ return 0; } int fun(int x, char *p) { /* ... */ } ``` You need to declare your function before main, like thi...
If I can create a QString in C++ like: ``` QString s = "my string"; // or, QString *s = new QString("my string"); ``` Then, when will I event need to usemalloc?
You never need to usemallocin C++. Ok, now that I've saidnever, one exception is when you are using C code that for some reason or another takes ownership of a block of memory you give it and later callsfreeon a pointer to that memory to deallocate it. I have never seen that before (I don't usually use C libraries a...
gcc 4.6.2 c89 Is there any standard regex expression that can be used to extract the IP address from a string. I am thinking about using sscanf with a regex expression to get the IP from this sample string below. This is the sample string: ``` v=0 o=sip_user IN 10230 22472 IP4 NET.CAT.NTBC s=SIP_CALL c=IN IP4 10.1...
``` \b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b ```
what does this mean? ``` #define WS_RECURSIVE (1 << 0) ``` I understand that it will defineWS_Recursive (1 << 0)but what does<<mean? Thanks!
<<is theleft shift operator. It is shifting the number1to the left0bits, which is equivalent to the number1. It is commonly used to createflags, numbers that can be combined together with|(bit or) and various operations can be applied to them, such as testing whether a flag is set, setting a flag, removing a flag, et...
I have a C project that uses 2-space indents (in/projects/c) and a C++ project with 4-space indents (in/projects/cpp). I can't figure out how to make Emacs automatically do the right spacing depending on where the file I open lives. I can tell it to usec++-mode(4 spaces) for the .cpp files, but the .h files (in the ...
Directory Local Variables:http://www.emacswiki.org/emacs/DirectoryVariables You can either use .dir-locals.el files, or alternatively you can configure it entirely in your .emacs file with thedir-locals-set-class-variablesanddir-locals-set-directory-classfunctions.
I'm trying to post some of the work i've done in an eportfolio thus trying to put code online. I have a quite large C file that i have put between two<pre></pre>tags and it puts only about 1/4th of the code on the screen and due to this doesn't recognize some of my</div>tags at the end of the HTML. I guess i'm wonderi...
It is simply because html still can be valid inside<pre>tags. The easy to fix this is to replace all<characters with&lt;
I do not understand why the following code can create the aaa file, but cannot write '1' (the buffer value) into the aaa file. ``` #include <stdio.h> #include <stdlib.h> int main() { int a; int b; int buf; FILE *fp; buf = 1; a = 5; b = 6; fp = fopen("c:\\aaa.txt","wb"); fwrite(&bu...
callfclose(fp)orfflush(fp)to make sure content of file buffer gets flushed to the file.
I'm looking for a pretty simple thing: I want to test if a key was pressed.any key. If not, the program should continue its business. So it must be a "non blocking" call. I guess this question is probably equivalent to checking if the keyboard buffer has anything into it. I guess such a function must exist in C for...
In windows you can use '_kbhit()' in conio.h It is a non-standard function and may not be available on other platforms.
I want to check whether the user input contains only digits or not. So, I use the following code: ``` for(i = 0; argv[1][i] != NULL; i++) if(!isdigit(argv[1][i])) { printf("Error"); return -1; } ``` It works well but I got this warning: ``` warning: comparison between pointer and integer...
NULLis not the same as the null-terminator character. You should use'\0'instead.
My compiler (gcc) is giving me this warning. Please help me to understand what it means: warning: trigraph ??/ ignored, use -trigraphs to enable
You have "accidentally" written atrigraphsomewhere in your source code (the compiler's warning would pinpoint the line). Since trigraphs were invented to solve a problem that doesn't come into play on modern systems, you don't actually want the trigraph??/to be replaced with the character\. Therefore, this warning sh...
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
See thegetifaddrsman page. There is an example program towards the end.
I'm thinking about generating random strings, without making any duplication. First thought was to use a binary tree create and locate for duplicate in tree, if any. But this may not be very effective. Second thought was using MD5 like hash method which create messages based only on time, but this may introduce ...
Generate N sequential strings, then do arandom shuffleto pull them out in random order. If they need to be unique across separate generators, mix a unique generator ID into the string.
I have two filesPosit.candHeadPose.cpp Posit.ccompiled toPositnew My question is How to call already compiled Positnew like thissystem("Positnew");from HeadPose.cpp
Just use c keywordexternto declare the function then the linker will make sure that it can be linked either dynamically or statically. extern void Positnew()
I want to set up an environment on my PC (Win7x64) that I will be able to combine these projects and compile them into one executable: FFmpegAMV codec tools For this I need an environment that can compile/debug both the above projects (creating a Windows compatible exe). Any ideas?
http://ffmpeg.arrozcru.org/wiki/index.php?title=Main_PageNetBeans can handle MinGW. (Might be other IDEs, but I've used MinGW under NetBeans so I know it can.)
I am in need of a hash value calculated on an IP address and a port number. I have found the following example, and through trail, I can see it returns a three-digit hash value which is fine by me. However, I would like to know what happens in a little further detail, and I have a hard time figuring it out. Here is t...
It's no great mystery: It XORs (^) adds.s_addr with itself shifted 8 spaces to the right; then xors it with the port number, and finally ANDs the whole thing by 255 to limit it to 8 bytes in length.
I have files in a directory named as 1.txt ,2.txt and so on. I am reading these files by: ``` int counter=0; unsigned char buffer[212]={0}; while(1) { sprintf(buffer,"path/%d.txt",++counter); FILE *fp = fopen(buffer,"rb"); // some operations.. fclose(fp); } ``` I have more than 800 txt files in the folder(1...
Maybe you are running uout of file descriptors (max is for example 500 per process). Try to use the readdir function.
by this Why does fopen("any_path_name",'r') not give NULL as return? i get to know that in linux directories and files are considered to be file. so when i give any directory-path or file-path in fopen with read mode it doesnt give NULL file descriptor and? so how can i check that whether it is dirctory path or fi...
man 2 stat: ``` NAME fstat, fstat64, lstat, lstat64, stat, stat64 -- get file status ... struct stat { dev_t st_dev; /* ID of device containing file */ mode_t st_mode; /* Mode of file (see below) */ ... The status information word st_mode has ...
I am trying to convert part of a char* into an int. For example if a user inputs 'step 783'. I want to convert 783 into an int. ``` char buffer[100]; char* input = fgets(buffer, sizeof buffer, stdin) int i = input[5] - '0'; //assume location 5 is where the number will start printf("%i", i); ``` Right now, this code ...
You can use the ordinary conversion functions, starting at the desired position: ``` int i = atoi(input + 5); long int j = strtol(input + 5, NULL, 0); ``` The second one,strtol(), is particularly useful if you want to find out where the numberended(via the second parameter,see manual).
How can I convert a hex ip (such as42477f35), and get it to spit out the correct decimal ip (in the example before, the correct result is66.71.127.53)? I'd like it to take the hex ip in as a string, then output the correct result as a string too so I can use it elsewhere in the C code. I'm not an expert in C, so if ...
This is one possibility: ``` #include <stdio.h> int ip_hex_to_dquad(const char *input, char *output, size_t outlen) { unsigned int a, b, c, d; if (sscanf(input, "%2x%2x%2x%2x", &a, &b, &c, &d) != 4) return -1; snprintf(output, outlen, "%u.%u.%u.%u", a, b, c, d); return 0; } ```
Does anyone know how to catch the output (I think its stdout) fromexecvpinstead of the system printing it (in c on linux) in the terminal?
execvpreplaces the current running process in memory. There's no "catching" the output. I suspect you're trying to run an external process from an existing process, and parse its output. For that you need to usepopen()which does afork()then anexec(), returning aFILE *to read (which will be thestdoutof the process you...
I'm reading linux kernel code and I encounter something like the following: ``` typedef void (* gps_location_callback)(GpsLocation* location) ``` then later it can be used like: ``` gps_location_callback location_cb; ``` Can somebody tell me what does that typedef mean? I never saw something like this before.. Tha...
This is afunction pointer. Variables of this type point to a function whose signature isvoid (GpsLocation*): ``` void foo(GpsLocation *); gps_location_callback f = foo; // now use f(p) etc ``` Without the typedef you'd have to write: ``` void (*f)(GpsLocation *) = foo; ```
I want to set up an environment on my PC (Win7x64) that I will be able to combine these projects and compile them into one executable: FFmpegAMV codec tools For this I need an environment that can compile/debug both the above projects (creating a Windows compatible exe). Any ideas?
http://ffmpeg.arrozcru.org/wiki/index.php?title=Main_PageNetBeans can handle MinGW. (Might be other IDEs, but I've used MinGW under NetBeans so I know it can.)
I am in need of a hash value calculated on an IP address and a port number. I have found the following example, and through trail, I can see it returns a three-digit hash value which is fine by me. However, I would like to know what happens in a little further detail, and I have a hard time figuring it out. Here is t...
It's no great mystery: It XORs (^) adds.s_addr with itself shifted 8 spaces to the right; then xors it with the port number, and finally ANDs the whole thing by 255 to limit it to 8 bytes in length.
I have files in a directory named as 1.txt ,2.txt and so on. I am reading these files by: ``` int counter=0; unsigned char buffer[212]={0}; while(1) { sprintf(buffer,"path/%d.txt",++counter); FILE *fp = fopen(buffer,"rb"); // some operations.. fclose(fp); } ``` I have more than 800 txt files in the folder(1...
Maybe you are running uout of file descriptors (max is for example 500 per process). Try to use the readdir function.
by this Why does fopen("any_path_name",'r') not give NULL as return? i get to know that in linux directories and files are considered to be file. so when i give any directory-path or file-path in fopen with read mode it doesnt give NULL file descriptor and? so how can i check that whether it is dirctory path or fi...
man 2 stat: ``` NAME fstat, fstat64, lstat, lstat64, stat, stat64 -- get file status ... struct stat { dev_t st_dev; /* ID of device containing file */ mode_t st_mode; /* Mode of file (see below) */ ... The status information word st_mode has ...
I am trying to convert part of a char* into an int. For example if a user inputs 'step 783'. I want to convert 783 into an int. ``` char buffer[100]; char* input = fgets(buffer, sizeof buffer, stdin) int i = input[5] - '0'; //assume location 5 is where the number will start printf("%i", i); ``` Right now, this code ...
You can use the ordinary conversion functions, starting at the desired position: ``` int i = atoi(input + 5); long int j = strtol(input + 5, NULL, 0); ``` The second one,strtol(), is particularly useful if you want to find out where the numberended(via the second parameter,see manual).
How can I convert a hex ip (such as42477f35), and get it to spit out the correct decimal ip (in the example before, the correct result is66.71.127.53)? I'd like it to take the hex ip in as a string, then output the correct result as a string too so I can use it elsewhere in the C code. I'm not an expert in C, so if ...
This is one possibility: ``` #include <stdio.h> int ip_hex_to_dquad(const char *input, char *output, size_t outlen) { unsigned int a, b, c, d; if (sscanf(input, "%2x%2x%2x%2x", &a, &b, &c, &d) != 4) return -1; snprintf(output, outlen, "%u.%u.%u.%u", a, b, c, d); return 0; } ```
Does anyone know how to catch the output (I think its stdout) fromexecvpinstead of the system printing it (in c on linux) in the terminal?
execvpreplaces the current running process in memory. There's no "catching" the output. I suspect you're trying to run an external process from an existing process, and parse its output. For that you need to usepopen()which does afork()then anexec(), returning aFILE *to read (which will be thestdoutof the process you...
I'm reading linux kernel code and I encounter something like the following: ``` typedef void (* gps_location_callback)(GpsLocation* location) ``` then later it can be used like: ``` gps_location_callback location_cb; ``` Can somebody tell me what does that typedef mean? I never saw something like this before.. Tha...
This is afunction pointer. Variables of this type point to a function whose signature isvoid (GpsLocation*): ``` void foo(GpsLocation *); gps_location_callback f = foo; // now use f(p) etc ``` Without the typedef you'd have to write: ``` void (*f)(GpsLocation *) = foo; ```
Example: ``` char str[10]; gets(str); str = (char[10]) strtok(str, " "); // type error here ``` Sincestrtok()returns achar *, I get an type error without that casting. With it I get the following: ``` error: cast specifies array type ``` What is the best to fix this code?
Oh man, be careful with thatgets()!Related question You can't assign to arrays (in other words, use them as lvalues). ``` char *p = "string"; char array[10]; array = p; /* invalid */ ``` Apart from that, you're not usingstrtok()correctly. The pointer returned points to the subsequent token, so you might want to c...
This is an interview question: What is difference betweenint []andint*, all of them are input arguments to a function. ``` f(int a[] , int* b) ``` My answers: Forf(), they have the same functions. The first one is the beginning position of the first element ina[]. The second one points to anint. But, how to dist...
As function parameters, the two types are exactly the same,int []is rewritten toint *, and you can't distinguish between them. Many many questions in StackOverflow cover this subject, and thec-faqeven has aspecial sectionon pointer and arrays (as arguments or not). Take a look into it.
In C if you have the following code: ``` for (size_t x, y = someValue; y > 0; y -= x, ptr1 += x, ptr2 += x) { // do stuff } ``` Will the variable y also be of the type size_t or would it be an int?
a declaration of ``` int a,b,c; size_t x,y,z; ``` means that all of a,b,c are same type (int) as are x,y,z (size_t) The declaration inside a for-loop is no different -- and in your example both x and y are of type size_t howeverin your examplexis not initialized (only y is set tosomevalue) -- and unless the body o...
I am new to the C language and pointers and I am confused by this function declaration: ``` void someFunction(int (*)(const void *, const void *)); ``` Can anyone explain in layman's terms what this does and how it works?
It's the prototype of a function that takes: a pointer to a function that takes aconst void*and aconst void*as arguments and returns anint as an argument, and returnsvoid.
My iPhone is jail broken with full terminal support. I need something (that isn'tcmpordiff) to compare app binaries. Both those commands give me weird results, they basically say that both binaries are completely different, when I can see and know that only one byte has been changed.
If it's possible to build it for the iPhone, you could trybsdiff, it's a diff-like utility that is specifically designed to handle binary data. The tools you mention are meant for textual input when it comes to finding differences. Failing that, you could try generating a brutally bloated textual representation, with...
Are there some libraries with C API to draw pictures? Just like the librarymatplotlibin python. I will use it to draw lines, dots, circles and I hope it has detailed documentation and opensource. My platform is gentoo.
The most comprehensive one is probablyImageMagick. They suggest using theMagickWandAPI. Other options arecairo, with a image buffer output device, or maybelibgd.
I am writing a program for analyzing certain type of packets. I got the dump file containing test packets in tcpdump format. is there any way to send this dump into one of the interfaces? I thought tcpdump would be able to do this on its own (unfortunately it isn't). Only thing I managed to do is to look at packets vi...
Did you try to take a look totcpreplaythat is done to : Replay network traffic stored in pcap files
So I created a rule to convert all .c files to .o files. I used variable$to place the right hand side of the rule into the recipe. The left hand side is ok with $@, but the right hand side is empty. I remember I did a similar Makefile with$, and it worked. ``` CFLAGS =-c -g all:server client server:server.o ...
Should be$<, not simply$. Seeinfo "(make) Automatic Variables".
I'd like to input my own graphs for use with the Stanford GraphBase CWEB library. I foundthisexample of a graph on the SGB webpage, and understand it for the most part. What I don't understand is why there are four zero-rows ("", 0\n) in the vertex list and so many zero-rows (0,0,0) in the edge-list. Graphs seem to co...
The extra zero-lines are not strictly necessary. They're included so that when the graph is loaded, memory is preallocated for vertexes and arcs that might be added to the graph later on (for example, in some algorithm being run on the graph). This is as an alternative to dynamically allocating memory for the new vert...
I have a visual studio project which I am trying to switch over to work in eclipse in linux. The project is written in C. I don't know how to properly switch my project so that it works in eclipse in linux. I also was wondering how to create threads and how to use any sleep type library function. Basically I need ...
Windows and Linux have different APIs for things like sleep. This article gives a good overview of some common porting conversions, such as sleep.http://www.ibm.com/developerworks/systems/library/es-MigratingWin32toLinux.html
I got a error. "Passing argument 1 'strchr' makes pointer from integer without a cast" How can I fix that ? this happen inconst char *ptr = strchr(c, ';');and I'm trying to do is just get the index of a specific char in a char array. In my File, I have for example 100 lines, and in each line, i has something like t...
Your variablecis asinglecharacter, not a char array.
I'm using__get_cpuid()to get info on thex86andx86_64processors my programs run on. With GCC on Linux and Mac OS, it seems to compile and run OK without include any header, but how portable is that? Would it work with other compilers? Should I include a header for that?
It has two leading underscores. Any leading underscore at all is a big hint that the variable or function is not portable.
I have recently been introduced toncursesfor asynchronous keyboard key listening, and getting on well with it. One issue i'm facing is that you can only have text on the visible screen, no scrollbars. I was wondering if its possible to keep usingncursesas it is so lovely, but have the program still keep the scrollbars...
scroll(). You have to set scrollok(win, TRUE) first. Actually if you just want to spew data like a normal terminal you only need to setscrollok()by itself. ``` #include <ncurses.h> int main(void) { int i = 0; initscr(); scrollok(stdscr,TRUE); while(1) { printw("%d - lots and lots of ...
This is actually not as simple as I first thought. In the absence of a hardware RNG, what is the best way to seed a Mersenne Twister? Or should I say, what is an acceptable way to seed a a Mersenne Twister RNG that is used to generate UUID's?
There is a nice discussion of pseudo-random number generatorshereincluding a section on the proper seeding of PRNGs (see rule 3), which usesmd5sumand/dev/randomor/dev/urandomto generate seeds. This also includes a number of PRNG alogrithms which are a lot easier to code up (< 10 lines of code) than the MT but are arg...
Is there a generic solution out there to create a 1-D histogram array of data from an input 1-D array of double-precision data? Not looking to plot the histogram in C, I just need something to create the histogram 1-D array by binning the data. Could someone help me understand what the binning (e.g. loop) code may l...
``` int* bin = calloc(hist_pts,sizeof(int)); float interval = (float)(max - min ) / num_bins; for (i=0;i<N;i++) bin[ (int)((value[i]- min)/interval) ]++; //don't forget to `free(bin) after you use it. ```
without -g flag: ``` (gdb) break main Breakpoint 1 at 0x8048274 ``` with -g flag: ``` (gdb) break main Breakpoint 1 at 0x8048277: file example.c, line 31. ``` I vaguely know -g option stores the symbol table information. What does the -g option exactly do?Is there any way I can look at this symbol table?
-g(forgcc) stores debugging information in the output files so that debuggers can pick it up and present more useful information during the debugging process. Exactlywhatgets stored can depend a great deal on the environment you're running in. One way to look at what this consists of is to useobjdumpwith the--debuggi...
I wrote this small C program: ``` #include <stdio.h> #include <stdlib.h> int main() { FILE * fp; fp = fopen("data.txt","w"); fprintf(fp,"%d",578); return 0; } ``` Then I analyzed data.txt usingxxd -b. I was expecting that I will see the 32 bit representation of 578 instead I saw the ASCII representation of 578...
Usefwrite: ``` uint32_t n = 578; fwrite(&n, sizeof n, 1, fp); ``` fprintfis forformattedoutput, whence the trailingf.
The thing is that i want to get the number of elements from a specific folder. Its posible? I've made this: Is a good practice? Is there any function? ``` main(){ char path[6]="#.txt"; int i=49,a=1,c=0; //for 9 elements while(a){ path[0]=i; if(fopen(path,"r")){ c++; printf("%i",c); } else a=0; i++; } ...
Here's your hint:FindFirstFileandFindNextFile The number of times the return value isTRUEis the number of matching files.
Is there a way to do something like this. ``` printf("Display Time is %S\n",system("date")); ``` I know I can use the time structure to printout the date but I would like to know whether I can do something like this.
system("date > out.txt"); after read out.txt or popen()
I'm trying to create a simple program or function that will take the users input which could be a valid hex number. I'm trying to work out a way to verify that it's a correct hex value and return the hex value if it's true or return an error message if it's false. I was thinking of a function that checks every char ...
Givenconst char *s, if you want to determine if every character in the string pointed to bysis a valid hex digit you can use: ``` if (s[strspn(s, "0123456789abcdefABCDEF")] == 0) { /* valid */ } ```
this code will good for n<20, but for n=40 give me access violation error: this code will fill X and O random. ``` int i=0,j=0; int x=0,y=0; int n=40; for(i=0;i<n;i++) { for(j=0;j<n;j++) arr[i][j]='O'; } srand(clock()); for(i=0;i<n*n;i++) { x = rand()%n; y = rand()%n; if(arr[x][y] == ...
change ``` arr = (char**)malloc(n); ``` to ``` arr = (char**)malloc(n*sizeof(char*)); ```
I have an .obj parser, code is: ``` class Model { public: List *coords; List *tcoords; List *normals; List *faces; Model() { coords=new List(); tcoords=new List(); normals=new List(); faces=new List(); } ~Model() { delete(coords); delete(tc...
Typically, you create a peer class on the Java side that holds a pointer to the class in a long variable. Jim S.
I wrapped the SDL functions in C++ classes in order to make it simple for me to use them without complicating the code, but I wonder if it is good practice to do so, as, as far as I know, SDL is written for C, no? Also: The Core class I made is the one which initializes the screen, so is there any way I can make the...
SDL is writteninC, not justforC. It's perfectly fine to write a C++ wrapper round it if you want to. As far as the screen goes, you make it available to other classes in exactly the same sort of way you'd make anything else available - you either pass the pointer around (sensible) or use some sort of global access po...
Is there a straight-forward way to extend this rand() function (from K&R's "The C Programming Language") to yield 64 random bits instead of 15? ``` int rand() { rand_next = rand_next * 1103515245 + 12345; return (unsigned int)(rand_next/ 65536) % 32768; } ``` EDIT: And what I mean by that is changing it to use 6...
Linear congruential generators exist for any number of bits. For 64 bits, MMIX (for example) uses the following recursive formula: ``` x = x * 6364136223846793005 + 1442695040888963407; ```
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he...
FromLSP(page 28): Yes, this function’s name is missing an e. Ken Thompson, the creator of Unix, once joked that the missing letter was his largest regret in the design of Unix.
I am doing a major upgrade, therefore, if the user has pinned the application on the StartMenu before the upgrade, the user will lose it after the upgrade. So I have created a custom action in the installer to programmatically create a shortcut to the application in the Start Menu folder. However, that change does no...
It isnot possibleto programmatically pin applications to the Start Menu. This is a design decision Microsoft has made, fueled mainly by programs that kept insisting they wanted front row seats on what ultimately is the user's establishment. I realize that your purpose here is benevolent since you only intend to do th...
Is there a way to tell whether a file is in local disk or NFS in C? The code should be portable across various linux distros and shouldn't rely on system calls (e.g. stat -f).
You want to usestatfsfrom<sys/vfs.h>. int statfs(const char *path, struct statfs *buf); struct statfs { __SWORD_TYPE f_type; /* type of file system (see below) */ Here's how to use it: ``` struct statfs s; if (statfs("/etc", &s)) perror("statfs"); switch (s->f_type) { case EXT2_SUPER_MAGIC: break; ...
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 Does anyone have any knowledge of C or c++ tutorials that teach the language on video and through examples?
FredOverflowdidstart such a list(you need enough rep to see deleted questions to see this one) for C++ a while ago, which via some detours ended up on theC++ chat room's wiki:http://loungecpp.wikidot.com/videos-and-podcasts-by-c-celebrities
I have the following struct: ``` struct Node{ int *VC; Node *Next; }; ``` My goal is to create a linked list of pointers pointing to anint My question is how can i allocate memory forNode. ie ``` int* ptr = (int *) malloc(sizeof(int)*10); //code to allocate memory for a new Node n n->VC = ptr; n->Next = nu...
Allocating memory for astructis the same as allocating memory for anint(in C). Just usesizeofto get the size of the struct: ``` struct Node *n = malloc(sizeof(struct Node)); ```
What is the way to parse a given jstring without std? I am in android, and cannot fint a way to use string functions. Is it not available? I d like something similar then: .replaceAll, .split, .startWith, or StringTokenizer, etc in Java. "jni/hello-jni.cpp:207: error: 'string' in namespace 'std' does not name a t...
I guess that by "without std" you mean without C++ andstd::stringin particular. In that case you can use any standardC string functionsor throw in your own as you feel need. For conversion fromjstringtoconst char *you can lookhere.
I have the following string:"http://www.google.ie/".I want to create a string"www.google.ie" How do I do this in C? Here's what I've tried so far: ``` char* url="http://www.google.ie/"; char* url_stripped=NULL; char* out=strtok(url,"http://"); while(out){ out=strtok(0,"."); url_stripped=out; break; } pri...
C library gives you a lot of function to work with! So, a suggestion to begin with, is to give a look here:http://www.cplusplus.com/reference/clibrary/cstring/so you can choose the function that fits your needs.. instead of reinventing the algorithm i suggest to work with you already have! good work!
for example in Python: ``` number = struct.unpack('!L', socket.inet_aton(ip))[0] ip = socket.inet_ntoa(struct.pack('!L',number)) ```
inet_addr,inet_aton,inet_ntoa, there are quite a few functions, try looking up the documentation.
I've addedC:\cygwin\binto my windows path, yet it's still not detecting g++ or gcc when I try to compile from source. Is there anything I'm missing here? Just installed Cygwin 1.7
Cygwin would create a shortcut in start menu calledCygwin Bash Shell. You don't have to setPATHif you use this. Compilation tools likegccandg++is not installed by default, are you sure you've installed all of them? btw: I also installed thesshtool ofCygwin, which enables me to connect toCygwinusing other terminals l...
Is the defacto method for comparing arrays (in C) to usememcmpfromstring.h? I want to compare arrays of ints and doubles in my unit tests I am unsure whether to use something like: ``` double a[] = {1.0, 2.0, 3.0}; double b[] = {1.0, 2.0, 3.0}; size_t n = 3; if (! memcmp(a, b, n * sizeof(double))) /* arrays eq...
memcmpwould do anexactcomparison, which is seldom a good idea for floats, and would not follow the rule that NaN != NaN. For sorting, that's fine, but for other purposes, you might to do an approximate comparison such as: ``` bool dbl_array_eq(double const *x, double const *y, size_t n, double eps) { for (size_t ...
When I write code, I'd like to use ANSI C style, but the code style inc.vimtemplate is K&R. Where can I get another template or any other plugin instead ofc.vim?
You should check:help cinoptions-valueand define your own C style. IIRC, you need toset cindentso that cinoptions are taken into account. FWIW, it is what I do when opening a C or h file : ``` setlocal cinoptions={0,:1s,g1s,t0,(0,=.5s setlocal noautoindent setlocal nosmartindent setlocal cindent ```
I want to port the following regex from python: ``` HASH_REGEX = re.compile("([a-fA-F0-9]{32})") if HASH_REGEX.match(target): print "We have match" ``` to C with apr-utils apr_strmatch function: ``` pattern = apr_strmatch_precompile(pool, "([a-fA-F0-9]{32})", 0); if (NULL != apr_strmatch(pattern, target, strlen...
apr_strmatchdoesn't do regular expression matching at all; it does ordinary substring search using theBoyer–Moore–Horspoolalgorithm (seesource). For RE matching in C, tryPCRE.
Is there a way to check if the compiler generates equivalent code for iteration using pointers and iteration using indexing??? i.e. for the codes ``` void f1(char v[]) { for(int i=0; v[i]!=0;i++) use(v[i]); } ``` and ``` void f1(char v[]) { for(char *p = v; *p!=0; p++) use(*p); } ``` I use mi...
Put a breakpoint in the function.Verify that you compile in Release (otherwise it will surely be different) with debug information turned on.Run.Open the Assembly window to see the generated assembly (usually Alt+8).
I create an input stream from a string with ``` pANTLR3_UINT8 input_string = (pANTLR3_UINT8) "test"; pANTLR3_INPUT_STREAM stream = antlr3StringStreamNew(input_string, ANTLR3_ENC_8BIT, sizeof(input_string), (pANTLR3_UINT8)"testname"); ``` and then use my lexer and parser to process the string. When I'm done with this...
I believe what you're looking for is thesetCharStream()function.
Are there any 32-bit checksum algorithm with either: Smaller hash collision probability for input data sizes < 1 KB ?Collision hits with more uniform distribution. These relative to CRC32. I'm practically not counting on first property, because of limitation of storage space of 32 bits. But for the second ... seems ...
How aboutMurmurHash? It issaid, that this hash has good distribution (passes chi-square tests) and good avalanche effect. Also very good computing speed.
It is well known that both C++ takes features from C but that C also standardizes C++ features. C1x has gained full expression temporaries (previously it only had sequence point temporaries). C1x also took from the C++11 threading effort. I wonder what other features C1x took from C++?
Some similarities include: static assertions:_Static_assert ( constant-expression , string-literal );atomic supportunicode support - adds some typedefs (e.g.char16_t=uint_least16_t), literals, and utilities._Generic _Genericis really more like overloading than what we have with the power of templates. The ubiquitous...
I need to generate a sine wave to fill a char table of size 1024. The word size on the microcontroller is 16-bit and floating-point operations are not available. The sine wave itself will oscillate between the value of 0 to 255, with 127 being the center point. Any ideas?
You only actually need to store one quarter of the sine wave -- you can lookup the other three quarters from the first quadrant. So you only need 256 bytes. To generate the values on the micro controller, implementCORDIC. You can store one value, and generate the whole sine wave from that.
I was going through the existing code and when debugging the UTC time which is declared as unsigned int utc_time; I could get some positive integer every time by which I would be sure that I get the time. But suddenly in the code I got a negative value for the variable which is declared as an unsigned integer. Plea...
Unsigned integers, by their very nature, canneverbe negative. You may end up with a negative value if you cast it to a signed integer, or simply assign the value to a signed integer, or even incorrectly treat it as signed, such as with: ``` #include <stdio.h> int main (void) { unsigned int u = 3333333333u; ...
This is actually not as simple as I first thought. In the absence of a hardware RNG, what is the best way to seed a Mersenne Twister? Or should I say, what is an acceptable way to seed a a Mersenne Twister RNG that is used to generate UUID's?
There is a nice discussion of pseudo-random number generatorshereincluding a section on the proper seeding of PRNGs (see rule 3), which usesmd5sumand/dev/randomor/dev/urandomto generate seeds. This also includes a number of PRNG alogrithms which are a lot easier to code up (< 10 lines of code) than the MT but are arg...
Is there a generic solution out there to create a 1-D histogram array of data from an input 1-D array of double-precision data? Not looking to plot the histogram in C, I just need something to create the histogram 1-D array by binning the data. Could someone help me understand what the binning (e.g. loop) code may l...
``` int* bin = calloc(hist_pts,sizeof(int)); float interval = (float)(max - min ) / num_bins; for (i=0;i<N;i++) bin[ (int)((value[i]- min)/interval) ]++; //don't forget to `free(bin) after you use it. ```
without -g flag: ``` (gdb) break main Breakpoint 1 at 0x8048274 ``` with -g flag: ``` (gdb) break main Breakpoint 1 at 0x8048277: file example.c, line 31. ``` I vaguely know -g option stores the symbol table information. What does the -g option exactly do?Is there any way I can look at this symbol table?
-g(forgcc) stores debugging information in the output files so that debuggers can pick it up and present more useful information during the debugging process. Exactlywhatgets stored can depend a great deal on the environment you're running in. One way to look at what this consists of is to useobjdumpwith the--debuggi...
I wrote this small C program: ``` #include <stdio.h> #include <stdlib.h> int main() { FILE * fp; fp = fopen("data.txt","w"); fprintf(fp,"%d",578); return 0; } ``` Then I analyzed data.txt usingxxd -b. I was expecting that I will see the 32 bit representation of 578 instead I saw the ASCII representation of 578...
Usefwrite: ``` uint32_t n = 578; fwrite(&n, sizeof n, 1, fp); ``` fprintfis forformattedoutput, whence the trailingf.
for example in Python: ``` number = struct.unpack('!L', socket.inet_aton(ip))[0] ip = socket.inet_ntoa(struct.pack('!L',number)) ```
inet_addr,inet_aton,inet_ntoa, there are quite a few functions, try looking up the documentation.
We are considering which parallel framework forC/C++to use. We have some very special conditions and are not 100% sure, that e.g.TBBcan add something "more". There areNrunning threads and one synchronized workqueue (usingpthreadmutex).Our jobs are prioritized (int).Jobs are put into the queue and idle thread takes a ...
TBB 4 provides a concurrent_priority_queue (search 'priority' in thereference manual). Furthermore, using TBB is nice if you can design your program with tasks, not threads, in mind. Indeed, it provides a lot of stuff to describe dependancies between tasks. Also, TBB seems to be fairly portable if it's important for y...
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he...
Correct. In both case you increase bufCnt. But without else if you increase bufCnt two times.
OK, when a program tries to access a page which is not there in the physical memory, we say a page fault has occurred. But say, program tries to write to a page which is read-only and is there in the physical memory. What is that fault called?
According to Intel terminology, it'smemory access violation, aka#AVexception. (I know, there is [linux] tag, but also there is [x86] tag.)
How to test context switch performance? Firstly, we need to know all the scenarios of context switch. I'm NOT sure that I'm able list all those scenarios: process context switchthread context switchprocess signal context switchkernel thread context switchinterrupt context switch Secondly, is there any way or metho...
You forgot system call induced context switch :-) The lmbench benchmark suite has the lat_ctx test that tests context switch times. You can run it on your hardware to test the cost of context switches (http://www.bitmover.com/lmbench/) In addition, recent Linux version has a performance testing tool called "perf" wh...
How to compile 32bit x86 application in 64bit x86 environment? Any command for cc/ld/ar, including options? Thanks. Any links is well appreciated. Thanks. Note: take c code for example.
To compile and link a C source file with a 64-bit multilib GCC, you can do the following: ``` gcc -m32 -c somefile.c gcc -m32 somefile.o -o myprog ``` Note that all 32-bit libraries need to be installed and useable by the multilib compiler. arshould work, if built correctly, it is discouraged to calllddirectly, bec...
I have a multi-threaded program and cannot figure out why the printf does not work as expected. This is my code: ``` #include <pthread.h> #include <stdio.h> void *Msg(void *arg) { pthread_t x; x= pthread_self(); printf("x=%ld\n", x); printf("This MSG from a thread \n"); pthre...
You should join the threads togive them a chance to runbefore the main thread exits. When one thread exits the process all the other threads are killed. Try: ``` pthread_join(n, NULL); return 0; ```
How do I make the functions align at 4-byte boundaries with GCC, target 680x0? -malign-functions=4does not seem to do the trick, by itself anyway. Some kind of option meant to improve cache performance on 68020 and up perhaps?
-malign-functions=4should do the trick but it can be overridden with thefunction attributealigned(). Make sure that your code doesn't use this (for example with a macro).
I am using fputs to write strings to file, but under the debug mode, the content is not written to disk after the statement fputs. I think there is some buffer. But I would like to debug to check whether the logic is correct by viewing the content directly. Is there anyway to disable the buffer? Thanks.
You have a couple of alternatives: fflush(f);to flush the buffer at a certain point.setbuf(f, NULL);to disable buffering. Wherefis obviously yourFILE*. ie. ``` #include <stdio.h> int main(void) { char s[100]; FILE *f = fopen("test.txt", "w"); setbuf(f, NULL); while (fgets(s, 100, stdin)) fputs...
Let us say that I declare and initialize ``` int a[3] = {1, 2, 3}; ``` How can I later asisgn the entire array in one fell swoop? i.e. ``` a = {3, 2, 1}; ```
If your c compiler supports compound literals, you can usememcpy: ``` memcpy(a, (int[]){3, 2, 1}, sizeof a); ``` If you don't plan to stick any variables in there (you can; isn't C99 amazing?),(int[])can be replaced by(const int[])to put the literal into static memory.
So my question is pretty simple, I guess it has been answered before but I can't get my hands on a good thread about it: can I parse a file once, gather some needed information to initialize my structures and then parse it "for real" a second time? When I callyylex()twice it just doesn't seem to do anything. Or is it...
Useyyrestart(FILE *in). But note that theflex manualsuggests that instead of a two-pass scanner like this, you should build a parse tree the first time.
I am trying to understand bishift operations better so I wrote myself a little program. ``` unsigned char a = 240; a= (a << 3) >> 7; printf("a: %u\n",a); ``` Now I would imagine that the result would be something like : ``` 11110000 // 240 10000000 // << 3 00000001 // >> 7 ``` So 1, but I get 15. I am confused... ...
Your problem is that this statement :(a << 3)converts the input to anint. So at this point you have240 * 2 ^ 3 = 1920 ``` 00000000000000000000011110000000 ``` Then you are dividing the previous result by2 ^ 7 = 128so you have :15 ``` 00000000000000000000000000001111 ``` Which is exactly what you are getting as a r...
Recently, I had to implement a stream library,libstream, for one of my projects. Basically, it's achar-FIFO implemented as a linked list storing chunks of 4k bytes each (instead of one large chunk), with wrapper functions such asread(),write()andpeek(). Seemingly, there's nothing comparable available on the net, at l...
There is an I/O Stream library from A&T Research underCommon Public License 1.0, calledSFIO: A Safe/Fast I/O Librarywhich you might want to give a look. It is downloadablehere. It is difficult to answer Why there are no generic more commonly available stream libraries in open domain because pretty much everything in ...
If I want to transport a signed long (32 bit integer) across the network what do I do? If I send as a signed long then at other end I won't know (potentially) how remote machine represents signed numbers? So what do I do?
Just usentohlandhtonland cast or implicitly convert back and forth betweenuint32_tandint32_t.
I am converting some old OpenCV code using the C api to the new C++ API in OpenCV 2.3. I am wondering what the method is to replace thecvGetSubRectcall is? I have the following,cvGetSubRect(some_cv_mat_pointer, another_cv_mat_pointer, some_cv_rect); What is the equivalent to this in the C++ api?
You create an roi on the source image which gives you a new image - there is no actual pixel copying it all happens automatically ``` Mat image(.....) // original image Rect roi(10, 20, 100, 50); // shape of roi Mat image_roi = image(roi); /// really a window into image, copy it if you need to...
I am writing a windows kernel mode driver in which I will have to manipulate lots of strings. Everywhere it has been advised to use "Safe String" functions instead of normal C functions. However, many of the string functions haven't been implemented e.g. strchr, strstr. My question is whether there are any functions ...
You can use regular C runtime functions like strstr() in a driver. Avoid focusing on finding a safe version of that function, none exists. There's no scenario where strchr() or strstr() can corrupt memory unintentionally. They only read, they don't write. They can certainly cause a blue screen if the input strings...
I have a library; call itlibdog.so. I do not have the source tolibdog.so. I do not have the.ofiles which went intolibdog.so. ``` ldd libdog.so libdogfood.so.1 => not found ``` libdog depends on libdogfood. I have a static dogfood library,libdogfood.aandlibdogfood.la. I want to create a new library,libcompletedog.so...
Most UNIX systems (AIX is the exception) consider.solibraries a "final" product of the link, that can not be relinked into something else. If yourlibdogfood.ais a 32-bit library, you might be able to link it intolibdogfood.so.1, and thus satisfy the missing dependency: ``` gcc -shared -o libdogfood.so.1 \ -Wl,--who...
I have a Xilinx Virtex-II Pro FPGA board that is attached via RS232 to an iRobot Create. The iRobot takes a stream of byte integers as commands. I've found that printf will actually send over the serial port (Hypterminal is able to pick up whatever I print), and I figure that I can use printf to send my data to the ...
Usefwrite: ``` char buf[] = { 0x80, 0x80, 0x80 }; fwrite(buf, 1, sizeof(buf), stdout); ``` You can write to any file handle;stdoutis just an example to mirror yourprintf. On a Posix system, you can also use the platform-specificwritefunction that writes to a file descriptor.
The question is actually somewhat broader. Based on the last 15 years experience I currently assume that size of types is as follows: ``` byte = 8 bit short = 2 bytes int = 4 bytes long long = 8 bytes ``` Is there a modern OS where this assumption can be challenged?
Whether or not such "modern" systems exist, you shouldstatic_assertassert those assumptions in your code so that if your code is ever ported to a platform where the assumption is incorrect, the person doing the porting will be alerted to the problem immediately.