question
stringlengths
25
894
answer
stringlengths
4
863
Can anyone please help me understand how the output is3 2 15for the following code? I am expecting output as:2 2 15because first the elementa[1]i.e1will get pre-incremented andiwill be assigned2,thenjwill also be assigned2because post increment is done and,when it comes tom,a[i++]should be asa[2]i.e15, since post increment is done andmshould be assigned15. Please help me if I am wrong. ``` #include<stdio.h> int main() { int a[5]={5,1,15,20,25}; int i,j,m; i=++a[1]; j=a[1]++; m=a[i++]; printf("%d %d %d\n",i,j,m); return 0; } ```
``` int a[5]={5,1,15,20,25}; ``` Incrementa[1]to2, and setito that ``` i=++a[1]; ``` Setjtoa[1](2),thenincrementa[1]to 3 ``` j=a[1]++; ``` setmtoa[i](a[2], or 15),thenincrementito 3 ``` m=a[i++]; ```
I have a rather simple question: I want to write a library (to be used in other projects via a.sofile) which uses the C11-Specific_Generickeyword. I would love it if projects using the library did not need to compile their project using the C11 standard. Is this possible? PS: I Googled a bit and didn't see an answer, and I'm on my phone, so, as a forewarning, there's no "Possible Duplicates" list on my screen.
The .so file will know nothing about_Generic, the decisions that this feature makes are at compile time. What you should worry about are your header files. If you'd have "stray"_Genericin there and a client has a pre-C11 compiler, this would crash. So you'd have to#if/#elsethe part of your headers with__STDC_VERSION__to protect pre-C11 compilers to see this.
I am not really that advanced in C but I found this in a piece of code ``` ssize_t ret = 0; ret += sprintf(buf + --ret, "\n"); ``` What does this mean?And can we really do--retin this case?
``` ret += sprintf(buf + --ret, "\n"); ``` The above line does not mean anything, because it isUndefined Behavior (UB). Thus, the answer is an emphaticNo!. Why? Becauseretis written twice, and there is no intervening sequence-point. (The actual increment ofretcan happen at any time after reading it to determine the value of--ret, and before the closing semicolon.Thus, it conflicts with the change by the assignmentret += ....Also, the read ofretinret += ...conflicts with the update ofretin--ret.) As an aside, in C++ since C++11 (sequencing instead of sequence-points) it would be well-defined.
I have a switch case that looks like this: ``` switch ( class.Function() ) { case firstThing: { } break; case secondThing: { //call third thing } break; case thirdThing: { } break; } ``` Is there any way to call a specific case in C / Objective-C?
Don't know why you would want to do that, but in your example, if you simply leave out the break statement at the end of case secondThing: the user will continue through the subsequent case statement until they hit a break.
I want to write anintegertobinaryfile which inside it there are a lot ofintegers. I want to know how toinsertan integerbetweenfile without changing the value of integersbeforeandafterit. The problem with below code is that it changes the value of the integer after file pointer. ``` int a=5; fwrite(&a,sizeof(int),1,fp);//fp is a FILE * ```
Something simple you can do is read the file into memory then write the first half back to the file then insert your integer and then continue writing the rest of the file. Or you can use fputs or fprintf to append to the end of the file your integer.
This question already has an answer here:mktime returns wrong timestamp (off by a whole month)(1 answer)Closed8 years ago. I've been trying to use mktime to get which day of the week it is for whatever date I use. But it keeps returning wrong values for wday and yday. I don't care about yday but I'm not sure what the problem. Ive looked over the code multiple times, searched around on the internet etc..., and I've finally run out of ideas of what I could be doing wrong. Here's a pic of the code and values after calling mktime. If someone could give me a hand I'd appreciate it. Thanks
According tothe documentation, thetm_monfield is 0-based, so 1 is actually February. Thetm_mdayfield is, however, 1-based. It's kind of annoying that they're different.
Consider the following type in C11, where MyType1 and MyType2 are previously declared types: ``` typedef struct { int tag; union { MyType1 type1; MyType2 type2; } } MyStruct; ``` I'd like to allocate enough memory usingmallocto hold thetagattribute andtype1. Can this be done in a portable way? I guess,sizeof(tag) + sizeof(type1)may not work due to alignment issues. Can I calculate the offset of type1 from the beginning of the structure in a portable way?
You can useoffsetof(), and since that will include both the size oftagand any padding, it's enough to then add the size oftype1: ``` void *mys = malloc(offsetof(MyStruct, type1) + sizeof (MyType1)); ```
Is it possible with the C++ preprocessor to emit an#errorif a particular#defineis used? Something like this: ``` #define this_must_not_be_used #error You shouldn't use that. ```
In C++11, ``` #define this_must_not_be_used static_assert(false, "You shouldn't use that."); ``` In C11, ``` #define _Static_assert(0, "You shouldn't use that."); ``` For C before C11 or C++ before C++11, you'll have to think up some other invalid expression that contains a string that will show up in the error message. I'm thinking along the lines of ``` #define this_must_not_be_used ("You shouldn't use that",) ```
I have matrix that is used for rotation: ``` CvMat* rot_mat = cvCreateMat(2, 3, CV_32FC1); cv2DRotationMatrix(center, angle, scale, rot_mat); ... ``` This matrix is used for image operations. ``` cvWarpAffine(..., ..., rot_mat, ..., ...); ``` I have to know, how this matrix should affect exact pixel - location it should be transfered. How can I multiply 2D point (pixel location) and my matrix to find out where pixel should be transferred?
I found an answer to this in thisforum. Just in case the link fails here is the solution: ``` cv::Point2f operator*(cv::Mat M, const cv::Point2f& p) { cv::Mat_<double> src(3/*rows*/,1 /* cols */); src(0,0)=p.x; src(1,0)=p.y; src(2,0)=1.0; cv::Mat_<double> dst = M*src; //USE MATRIX ALGEBRA return cv::Point2f(dst(0,0),dst(1,0)); } ```
How can i map numbers like this: ``` 1 => 0x01; 2 => 0x03; 3 => 0x07; 4 => 0x0F; .... 8 => 0xFF; ``` I have only 8 numbers to map and i need this for my RT embedded system so the solution must be efficient. Is there a way to implement this using ENUM or DEFINE? I don't want to use switch statement. Should i use an array: ``` BYTE bMap[8] = { 0x01, 0x03, 0x07, 0x0F, .... 0xFF, } ``` or is there another way? Thank you! Max.
The two most obvious solutions would be: Use an array.const uint8_t masks[] = { 1, 3, ... }.Your mask seems to be "thei + 1rightmost bits should be set", so you can trivally compute that at runtime using(1 << (i + 1)) - 1which is easier to implement and less error-prone.
A quick search on RDS points to the linux man page of reliable datagram socketshttp://linux.die.net/man/7/rds Has anybody used it if yes how are they different from TCP or UDP sockets ?
A few links: http://linux.die.net/man/7/rds Currently, RDS can be transported over Infiniband, and loopback. RDS over TCP is disabled, but will be re-enabled in the near future. [rds-devel] What is RDS and why did we build it ?: .... is a socket interface - existing UDP apps usual run on RDS with no modifications or require minimal change. RDS Wire Specification 3.1: The RDS protocol allows multiple reliable datagram socket operations between two nodes to share a single connection-oriented connection.Currently supported transports include TCP sockets and IB Verbs Reliable Connected connections. In other words, it sounds like a message-oriented stream implemented as UDP over TCP.
I have a function that takes as input a number of bits, and returns the number of bytes required to store those bits: ``` unsigned int get_number_of_bytes(unsigned int number_of_bits); ``` So, assuming 8 bits per byte: number_of_bits= 0 => function returns 0number_of_bits= 1 => function returns 1number_of_bits= 8 => function returns 1number_of_bits= 9 => function returns 2 A possible implementation would be: ``` unsigned int get_number_of_bytes(unsigned int number_of_bits) { if (number_of_bits == 0) return 0; else return (number_of_bits - 1) / CHAR_BIT + 1; } ``` (CHAR_BITis usually equal to 8.) How to code this function without anif(and without a?:operator)?
``` unsigned int get_number_of_bytes(unsigned int number_of_bits) { return (number_of_bits + CHAR_BIT - 1) / CHAR_BIT; } ```
For a double value stored inx, how large doesbufferneed to be in the function call below? ``` sprintf(buffer, "%.*g", DBL_DIG, x); ```
The worst case will be : one minus-if number if negativeone decimal point.DBL_DIG decimal digitsthe exponent part that should not be greater thate+999(*)the terminating null So the size of buffer should beDBL_DIG + 8. (*) According to wikipedia page on [IEEE floating point] the exponent part for a double is at most 21023< 10308. So the decimal representation of the exponent need at most 3 digits. Of course above stuff only has sense for IEEE754 compliant floating point implementations (thanks to Basile Starynkevitch for noticing)
I came across a problem where _dl_resolve_conflicts was crashing. After a bit of search found it linked error while resolving pre-linked elfs. Can anyone throw some insight.
If you know in advance that some combination of object files will be referenced by a program, then pre-linking will fix up any references between that set of object files. The linker will still need to fix up references between your program and the object files.
We have the dot operator in structures to access a particular element of struct. Now if I have a structure: ``` struct x { int a; float b; }; ``` and I create an objectstruct x obj, then how exactlyobj.bis interpreted in the compiler in order to access b?How is the address location of b in the structure computed?
Every instance ofstruct xwill have the same layout, which is determined according to the ABI of your platform. The C standard puts some requirements on this layout, such as that members must be arranged in declaration order, but platforms have considerable flexibility concerning alignment and padding. The layout of data typestruct xwill be combined with knowledge of whereobjbegins in memory, in order to locateobj.b. If you are interested in learning the layout, you might want to use theoffsetofmacro found in<stddef.h>.
I tried like ``` int a=b=3; ``` but the compiler says'b' undeclared. Please help, thanks.
You can use,to declare the variables in a single line first ``` int a, b, c, ... , last; ``` and then you can assign to them all at once ``` a = b = c = ... = last = 3; ``` note that ``` int a = b = 3; ``` which is equivalent to ``` int a = (b = 3); ``` will declareaand initialize it with the resultb = 3, which in turn will assign3tob, which isUNDECLARED
This question already has answers here:Printing the physical address of a C pointer(2 answers)Closed8 years ago. When we print the address a variable in c program, as per my understanding it displays the virtual address because every time it comes same (except for auto variables). Is there any way we can know the physical memory address. I am using Linux 32 bit machine.
There is no easy and portable way to do so. The mapping between virtual and physical address happens via the memory management unit of your OS, which is free to move the data around as it sees fit.
I wrote a program with CodeBlocks on Windows and when I try to compile it in a Unix Terminal it shows me multiple errors and warnings. I'm almost sure it's connected to differences in text formatting differences between these two systems. Sometimes something similar happens when you copy a code from website etc. My question is how to reformat.cfiles to be able to compile it withcccommand in a Unix terminal without rewriting the whole program?
The text formatting of the source file of a C program should be irrelevant. Unless the file is encoded in such a way that the compiler itself cannot read (for example you wrote it all in Kanji instead of ASCII characters). You have not provided either the source file, the errors when compiled under Windows, the errors, if any, when compiled under Unix or even the commands you are trying to run and the versions of the compilers. Without further information no better answer can be provided.
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.Closed8 years ago.Improve this question ``` char* mystrcpy(char* dest, const char* src) { int i; for (i = 0; i < mystrlen2(src); i++) dest[i] = src[i]; dest[i] = '\0'; return dest; } ```
Strings are implemented in C as arrays of characters and are accessed through a pointer to the first element in the array. The char*'s in this function are such pointers.
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.Closed8 years ago.Improve this question What these C macros get expanded to ? ``` #define PERIPH_BASE ((uint32_t)0x40000000) #define AHB2PERIPH_BASE (PERIPH_BASE + 0x08000000) #define GPIOA_BASE (AHB2PERIPH_BASE + 0x0000) #define GPIOB_BASE (AHB2PERIPH_BASE + 0x0400) #define BLINK_GPIOx(_N) (GPIO_TypeDef *)(GPIO_BASE +(GPIOB_BASE-GPIOA_BASE)*(_N))) #define BLINK_PORT_NUMBER(4) ``` the call to this is ``` GPIO_SetBits(BLINK_GPIOx(BLINK_PORT_NUMBER), BLINK_PIN_MASK(8)); ```
Use-Eoption ofgcccompiler to see the preprocessor output. example:gcc -E program.c -o preprocessOutput.pThen view the contents of the filepreprocessOutput.p
I tried like ``` int a=b=3; ``` but the compiler says'b' undeclared. Please help, thanks.
You can use,to declare the variables in a single line first ``` int a, b, c, ... , last; ``` and then you can assign to them all at once ``` a = b = c = ... = last = 3; ``` note that ``` int a = b = 3; ``` which is equivalent to ``` int a = (b = 3); ``` will declareaand initialize it with the resultb = 3, which in turn will assign3tob, which isUNDECLARED
This question already has answers here:Printing the physical address of a C pointer(2 answers)Closed8 years ago. When we print the address a variable in c program, as per my understanding it displays the virtual address because every time it comes same (except for auto variables). Is there any way we can know the physical memory address. I am using Linux 32 bit machine.
There is no easy and portable way to do so. The mapping between virtual and physical address happens via the memory management unit of your OS, which is free to move the data around as it sees fit.
I'm writing code to resize images with Go and thego-opencv package. After the resize happens, the image that I write out is missing the ICC profile from the original image. Are there any Go or C libraries that can read/write ICC profiles? The goal is to not use command line tools but Go/C libraries so I can do all of this within the process. I know exiftool exists and can do this for me, but I'd rather not shell out to a perl script.
I only know ofgo-iccjpeg: A small utility package to extractInternational Color Consortium (ICC) profilesfrom JPEG buffers. ``` import "github.com/vimeo/go-iccjpeg/iccjpeg" iccjpeg.GetICCBuf(input io.Reader) ([]byte, error) ``` It takes anio.Readerwith a JPEG, and returns a buffer with the embedded ICC profile from that JPEG, if there is one.If there is not one, it returns an empty buffer.
I am studying about ALSA base on this article:http://equalarea.com/paul/alsa-audio.html#interruptex(A Minimal Interrupt-Driven Program) Notice theshort buf[4096];if we declare it as global, Bad address error will be prompted. If we declare it as a local ofint playback_callback (snd_pcm_sframes_t nframes), it run and sometimes prompts Bad address error. If we usemallocto allocatebuf, the error gone. As I see from the source code ofsnd_pcm_writei, it callsioctlto send the buffer to device. So, whyioctlbehaves as I described? I am using Ubuntu 14.04 64bits
That program is buggy. bufhas enough space for 4096 samples, but the device is configured for two samples per frame, so 4096 frames will overflow the buffer.
C standard (e.g. C99) tells thatmalloc(0)returns "a null pointer or a unique pointer that can be successfully passed to free()". Which of the two, isimplementation-defined. (This has been asked on StackOverflow many times, e.g.1,2,3,4.) My question is: how does GCC define it?
GCC doesn't define it at all. GCC uses themalloc()implementation provided by the standard library. On OS X this will be libSystem, on Linux this will usually be glibc or eglibc, etc. These libraries are open source, so you can browse the source code.
I have been trying to allocate a 2 dimensional array at run time usingmallocby using the concept of pointers to pointers. This code doesn't show any compilation error but gives a runtime error. ``` #include<stdio.h> #include<stdlib.h> int ** alpha(void) { int **x; x=(int **)malloc(3*sizeof(int *)); for(int i=0;i<3;i++) { x[0]=(int *)malloc(3*sizeof(int)); } for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { x[i][j]=i+j; } } return x; } int main() { int **p; p=alpha(); printf("%d",p[1][2]); return 0; } ```
The reason for the runtime error is because you allocate memory just forx[0].So, change ``` x[0]=(int *)malloc(3*sizeof(int)); ``` to ``` x[i]=malloc(3*sizeof(int)); ``` anddon't cast the result ofmalloc.
I need a command in cmd that works like pause but I can code to continue. e.g. ``` system("pause"); some lines of code;` ``` The problem withsystem("pause")is that "some lines of code" will not work until the user press sth. I want to continue cmd with some command.
I want something that run the code but update cmd only when I give the permission to it. If I understand correctly,the codeshall produce output which you don't want to be shown before you press a key. If you don't mind to have the output paged, you could use something like ``` FILE *stream = popen("PAUSE<CON&&MORE", "w"); ``` and letthe codeoutput to stream (withfprintf(stream, ...)etc.).
I have been trying to allocate a 2 dimensional array at run time usingmallocby using the concept of pointers to pointers. This code doesn't show any compilation error but gives a runtime error. ``` #include<stdio.h> #include<stdlib.h> int ** alpha(void) { int **x; x=(int **)malloc(3*sizeof(int *)); for(int i=0;i<3;i++) { x[0]=(int *)malloc(3*sizeof(int)); } for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { x[i][j]=i+j; } } return x; } int main() { int **p; p=alpha(); printf("%d",p[1][2]); return 0; } ```
The reason for the runtime error is because you allocate memory just forx[0].So, change ``` x[0]=(int *)malloc(3*sizeof(int)); ``` to ``` x[i]=malloc(3*sizeof(int)); ``` anddon't cast the result ofmalloc.
I need a command in cmd that works like pause but I can code to continue. e.g. ``` system("pause"); some lines of code;` ``` The problem withsystem("pause")is that "some lines of code" will not work until the user press sth. I want to continue cmd with some command.
I want something that run the code but update cmd only when I give the permission to it. If I understand correctly,the codeshall produce output which you don't want to be shown before you press a key. If you don't mind to have the output paged, you could use something like ``` FILE *stream = popen("PAUSE<CON&&MORE", "w"); ``` and letthe codeoutput to stream (withfprintf(stream, ...)etc.).
I decided to turn a program I wrote into a "web app". It's all C. I know it can be easily set up as a CGI binary on Apache, but doing so requires spawning a new process for every single little request, which seems resource intensive and possibly slower than even PHP. Is there a scalable alternative? ASIO or something? If so, what libraries are available? Or should I just turn the program into a PHP extension? My question is basically, can you list all the software/libraries that allow a binary to eventually interact with Javascript on a client?
FastCGI seems like the obvious candidate
So you can do this to createc1andc2as instances ofstruct Complex: ``` struct Complex { int real; int imag; } c1, c2; ``` And you can do this to typedef the anonymous struct: ``` typedef struct { ... } Complex; ``` But is there any way to do both at once?
No, you can't.typedef's syntax is ``` typedef T type_ident; // T is type specified by the declaration specifiers ``` This means that anything aftertypedef Twill be a type name, not the instance of that type. So, in ``` typedef struct { ... } Complex, c1, c2; ``` Complex,c1andc2are all typedef name with the typestruct { ... }.
``` typedef enum Ranks {FIRST, SECOND} Order; ``` I'm not clear on what's going on here. It seems from the rest of the example in the tutorial that I would useOrderto create variables, as inOrder x = 0;, but what isRanks?
Ranksis the name of anenumandOrderis the name of aenum Rankstype, when used you should do it this way ``` enum Ranks ranks; Order order; ``` it is similar to doing ``` enum Ranks {FIRST, SECOND}; typedef enum Ranks Order; ```
I've had a series of bugs over the last month due to mistyping of "&" instead of "&&" in C. My latest one was simple - i.e. I wrote ``` value = data && 0x0123 ``` It was obvious after I hit a break and saw the value was 0 or 1, but I want a way to catch this earlier, similar to coding ``` if (1 == END) ... ``` to catch misuse of=and==. Any ideas?
In C++,andandbitandare alternatives for&&and&respectively (You can find all the alternatives oncppreference). ``` #include <iostream> int main() { std::cout << std::boolalpha << (42 and 0x0123) << std::endl; std::cout << std::boolalpha << (42 bitand 0x0123) << std::endl; return 0; } ``` Live on Coliru(Thanks to Fred Larson for the std::boolalpha suggestion) C99 defines these as macros in iso646.h (Credit goes to Shafik Yaghmour,more details in one of his answers)
I have no ideas on how to do this.. i would appreciate it if someone helps, In a matrix , where prime numbers come first and then composite , sorting is done by columns, Here is an example. Input: ``` 25 3 7 11 15 32 16 9 19 ``` Output: ``` 3 19 32 7 25 16 11 15 9 ```
It may have nothing to do with sorting. Just find the next prime number and insert it in the current position: ``` 25 3 7 11 15 32 16 9 19 3 25 7 11 15 32 16 9 19 3 7 25 11 15 32 16 9 19 3 7 11 25 15 32 16 9 19 3 7 11 19 25 15 32 16 9 3 19 32 7 25 16 11 15 9 ``` We transform the matrix into the line by rows, but then, restore the matrix by columns. Anyway, the example is vague.
I have a function that requires to send a string with<cr>at the end. How can I directly join the string-part with the<cr>= 0x0D in C without using any library function? (I am using uC.) Example array/string "ABC\x0D", but 0x0D should be not sent as ascii but as<cr>.
Provided you have enough room in your array, you simply put at the end of the string a0x0dand a\0. Example : ``` char str[8] = "ABCDEF"; ``` This string contains 6 characters and the terminating null : it can accept the cr. How to do that : ``` str[6] = '\r'; /* or 0x0d or 13 */ str[7] = '\0'; /* or 0x0 or 0 */ ``` That's all...
I have a binary file that has this particular string in it:^@^Aname^@Team Fortress 2 This is how I tried to find it usingmemmem: ``` char *game = "Team Fortress 2"; sprintf(searchString,"\1\1name\1%s\0",game); ... if(pos = memmem(buffer,result,searchString,strlen(searchString))) ``` How do I match the escaped characters^@and^A? It seems to find\1\1name, but not withgameinsearchString.
Because your string contains nulls it isn't a valid C string and string manipulation functions such as memmem and strlen won't work. You'll have to roll your own version. The simplest way is to loop through each index of the string, then use a second loop to check it against the string you're searching for. There are fancier and faster methods, but they are more difficult to understand and implement properly if you don't need the extra speed. SeeWikipediafor an overview of the subject.
I have the following code: ``` #define MY_MACRO(PARAM) int PARAM_int; double PARAM_double; [subsequent instructions] ``` Unfortunately, it does not work, meaning that PARAM is not replaced inside the variables names. Is this solvable some way?
PARAM_intis considered to be a single token, that is distinct fromPARAM. You can concatenate tokens in a macro definition with##: ``` #define MY_MACRO(PARAM) int PARAM ## _int; double PARAM ## _double; ``` Now,PARAMwill expand to whatever you invoke the macro with, and then the resulting token will be pasted together with_intand_double.
As the title, is it possible to initialize a pointer in a struct to point to the first element of an array that is also in the same struct? ``` struct foo { int barr[12]; int* barr_itt; }; struct foo f = {{0}, /*.?.*/} ```
Yes, use the name of the variable ``` struct foo f = {{0}, f.barr} ; ```
I have C code which contains references to requirement numbers of a very simple pattern: ``` /** * Lorem ipsum, you know the routine. * See also: Requirement R12345. */ ``` In other words, the requirement is anRfollowed by exactly 5 decimal digits. I would like to add those to my ctags file so I can jump to tags with:ta R12345. I've read the exctags docs up and down, but could not find any option that would allow this. I thought of grepping for the requirements and patching up the tags file with appropriate lines (using search for line numbers probably makes this easy) but I am not sure if the extra lines would need to be merged or just appended, and what the exact format is.
I must be blind not recognizing the--regex-<LANG>option. This does exactly what I want: ``` ctags ... --regex-c='/\<(R[[:digit:]]{5})\>/\1/' *.[ch] ``` This creates the tags file with additional tags for all R12345 requirements.
I would like to increase the maximum pipe size in linux. I am not talking about F_SETPIPE_SZ... but it seems there is 1MB limit to the pipe size(depends on the linux version I guess) Can anyone let me know how I can increase the max limit?
Changing the value in /proc/sys/fs/pipe-max-size, seems to do the trick :)... Thanks Joachim for your pointer in the right direction. My current linux has the max value as 1048576
Hi I managed to read txt files and printing them on the console window. I was given a task to select and sample a certain amount of data. Example of txt file: ``` Voltage (V),Current (I),Power (W) 50,2,100, 51,2,102, 52,2,104, ``` etc.. How can I display only the column of Voltage and Power?
``` #include <stdio.h> int main(void) { int V, I, W;//float ? FILE *fp = fopen("data.txt", "r"); while(fgetc(fp) != '\n') ;//skip first line while(3==fscanf(fp, "%d,%d,%d,", &V, &I, &W)){ printf("V:%d, I:%d, W:%d\n", V, I, W); } fclose(fp); return 0; } ```
I have following variables in my code ``` uint8_t array[8]; uint64_t epoch; ``` I need to copy the epoch variable into array(msb of epoch should go into array[0]). I did this logic by copying each and every byte individually ``` array[0] = epoch>>56; array[1] = epoch>>48; . . array[7] = epoch; ``` What's the other alternative??
Something like this should be endian-independent: ``` const size_t SIZE64 = sizeof(uint64_t); for(size_t i=0; i<SIZE64; i++) { uint8_t bits = 8 * (SIZE64-i-1); // 8 bits * (8 bytes - byte index) array[i] = epoch >> bits; } ```
is it possible for struct member to point at another member from different struct? I want to do something like reference table. ``` struct a { int a; int b; }; struct b { * struct a.b; }; ``` A guess it's not possible since there is no memory allocated, but I'm open for suggestions.
Sure, just use a pointer ``` struct b { int* p ; //or an array of pointers if you need a table } ; struct a sa = { 1 , 2 } ; struct b sb = { &sa.a } ; printf("%d\n" , sb.p ) ; sb.p = &sa.b ; printf("%d\n" , sb.p ) ; ```
I am using g-soap-2.8 to send a post request to a web service. But the problem is that the web service requiresFrom (Http Header Field) must be present in Header. But gsoap has no context related to From header field. Can anyone explain how to add this particular header field-value pair in gsoap.
Thesoap.http_extra_headerstring can be used for this: ``` soap->http_extra_header = "SomeField: SomeValue(s)"; ``` You can add multiple extra HTTP headers by separating them with\r\nin the string. Set this string before making the call. The string will be reset to NULL when the call completes, so the extra headers do no accidentally bleed into the next calls.
``` AppXYZ(2111,0xb04a3000) malloc: *** mach_vm_map(size=1207959552) failed (error code=3) *** error: can't allocate region *** set a breakpoint in malloc_error_break to debug libc++abi.dylib: terminating with uncaught exception of type std::bad_alloc: std::bad_alloc ``` How to get symbolicated information from the above debugger logs? Like I need to know the class of the address (0xb04a3000), the exact location of the bug in the code and so on.
In gdb, I would just do as it says, i.e. put a breakpoint in the function mentioned: ``` $ gdb AppXYZ [... gdb starts ...] gdb$ break malloc_error_break gdb$ run ``` The reproduce the thing that caused the crash. Informally, it seems to be because it's trying to allocate more than 1 GB of memory in a singlemalloc()call, that's rather daring in some environments.
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.Closed8 years ago.Improve this question Is it possible to create a complete MS DOS application to run in windows 7 and windows 8. I like to create a basic accounting application for personal use.
It's possible to create MS-DOS applications on 32-bit versions of Windows. You need a compiler targeting MS-DOS, such asdjgpp(MS-DOS port of gcc) orTurbo C++. It is not possible to run (and thus, develop) MS-DOS applications on 64-bit versions on Windows. MS-DOS is outdated and it's probably not good idea to write MS-DOS software today. However, Windows applications don't have to be graphical. It's possible to write command line applications for Windows, that run in command prompt. Many people make false assumption that text-mode applications have to be MS-DOS applications.
``` void main() { int a=10; int *j; *j=&a; b[]={1,2,3,4}; b=j; } ``` Some one asked me is there any problem in this program ,i am just confused for me everything seems fine. Just curious to know.
Turn on all your compiler warnings and errors. Then it will tell you exactly what is wrong with the program. *j = &a;is a constraint violation.*jhas typeintbut&ahas typeint *which is incompatible. You might have meantj = &a;which will pointjtoa. b[]={1,2,3,4};is a syntax error. Maybe you meantint b[]={1,2,3,4};which would declare an array. b=j;is a constraint violation becausebis an array and arrays cannot be assigned to. (Technically: becausebis an array, decays to an rvalue and rvalues cannot be assigned to). However,j = b;would be OK and it would makejpoint to the first member ofb; void main()is non-portable, it should beint main().
I have a C file pointer which I must pass to a Fortran77 program (as an integer) only to be used back again in the C program (as a file pointer) for writing more data into a text file. My C skills are outdated since I have forgotten most of it. Can anyone tell me how to convert a C FILE pointer into an integer and back? I would appreciate your help. I am maintaining a legacy code that just worked fine (by accident) a 10 year old compiler. I am having problems porting the code. The new compilers are the intel C and Fortran compilers. I know Fortran 2003 provides ISO bindings for C but I cannot use them here for other reasons.
FromFILE *toint ``` int fildes = fileno(f); ``` FrominttoFILE *: ``` FILE *f = fdopen(fildes, "r+"); ```
I want to display floating point number with fixed width before decimal. So far I managed to do it by taking the integer part, displaying desired width and filling with 0 using "%03d" before number value and then displaying the decimal part. I want to know if there is standard way of displaying like for example "%3.3f". I tried the following ``` printf("value: %3.3f", value); ``` But the result was only 1 digit before decimal. How can I achieve it ?
You can use ``` printf("%07.3f", value); ``` where07means printing at least 7 characters with padding zero. e.g. printf("%07.3f", 3.3); prints 003.300
I wrote some C code to create a python module. I wrote the code myself (did not use SWIG etc). If you're interested, the C code is at the bottom ofthisthread. Q: Is there any way to (hopefully, easily) find whether my C code has memory leaks? Is there any way to use python's awesomeness for finding memory leaks in its extensions?
if you using a linux environment we can easily find the memory leaks by using debugger named valgrind. To get the valgrind first you have to install it from the internet by using command sudo apt-get valgrind after the installation is completed compile your c code using this debugger you can easily find the memory leaks. This debugger shows what is the reason for the memory leak and also specifies the line at which the leak has been occured.
I have defined a structure ``` typedef struct { unsigned short a; unsigned short b; } my_struct; ``` The sending node creates a struct and transfers it using ``` my_struct my; packetbuf_copyfrom((void *)&my, sizeof(data_struct)); ``` The receiving node accesses the data via ``` my_struct *my; my = packetbuf_dataptr(); ``` So far so good. By when trying to access the members a or b of the struct ``` printf("%u", my.a); ``` I get: "error: request for member 'a' in something not a structure or union." If I transfer a simple string and access it everything is fine.
To access members of a structure, through a structure pointer we have to use arrow operator -> (formed by hyphen and a greater than symbol). To access your memberause ``` printf("%u", my->a); or printf("%u", (*my).a); ```
I am working on remote computer. The shell is tcsh with no root privileges. I have no control on the server. I have a script script.pl. When running it: ``` perl script.pl ``` gives the correct results but when I'm trying to send this output to some program I got an error "Illegal variable name." ``` ./vuln $(perl script.pl) Illegal variable name. ``` When i'm working on gdb, the error of course repeats ``` (gdb) r $(perl script.pl) Starting program: /vuln $(perl script.pl) Illegal variable name. ``` How to send the output of the script to the program either on shell and gdb?
tcsh does not understand this substitution syntax $(...) You need to use backticks for portable shell scripts: ``` ./vuln `perl script.pl` ```
I have a program that uses unsigned chars to represent integers with a small range. I find myself needing to clear them to 0 in several different parts of the program, I have also recently started using splint and apparently: ``` unsigned char c = 0; ``` gives the warning: ``` Variable c initialized to type int, expects unsigned char: 0 Types are incompatible. ``` As there is no suffix for a literal char, How is it best to resolve this? I think I have a few options: 1: Ignore the warning. 2: Cast every time: ``` unsigned char c = (unsigned char)0; ``` 3: Make a var to cut down the length of the code: ``` unsigned char uc_0 = (unsigned char)0; unsigned char c = uc_0; ``` 4: A function: ``` static inline unsigned char uchar(int in) { return (unsigned char)in; } unsigned char c = uchar(0); ```
splinthas an option+charintthat will treatcharintas interchangeable.
I have the code: ``` typedef struct foo *bar; struct foo { int stuff char moreStuff; } ``` Why does the following give anincompatible pointer typeerror? ``` foo Foo; bar Bar = &Foo; ``` To my knowledge,barshould be defined as a pointer tofoo, no?
The complete code should look like ``` typedef struct foo *bar; typedef struct foo { //notice the change int stuff; char moreStuff; }foo; ``` and the usage ``` foo Foo; bar Bar = &Foo; ``` Without having the typedef instruct foo, you code won't compile. Also, mind the;after struct definition [and afterint stuffalso, though I assume that's more of atypo].
I wrote some C code to create a python module. I wrote the code myself (did not use SWIG etc). If you're interested, the C code is at the bottom ofthisthread. Q: Is there any way to (hopefully, easily) find whether my C code has memory leaks? Is there any way to use python's awesomeness for finding memory leaks in its extensions?
if you using a linux environment we can easily find the memory leaks by using debugger named valgrind. To get the valgrind first you have to install it from the internet by using command sudo apt-get valgrind after the installation is completed compile your c code using this debugger you can easily find the memory leaks. This debugger shows what is the reason for the memory leak and also specifies the line at which the leak has been occured.
I have defined a structure ``` typedef struct { unsigned short a; unsigned short b; } my_struct; ``` The sending node creates a struct and transfers it using ``` my_struct my; packetbuf_copyfrom((void *)&my, sizeof(data_struct)); ``` The receiving node accesses the data via ``` my_struct *my; my = packetbuf_dataptr(); ``` So far so good. By when trying to access the members a or b of the struct ``` printf("%u", my.a); ``` I get: "error: request for member 'a' in something not a structure or union." If I transfer a simple string and access it everything is fine.
To access members of a structure, through a structure pointer we have to use arrow operator -> (formed by hyphen and a greater than symbol). To access your memberause ``` printf("%u", my->a); or printf("%u", (*my).a); ```
I am working on remote computer. The shell is tcsh with no root privileges. I have no control on the server. I have a script script.pl. When running it: ``` perl script.pl ``` gives the correct results but when I'm trying to send this output to some program I got an error "Illegal variable name." ``` ./vuln $(perl script.pl) Illegal variable name. ``` When i'm working on gdb, the error of course repeats ``` (gdb) r $(perl script.pl) Starting program: /vuln $(perl script.pl) Illegal variable name. ``` How to send the output of the script to the program either on shell and gdb?
tcsh does not understand this substitution syntax $(...) You need to use backticks for portable shell scripts: ``` ./vuln `perl script.pl` ```
I have a program that uses unsigned chars to represent integers with a small range. I find myself needing to clear them to 0 in several different parts of the program, I have also recently started using splint and apparently: ``` unsigned char c = 0; ``` gives the warning: ``` Variable c initialized to type int, expects unsigned char: 0 Types are incompatible. ``` As there is no suffix for a literal char, How is it best to resolve this? I think I have a few options: 1: Ignore the warning. 2: Cast every time: ``` unsigned char c = (unsigned char)0; ``` 3: Make a var to cut down the length of the code: ``` unsigned char uc_0 = (unsigned char)0; unsigned char c = uc_0; ``` 4: A function: ``` static inline unsigned char uchar(int in) { return (unsigned char)in; } unsigned char c = uchar(0); ```
splinthas an option+charintthat will treatcharintas interchangeable.
I have the code: ``` typedef struct foo *bar; struct foo { int stuff char moreStuff; } ``` Why does the following give anincompatible pointer typeerror? ``` foo Foo; bar Bar = &Foo; ``` To my knowledge,barshould be defined as a pointer tofoo, no?
The complete code should look like ``` typedef struct foo *bar; typedef struct foo { //notice the change int stuff; char moreStuff; }foo; ``` and the usage ``` foo Foo; bar Bar = &Foo; ``` Without having the typedef instruct foo, you code won't compile. Also, mind the;after struct definition [and afterint stuffalso, though I assume that's more of atypo].
if player1 inputs: "A5-B2" (ranges: A-G 1-7 ) so char * input = "A5-B2" and i want each data to be held like this: ``` int x1 = 1 (since A should be 1) int y1 = 5 int x2 = 2 (if A=1, then B=2 and so on) int y2 = 3 ``` so I realize I can use strtok which separates a5 from b2 but how do i seperate a from 5 and b from 2?
Use sscanf, ``` int sscanf(const char *str, const char *format, ...); ``` In this , ``` sscanf(input,"%c%d-%c%d",&ch1,&int1,&ch2,&int2); ``` After getting the input in separate variables, for the alphabets use like this. ``` int3=ch1-'A' + 1; int4=ch2-'A' + 1; ``` Ascii value of'A'is 65. You need that as 1. So subtract by'A'and add one, store that in the variable it give that as 1 and so on. If that is lower case then subtract with'a' +1.
``` pthread_t thread_id; while(1) { if(counter < 3) { // do something pthread_create( &thread_id , NULL , handle_me, (void*)arg); } else { // wait for counter to be changed // pthreads will be changing the counter // when changed, go back to beginning of loop counter++; } } ``` i am trying to achieve the following: signal from apthreadto main. what options do i have ? counter is protected by amutexwhen changed in threads.
Use a condition variable. From the thread incrementing the counter usepthread_cond_signalorpthread_cond_broadcast. In the other thread that waits for the signal, usepthread_cond_waitorpthread_cond_timedwait.
I am currently working on an ogl 4.3 project,I am using core profile and ARB_texture_storage is not supported albeit being in 4.2 compat. Is this bug in SDL/my driver or is ARB_texture_storage not in core ?
The functionality ofARB_texture_storageis a core feature since OpenGL 4.2, both in compatibility and core profiles. However, as this is a core feature, there is no requirement that the implementation advertises this also as any existension. In GL >=4.2, theglTexStorage*()familiy of functions is available and can be used, no matter ifARB_texture_storageis in the extension string or not.
I'm using the code below to add some "0" chars into my string, but it seems there is a problem and the program will crash. Everything seems logic but I do not know where is the problem? ``` #include <stdlib.h> #include <string.h> int main() { char *Ten; int i=0; Ten = malloc(12); Ten="1"; for (i=0;i<10;i++) strcat(Ten,"0"); printf("%s",Ten); return 0; } ```
You declareTenas a pointer to a string literal. However, you cannot rely on being able to modify a string literal, and thus the program crashes. To fix this, you can declareTenas an array instead: ``` int main() { char Ten[12]="1"; int i=0; for (i=0;i<10;i++) strcat(Ten,"0"); printf("%s",Ten); return 0; } ``` Note that you need 12 bytes; 11 for the characters and one for the terminatingNULcharacter.
``` #include<stdio.h> #include<conio.h> int main(){ char x[9]; for(i=0; i<=8; i++){ printf("\nEnter your guess: "); scanf("%c", &x[i]); } } ``` What is wrong with this code? When I enter the value for x[i], the loop runs for two times before letting me enter the value for x[i+1]. Someone please solve this out. I know its a simple error(not sure) but this is bugging the crap out of me.
``` scanf(" %c", &x[i]); ``` Note the space before%c. This space will make sure the newline character is ignored. When you enter a character and press enter there is a newline character in the buffer which will be picked up in the next iteration. So you need to ignore it by doing as shown above.
I've two arrays like these ones: ``` char test_results[] = "20 7 1 12 3" int test[] = {3, 8, 9, 12, 6} ``` I would like to take one by one the numbers oftest_resultsand compare it with the numbers oftestarray. If there's any coincidence, print the result. How can I do that? Thank you!
This should be what you need ``` char text[] = "20 7 1 12 3"; int test[] = {3, 8, 9, 12, 6}; char *ptr; int count; ptr = text; count = sizeof(test) / sizeof(*test); while (*ptr != '\0') { int value; int i; value = strtol(ptr, &ptr, 10); for (i = 0 ; i < count ; i++) { if (value == test[i]) printf("there is a coincidence at the %dth number of the array %d\n", i, value); } } ``` it will output there is a coincidence with the 3th number of the array 12there is a coincidence with the 0th number of the array 3
Have this simple struct in my header file ``` struct cont { char fname[10]; char lname[10]; char user[10]; char pass[10]; float price; }s; ``` I am having this linking errors about the declaration ofstruct cont sin the header file. By the way, I have multiple files(.C) containing the functions and the main. Files cant find the structure. Is this the correct way of declaring a global structure? So I can use it for all my files.
The best approach is to Define the structure in the header file.Declare oneexternvariable of that structure type in the header file.Define the variable in one of your.cfiles.
Is there any way of making aforloop iterate a fixed number of times, even though the right side of the interval might be increasing ? I want to do this without declaring an additional variable to use as a copy of the initialinc. For example: ``` for (i = 0; i < inc; i++) { if (condition) { inc++; } } ``` I am pretty sure that ifincincreases, the for will execute more thaninc - 1times. How can I iterate exactlyinctimes, without using a copy ofinc?
``` for (i = inc; i > 0; i--) { if (condition) { inc++; } } ``` This would work since you only assign inc once.
I'm trying to get a setup working for developing mpi programs using Eclipse on OSX Yosemite. My mpi installation was done via homebrew and I have added /usr/local/bin to my path via .bash_profile. My problem is, that when I open Eclipse mpicc is not in my path. I could manually add it to the project configurations or add a PATH environment variable to the project and that would compile, but I can't use Eclipse PTP tools because it still can't find the mpi binaries. So my question is, how do I configure Eclipse to include /usr/local/bin into it's path? Any help would be greatly appreciated.
The answer provided by Alexander O'Mara was correct, so for anyone looking at this, please refer toLaunch mac eclipse with environment variables set
I've two arrays like these ones: ``` char test_results[] = "20 7 1 12 3" int test[] = {3, 8, 9, 12, 6} ``` I would like to take one by one the numbers oftest_resultsand compare it with the numbers oftestarray. If there's any coincidence, print the result. How can I do that? Thank you!
This should be what you need ``` char text[] = "20 7 1 12 3"; int test[] = {3, 8, 9, 12, 6}; char *ptr; int count; ptr = text; count = sizeof(test) / sizeof(*test); while (*ptr != '\0') { int value; int i; value = strtol(ptr, &ptr, 10); for (i = 0 ; i < count ; i++) { if (value == test[i]) printf("there is a coincidence at the %dth number of the array %d\n", i, value); } } ``` it will output there is a coincidence with the 3th number of the array 12there is a coincidence with the 0th number of the array 3
Have this simple struct in my header file ``` struct cont { char fname[10]; char lname[10]; char user[10]; char pass[10]; float price; }s; ``` I am having this linking errors about the declaration ofstruct cont sin the header file. By the way, I have multiple files(.C) containing the functions and the main. Files cant find the structure. Is this the correct way of declaring a global structure? So I can use it for all my files.
The best approach is to Define the structure in the header file.Declare oneexternvariable of that structure type in the header file.Define the variable in one of your.cfiles.
Is there any way of making aforloop iterate a fixed number of times, even though the right side of the interval might be increasing ? I want to do this without declaring an additional variable to use as a copy of the initialinc. For example: ``` for (i = 0; i < inc; i++) { if (condition) { inc++; } } ``` I am pretty sure that ifincincreases, the for will execute more thaninc - 1times. How can I iterate exactlyinctimes, without using a copy ofinc?
``` for (i = inc; i > 0; i--) { if (condition) { inc++; } } ``` This would work since you only assign inc once.
I'm trying to get a setup working for developing mpi programs using Eclipse on OSX Yosemite. My mpi installation was done via homebrew and I have added /usr/local/bin to my path via .bash_profile. My problem is, that when I open Eclipse mpicc is not in my path. I could manually add it to the project configurations or add a PATH environment variable to the project and that would compile, but I can't use Eclipse PTP tools because it still can't find the mpi binaries. So my question is, how do I configure Eclipse to include /usr/local/bin into it's path? Any help would be greatly appreciated.
The answer provided by Alexander O'Mara was correct, so for anyone looking at this, please refer toLaunch mac eclipse with environment variables set
Have this simple struct in my header file ``` struct cont { char fname[10]; char lname[10]; char user[10]; char pass[10]; float price; }s; ``` I am having this linking errors about the declaration ofstruct cont sin the header file. By the way, I have multiple files(.C) containing the functions and the main. Files cant find the structure. Is this the correct way of declaring a global structure? So I can use it for all my files.
The best approach is to Define the structure in the header file.Declare oneexternvariable of that structure type in the header file.Define the variable in one of your.cfiles.
Is there any way of making aforloop iterate a fixed number of times, even though the right side of the interval might be increasing ? I want to do this without declaring an additional variable to use as a copy of the initialinc. For example: ``` for (i = 0; i < inc; i++) { if (condition) { inc++; } } ``` I am pretty sure that ifincincreases, the for will execute more thaninc - 1times. How can I iterate exactlyinctimes, without using a copy ofinc?
``` for (i = inc; i > 0; i--) { if (condition) { inc++; } } ``` This would work since you only assign inc once.
I'm trying to get a setup working for developing mpi programs using Eclipse on OSX Yosemite. My mpi installation was done via homebrew and I have added /usr/local/bin to my path via .bash_profile. My problem is, that when I open Eclipse mpicc is not in my path. I could manually add it to the project configurations or add a PATH environment variable to the project and that would compile, but I can't use Eclipse PTP tools because it still can't find the mpi binaries. So my question is, how do I configure Eclipse to include /usr/local/bin into it's path? Any help would be greatly appreciated.
The answer provided by Alexander O'Mara was correct, so for anyone looking at this, please refer toLaunch mac eclipse with environment variables set
I am working on a project for University which requires me to use POSIX threads in C. I have done most of the work but I have two major problems I can't seem to work out. First, I need to calculate the time a thread has been running. I can't figure which methods or functions I need to use for it.Second I have to display the attributes of each thread (created withpthread_attr_init()) as a message on the screen. Any help appreciated. Thank you.
For the first you can usegetrusage()with the "this thread only" option. For the second, useprintf()to print the fields of your pthread attribute struct.
I'm using Microsoft Visual studio 2013. Trying to import DevIL library to load image files i'm getting LNK1104 error: Cannot open file "IL/devil.lib" My Source.h file which include DevIL libs in Project/Sources directory while the DevIL libs in Project/Sources/IL directory. Here is my code ``` #ifdef _WIN32 #pragma comment(lib, "IL/devil.lib") #pragma comment(lib, "IL/ilu.lib") #pragma comment(lib, "IL/ilut.lib") #endif ```
You just need to add your path lib file to Additional Library Directories in VS. Right click on your project, select Properties/Linker/General, then aim to your lib file in Additional Library Directories path.
I have 2 integers and I want to merge these two numbers as integer.decimal . For example: ``` int a = 12; int b = 54367; double c = aFunction(a,b); ``` then I want c = 12.54367 How can I make this in C? Is there any specific "aFunction" in standard C Library?
I don't think there is anything that merges two integers, but withlog10andpowfrommath.h, it is easy! ``` double aFunction(int a, int b) { int decimals = log10(b) + 1; return a + b*pow(10.0, -decimals); } ```
I need to write a program that prints its input one word per line. Here's what I got so far: ``` #include <stdio.h> main(){ int c; while ((c = getchar()) != EOF){ if (c != ' ' || c!='\n' || c!='\t') printf("%c", c); else printf("\n"); } } ``` The logic is pretty simple. I check to see if the input is not a newline, tab or space, and in that case it prints it, otherwise prints a newline. When I run it, I get results like this: ``` input--> This is output--> This is ``` It prints the whole thing. What goes wrong here?
if (c != ' ' || c!='\n' || c!='\t')This will never be false. Perhaps you meant:if (c != ' ' && c!='\n' && c!='\t')
As we know, the root uid is 0. so I tried to compare current process uid with 0. as follows: ``` uid_eq(get_current_cred()->uid, 0) ``` however, I getincompatible type for argument 2 of ‘uid_eq’ I have also tried ``` uid_eq(get_current_cred()->uid, (kuid_t)0) ``` but this also give thiserror: conversion to non-scalar type requested How should I check if the current process is root in kernel? Thank you.
kuid_tis a struct, so you should declare one, and set it'svalmember to0. Try this ``` kuid_t rootUid; rootUid.val = 0; uid_eq(get_current_cred()->uid, rootUid); ```
characters in C are actually some ascii numbers. Then why following code, which is supposed to swap two characters, gives wrong result ``` void swap(char *a,char *b) { *a=*a+*b; *b=*a-*b; *a=*a-*b; } ```
The result would be weird if the above expression will result in arithmetic overflow. The above method will also fail in case both pointersaandbpoints to the same location*. Try this: ``` void swap(char *a,char *b) { if (a == b) // Check if the two addresses are same return; *a=*a^*b; *b=*a^*b; *a=*a^*b; } ``` *Ifaandbwill point to same location sayx100and let the value stored at that location is0111(in binary), then: ``` *a = *a ^ *b // *a will have now 0000 *b = *a ^ *b // *b = 0000^0000 = 0000 *a = *a ^ *b // *a = 0000^0000 = 0000 ```
In visual studio, for years i have been running programs withF5and Debugging withF11andF10, now when i click those there is an "Error" noise and nothing happens. When i run the program withCtr+F5it worked perfectly. At first i though is because the 2010 VS so i downloaded the 2013 VS and its acting the same there but without the noise. VS2010 after trying the above and VS2013 after trying the above pics attached.
Well,my solution was to format my HDD and download VS...
I want to get ``` int sign[8]= {0,1,0,1,0,1,1,1}; ``` to use on strtol function like ``` char c = (char) strtol(sign, NULL, 2); printf("%c\n", c); ``` I have no idea how to cast sign to use in strol. When I'm using ``` c = (char) strtol("01010111", NULL, 2); ``` everything is ok and I want to get such result. Please help :)
The problem is thatsignis not a string, it's an array of small integers. You can interpret them directly as bits and convert the array into a number, there's no point in going viastrtol()(and, in fact, it's rather un-idiomatic in C to do it your way). Just loop: ``` unsigned int array_to_int(const int *bits, size_t num_bits) { unsigned int ret = 0, value = 1; for(; num_bits > 0; --num_bits, value *= 2) ret += value * bits[num_bits - 1]; return ret; } ```
Im using semaphore.h, what is happening if 5 child processes waiting onsem_waitwhile another child process unlocking the semaphoresem_post? Are they all going to be unlocked?
No, only one will be unblocked. RTFM. sem_wait sem_post If many processes are block, then one will be chosen to be unblocked, which one is up to OS. Scheduler will choose one.
I'm browsing a project on Github, and a line that I can't make sense of is present in one of the files. The line itself is, ``` if(!*p) while(*c++ != ']'); ``` ... So IthinkI understand that thewhilegets executedif(!*p), but the while doesn't have any corresponding loop, which sort of puzzles me. What does this statement mean? For context:the line in the file
The;simply ends the single line while statement, without doing anything. This code could alternately be written as the following: ``` if(!*p) while(*c++ != ']'){} ``` Basically, the while statements continues until the return value of*c++does not equal the]character, presumably with the intent of seeking forward past the next]character. On a side note, there is no bounds checking in this loop, so it could seek past the intended address space, which could be bad.
I have a function,void *Client(void *threaData){} Can you tell me some things aboutvoid *threadDataparameter. When you usevoid *parameter and why?
void *is a generic pointer which can point to any object type. The above function can take a pointer to any type and can return a pointer to any type. A generic pointer can be used if it is not sure about the data type of data inputted by the user. Example: The following function will print any data type provided the user input about the type of data ``` void funct(void *a, int z) { if(z==1) printf("%d",*(int*)a); // If user inputs 1, then it means the data is an integer and type casting is done accordingly. else if(z==2) printf("%c",*(char*)a); // Typecasting for character pointer. else if(z==3) printf("%f",*(float*)a); // Typecasting for float pointer } ```
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.Closed8 years ago.Improve this question I would like to know what the following expression means: ``` char *fptr = NULL, *field; ``` Thanks!
Declare acharpointerfptrand initialize it toNULLand declare anothercharpointerfield. TheNULLis((void *)0)just an invalid pointer value and you can use it to verify if the pointer is valid. AssigningNULLto a pointer helps you avoid dereferencing an uninitialized pointer, for examplemallocreturnsNULLon failure. That way if you check your pointer againstNULLafter a call tomalloc, you prevent undefined behavior.
How can I print an array without changing line? I have this array. I want to print its element in one single line, for example(a b c d). ``` char word[20][20]; for (j = 0; j < 10; j++) { puts(word[j]); } ```
putsplacees a\nafter writingchararray to standard output. Useprintf("%s", word[j])instead.
HEREis the geeksforgeeks solution. I am not able to understand the findCeil() part. Step 4. Find index of Ceil of random number generated in step #3 in the prefix array. Let the index be indexc. ``` // Utility function to find ceiling of r in arr[l..h] int findCeil(int arr[], int r, int l, int h) { int mid; while (l < h) { mid = l + ((h - l) >> 1); // Same as mid = (l+h)/2 (r > arr[mid]) ? (l = mid + 1) : (h = mid); } return (arr[l] >= r) ? l : -1; } ``` Can someone please explain what is being done.
It's performing abinary searchof the array to find the first element of the array with a value greater than r. The wiki article should explain the technique pretty well. edit:Here's an animation of an example search
Let's say that the 'randomness' of an array is equal to the number of swap one needs to do in order to have the array as completely sorted. I want to write a program that would take in a sorted input array and as output would return an array with maximum 'randomness'. Please help.
Depends on how you define "swap". For example, if your array was[1,2,3,4,5]and swaps must be between adjacent numbers, then the array with maximum "randomness" would be the reverse[5,4,3,2,1]. However, if swaps can be between any two numbers, then the array with maximum "randomness" would be any array that takes(array length)-1swaps to sort, such as[5,1,4,2,3]
Is in C language lambda function or I have to write it by my own. I was searching on internet and haven't find anything only C++ and C#.
In the theoretical sense is not a lambda language because you don't have a true lambda type which is able to be passed around and behaves itself like a real value. But with function pointers you can obtain pretty similar results: ``` typedef int (*lambda)(); // defines lambda as a type which is a pointer to a function that returns an int int foo() { return 5; } int bar() { return 10; } lambda function; function = foo; function = bar; int result = function(); ```
I want to open a file abc.txt present in "../ab cd/Output" folder. What I have done so far is: ``` char temp1[100], temp2[10] = "abc.txt"; strcpy(temp1, "../ab\ cd/Output/"); FILE *fp_minenergy = fopen(strcat(temp1, temp2), "r"); ``` On executing it gives segmentation fault.
The problem should be just the file path itself ``` fopen("../ab cd/Output/abc.txt", "r"); ``` Your actualpathis not valid "../ab\ cd/Output/abc.txt", you don't need to escape here anything.
I'm trying to compare two char values, to see if the 'value' of one is greater than the other. My two values are char letter and char str[i]. At first I wrote;'letter'<'str[i]', which didn't work, but when I wroteletter<str[i], it did work. I don't understand why we need to remove the quotation marks because aren't we comparing the VALUE of the character , and not the character itself...? any advice would be appreciated.
Single quotes ('') are used to enclose characters.lettersandstr[i]are ofchartypes which holds character, not a character by themselves. So'letter'<'str[i]'is wrong. You just needletter < str[i].
i don't understand why second structure has 2 labels person and person_create. how is the second structure return a pointer . ``` struct Person{ char *name; int age; int height; int weight; }; struct Person *Person_create(char *name,int age,int height,int weight){ struct Person *who = malloc(sizeof(struct Person)); assert(who != null); who->name = strdup(name); who->age = age; who->height = height; who->weight = weight; return who; }; ```
``` struct Person *Person_create(char *name,int age,int height,int weight) ``` Read this line ``` Person_create ``` is a function name and this function returns a pointer to a structure which is ``` struct Person * ```
Can somebody explain to me how this recursion works? I'm getting stuck on how the result is 20 when the recursion leaves only on ifa == band it'sa = 6andb = 6 ``` int main() { printf("%d \n",mistero(2, 6)); return 0; } mistero( a, b) { if( a == b ){ return a; } return a + mistero(a+1, b); } ```
``` mistero(2, 6) = 2 + mistero(3, 6) = 2 + 3 + mistero(4, 6) = 2 + 3 + 4 + mistero(5, 6) = 2 + 3 + 4 + 5 + mistero(6, 6) = 2 + 3 + 4 + 5 + 6 = 20 ```
This program when run on CodeBlocks v13.12 with GCC v4.8.1 gives the output:2, 0. Can someone please explain why or how? ``` #include <stdio.h> int main ( ) { int function [ 2 ] [ 3 ] = { { 1, 2, 3 }, { 4 } }, i = 1, j = 1; function [ i + 1 ] [ j ] = function [ j ] [ i + 1 ]; // Assignment Statement printf ( "%d, %d", function [ i ] [ j ], function [ j ] [ i + 1 ] ); return 0; } ``` I've also noticed that in theAssignment Statement, the LHS of the expression is always assigned to the variablei. So, for example, if the statement was changed as: ``` function [ i + 1 ] [ j ] = 100; // Assignment Statement ``` The value ofiwould be100.
``` function [ i + 1 ] [ j ] ``` Accessing array out of bound will lead to undefined behavior. function [ 2 ]is array out of bound access.
i don't understand why second structure has 2 labels person and person_create. how is the second structure return a pointer . ``` struct Person{ char *name; int age; int height; int weight; }; struct Person *Person_create(char *name,int age,int height,int weight){ struct Person *who = malloc(sizeof(struct Person)); assert(who != null); who->name = strdup(name); who->age = age; who->height = height; who->weight = weight; return who; }; ```
``` struct Person *Person_create(char *name,int age,int height,int weight) ``` Read this line ``` Person_create ``` is a function name and this function returns a pointer to a structure which is ``` struct Person * ```
Can somebody explain to me how this recursion works? I'm getting stuck on how the result is 20 when the recursion leaves only on ifa == band it'sa = 6andb = 6 ``` int main() { printf("%d \n",mistero(2, 6)); return 0; } mistero( a, b) { if( a == b ){ return a; } return a + mistero(a+1, b); } ```
``` mistero(2, 6) = 2 + mistero(3, 6) = 2 + 3 + mistero(4, 6) = 2 + 3 + 4 + mistero(5, 6) = 2 + 3 + 4 + 5 + mistero(6, 6) = 2 + 3 + 4 + 5 + 6 = 20 ```
This program when run on CodeBlocks v13.12 with GCC v4.8.1 gives the output:2, 0. Can someone please explain why or how? ``` #include <stdio.h> int main ( ) { int function [ 2 ] [ 3 ] = { { 1, 2, 3 }, { 4 } }, i = 1, j = 1; function [ i + 1 ] [ j ] = function [ j ] [ i + 1 ]; // Assignment Statement printf ( "%d, %d", function [ i ] [ j ], function [ j ] [ i + 1 ] ); return 0; } ``` I've also noticed that in theAssignment Statement, the LHS of the expression is always assigned to the variablei. So, for example, if the statement was changed as: ``` function [ i + 1 ] [ j ] = 100; // Assignment Statement ``` The value ofiwould be100.
``` function [ i + 1 ] [ j ] ``` Accessing array out of bound will lead to undefined behavior. function [ 2 ]is array out of bound access.
I have a Webhook sayhttp://example.com/revoke/script. Whenever a user HTTP POST's to this URL, I want to start a bash scrip with root privileges. I had looked at calling system commands inphpandpython, but I have found out that invoking a script which requires root privileges , is very difficult.Can you suggest me some best practices to achieve this?
I usedincronfor this purpose. By using incron you can select a directory to be watched and whenever this directory got updated, incron can take certain actions such as invoking a script.