question
stringlengths
25
894
answer
stringlengths
4
863
I have three ints. Fx:20121121 I want to convert them into a single int20121121 Can this be done? I have tried messing around withatoi()without results.
Well, to answer directly the question that you asked, you would do it like this: ``` int combined = year*10000 + month*100 + day; ``` But your approach is quite possibly not the best solution to your actual problem.
I am having a two static librarya.libandb.lib(of C language) which is generated using VC6 (Visual studio 6.0) . I want to merge these two libs into one static libc.lib. How to do this in CLI mode? I have seen themerging of *nix static libs. I want to do the samething with VC6 static libs in CLI mode.
LIB.EXE /OUT:c.lib a.lib b.lib LIB.EXE is available in < VC6_InstalledFolder >/VC98/BIN. And this LIB.EXE is available in all versions of visual studio.
I am porting some C# code (classes mostly) to C. I have analysed the code and the port is definitely possible. One thing I am not sure of though, is how to handle (i.e. implement) raising events in C. I am in a Linux environment, and I expect the binary to run on Linux only. I heard that GLib supports events, but don...
The closes thing to C# events implemented by GLib are theGObject signals. Useg_signal_connectto connect your callback to an existing signal, andg_signal_emitto emit a registered signal. Seethe documentationfor details. As you are coming from a C# background, you might also consider usingVala, a programming language ...
Where can I find an serial C/C++ implementation of the k-nearest neighbour algorithm?Do you know of any library that has this?I have found openCV but the implementation is already parallel.I want to start from a serial implementation and parallelize it with pthreads openMP and MPI. Thanks,Alex
How about ANN?http://www.cs.umd.edu/~mount/ANN/. I have once used the kdtree implementation, but there are other options. Quoting from the website: "ANN is a library written in C++, which supports data structures and algorithms for both exact and approximate nearest neighbor searching in arbitrarily high dimensions."...
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen...
In Python: ``` i += 1 i += 1 i = 1 if j == 2 else 0 ```
I need to parse a HTTP request in C. I've been previously using std::regex for C++ but now I have to use C. What would be the best method to parse a HTTP request with C?
Apache recommends cgic, you can find it athttp://www.boutell.com/cgic/and its very simple to use
I'm designing an editor in GTK+ and wanted to add a feature of the gedit text editor to represent the line number at the left side of the text. I've added animage of gedit showing the line number at the left of each line. I require guidance of which widget I should use and how to use it. Thanks in advance :).. !
To get line numbering, useGtkSourceViewinstead ofGtkTextView.
I apologize if this is trivial, but I've been unable to find an answer by google. As per the OpenCL standard (since 1.0), the half type is supported for storage reasons. It seems to me however, that without the cl_khr_fp16 extension, it's impossible to use this for anything? What I would like to do is to save my va...
Usevload_halfNandstore_halfN. The halfN values stored will be converted to/from floatN.
This question already has answers here:Closed10 years ago. Possible Duplicate:Efficient bitwise operations for counting bits or find the right|left most ones Is there a fast way to find the first 1 in a (32 bit) binary number? e.g. if I have the number 00000000 00000000 00000000 10000000 I want to calculate the va...
With gcc, you can use__builtin_ctzand__builtin_clz.ctzgives the number of trailing 0 bits, andclzgives the number of leading 0-bits.
This question already has answers here:Closed10 years ago. Possible Duplicate:What is the difference between char a[] = “string”; and char *p = “string”; ``` int main() { char *p="ayqm"; char c; c=++*p; printf("%c",c); return 0; } ``` Its output isa. Seehttp://codepad.org/cbNOPuWtBut I feel that the output sho...
Sure, it'sundefined behavior. Anything can happen. You're attempting to modify a string literal, which is illegal. If you do, for example ``` char c = *p; ++c; ``` you'll see the correct output. The actual type ofpshould beconst char*, in which case you'd get a compiler error.
Thanks for reading, I'm in the midst of a homework assignment in which I need to, among other things, determine the MAC and IP addresses of a remote machine based on the captured packets I have. Using the pcap_loop function, I need to find the location of the proper struct (an ARP header which gives this information...
This article "http://en.wikipedia.org/wiki/Address_Resolution_Protocol" tells the layout of an ARP message. You don't need a structure, just use offsets.
I am writing a header-only library, and I can’t make up my mind between declaring the functions I provide to the userstaticorinline. Is there any reason why I should prefer one to the other in that case?
They both provide different functionalities. There are two implications of using theinlinekeyword(§ 7.1.3/4): Ithintsthe compiler that substitution of function body at the point of call is preferable over the usual function call mechanism.Even if the inline substitution is omitted, the other rules(especially w.r.tOn...
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...
Basically, you can write a PHP extension to do this. Follow the tutorial here:http://devzone.zend.com/303/extension-writing-part-i-introduction-to-php-and-zend/ There's also a SO topic:How to make a PHP extension
I have a project that has three files. The main file is called login.c. I want to #include my other two files using make, but I'm having trouble doing so. Thanks in advance for any advice!! here is my makefile: ``` objects = login.o cipher.o linked.o coptions = -Wall -g -ggdb loginTest: ${objects} gcc ${coption...
make can not automatically create *.h. You need to create it and #include that *.h file by yourself.
I'm trying to make a global variable, initialized in my msh.c file as: ``` volatile sig_atomic_t sig_int = 0; ``` This alone seems to be fine. However if I go to my proto.h file(which is included in all the c files for this project), and type: ``` extern volatile sig_atomic_t sig_int; ``` It throws a bunch of erro...
Yourproto.hfile needs to include<signal.h>so that thesig_atomic_ttype is defined, that's all.
I have an IP address in unsigned long format, coding in C++ I have a CIDR notation IP address range such as "10.2.3.98/24" How do i check if my IP address overlaps with the mentioned range?
To be as simple as possible, the part after the slash are the bits to keep, basically. So for example /24 means the most significant 3 bytes (24 bits) are preserved. Hence you can see if an address fits by masking it and checking for equality. The adress AND mask itself would be the min; If you are looking for max you...
I run the following C codes and got a warning: control reaches end of non-void function ``` int main(void) {} ``` Any suggestions?
Just putreturn 0in yourmain(). Your function main returns an int (int main(void)) therefore you should add a return in the end of it. Control reaches the end of a non-void function ``` Problem: I received the following warning: ``` warning: control reaches end of non-void function Solution: This warning is similar...
I am trying to reallocate memory to my table using the below expression.But I always keep getting the below error.Please kindly advise me. ``` typedef char *OFAttribs[6]; OFAttribs *tmp = realloc(pTable, sizeof(*tmp) * (nTableLen+1)); Error: invalid conversion from âvoid*â to âchar* (*)[6]â ```
Try this: ``` OFAttribs *tmp = (OFAttribs*) realloc(pTable, sizeof(*tmp) * (nTableLen+1)); ```
Im trying to figure out what the function declarations mean: ``` int *f(); ``` and ``` int (*g)(); ```
``` int *f(); ``` The above line is the declaration of a functionfthat has an unspecified number of parameters and that returns anint *. ``` int (*g)(); ``` The above line is the declaration of a pointergto a function that has an unspecified number of parameters and that returns anint.
I'm developing a note-taking utility and want to add a feature for voice-recording and playback in full duplex asynchronous mode.What cross-platform c/c++ libraries/API's can I evaluate for my purpose? Google isn't much help in this case and the existing QA's on SO doesn't quite cover this.
PortAudiocan accomplish what you want. It has lots of backends for different technologies like ALSA, ASIO, DirectSound etc.
This question already has answers here:Closed10 years ago. Possible Duplicate:What is the difference between char a[] = “string”; and char *p = “string”; ``` int main() { char *p="ayqm"; char c; c=++*p; printf("%c",c); return 0; } ``` Its output isa. Seehttp://codepad.org/cbNOPuWtBut I feel that the output sho...
Sure, it'sundefined behavior. Anything can happen. You're attempting to modify a string literal, which is illegal. If you do, for example ``` char c = *p; ++c; ``` you'll see the correct output. The actual type ofpshould beconst char*, in which case you'd get a compiler error.
Thanks for reading, I'm in the midst of a homework assignment in which I need to, among other things, determine the MAC and IP addresses of a remote machine based on the captured packets I have. Using the pcap_loop function, I need to find the location of the proper struct (an ARP header which gives this information...
This article "http://en.wikipedia.org/wiki/Address_Resolution_Protocol" tells the layout of an ARP message. You don't need a structure, just use offsets.
I am writing a header-only library, and I can’t make up my mind between declaring the functions I provide to the userstaticorinline. Is there any reason why I should prefer one to the other in that case?
They both provide different functionalities. There are two implications of using theinlinekeyword(§ 7.1.3/4): Ithintsthe compiler that substitution of function body at the point of call is preferable over the usual function call mechanism.Even if the inline substitution is omitted, the other rules(especially w.r.tOn...
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...
Basically, you can write a PHP extension to do this. Follow the tutorial here:http://devzone.zend.com/303/extension-writing-part-i-introduction-to-php-and-zend/ There's also a SO topic:How to make a PHP extension
I have a project that has three files. The main file is called login.c. I want to #include my other two files using make, but I'm having trouble doing so. Thanks in advance for any advice!! here is my makefile: ``` objects = login.o cipher.o linked.o coptions = -Wall -g -ggdb loginTest: ${objects} gcc ${coption...
make can not automatically create *.h. You need to create it and #include that *.h file by yourself.
I'm trying to make a global variable, initialized in my msh.c file as: ``` volatile sig_atomic_t sig_int = 0; ``` This alone seems to be fine. However if I go to my proto.h file(which is included in all the c files for this project), and type: ``` extern volatile sig_atomic_t sig_int; ``` It throws a bunch of erro...
Yourproto.hfile needs to include<signal.h>so that thesig_atomic_ttype is defined, that's all.
I have an IP address in unsigned long format, coding in C++ I have a CIDR notation IP address range such as "10.2.3.98/24" How do i check if my IP address overlaps with the mentioned range?
To be as simple as possible, the part after the slash are the bits to keep, basically. So for example /24 means the most significant 3 bytes (24 bits) are preserved. Hence you can see if an address fits by masking it and checking for equality. The adress AND mask itself would be the min; If you are looking for max you...
I run the following C codes and got a warning: control reaches end of non-void function ``` int main(void) {} ``` Any suggestions?
Just putreturn 0in yourmain(). Your function main returns an int (int main(void)) therefore you should add a return in the end of it. Control reaches the end of a non-void function ``` Problem: I received the following warning: ``` warning: control reaches end of non-void function Solution: This warning is similar...
I am trying to reallocate memory to my table using the below expression.But I always keep getting the below error.Please kindly advise me. ``` typedef char *OFAttribs[6]; OFAttribs *tmp = realloc(pTable, sizeof(*tmp) * (nTableLen+1)); Error: invalid conversion from âvoid*â to âchar* (*)[6]â ```
Try this: ``` OFAttribs *tmp = (OFAttribs*) realloc(pTable, sizeof(*tmp) * (nTableLen+1)); ```
Im trying to figure out what the function declarations mean: ``` int *f(); ``` and ``` int (*g)(); ```
``` int *f(); ``` The above line is the declaration of a functionfthat has an unspecified number of parameters and that returns anint *. ``` int (*g)(); ``` The above line is the declaration of a pointergto a function that has an unspecified number of parameters and that returns anint.
I am using Eclipse (C programming) and I have come up with this code but every time I build it, I get the error saying, "Undefined Reference to 'WinMain@16'". I have spent over 2 hours trying to solve this problem but I can't figure out my where my error is. Can anyone help? This is the code: ``` #include <stdio.h> ...
When you compile or build, files are not automatically saved to disk by Eclipse. But the compiler is using the on-disk files. So maybe you just didn't save the file after you've added the main function.
I'm doing some bitshifting work in C, and I'm reading in unsigned char's. Does every function I use with those variables need to take in an unsigned char as input, or because I loaded the value as unsigned will it automatically keep the first bit positive? Essentially do I need to do: ``` int Test1(unsigned char in...
int Test2(char input2)might not work.As largestunsigned charis greater than largestsigned char(largest positive integer in the range). But! Since bothunsigned charandsigned charare of same size, whether you read it assigned charorunsigned charwhat is stored in the memory is the same. Only the interpretation is diffe...
I would like to add pointers to a hash table using hsearch_r. At the moment it does not work using the following code segment (without variable declarations and checks): ``` // Allocate hash table htab = calloc( INITIAL_HASH_SIZE, sizeof(struct hsearch_data) ); hcreate_r( INITIAL_HASH_SIZE, htab ); // Add first poin...
The problem is that the keys in hsearch/hsearch_r are NUL-terminated strings, not arbitrary data.
Is function__ieee754_pow()can be optimized by using-Ooptions orffast-math.Is call forpowwill be change to call forcbrt, if we use nex code: ``` double test (double x) { return __ieee754_pow(x, 2./3.); } ``` And if the answer is NO, please explain why.
The compiler has no way of knowing the semantics of__ieee754_pow, i.e. no way of knowing that what it's doing it the "pow" operation. This is because the name__ieee754_powis not specified anywhere; it's an internal implementation detail of your system's math library. In any case, you should not be using it at all, and...
I am writing some C code using the LLVM C api. I need to check if an instruction value is of typeintor is a pointer. What I have tried to do is useLLVMTypeOf(LLVMValueRef val)and just see if it equals ALL of the different types ofint:LLVMInt1Type(),LLVMInt8Type(),LLVMInt16Type(), etc. I did not know how to figure o...
In c you can use LLVMGetTypeKind and LLVMTypeOf to determine what type it is. For integer type, you can check with: ``` if(LLVMGetTypeKind(LLVMTypeOf(LLVMValueRef val))==LLVMIntegerTypeKind) ``` For pointer type, you can check with: ``` if(LLVMGetTypeKind(LLVMTypeOf(LLVMValueRef val))==LLVMPointerTypeKind) ``` En...
I'm using this function to remove newline characters from a string: ``` void remove_newline(char *string) { string[strcspn(string, "\r")] = "\0"; string[strcspn(string, "\n")] = "\0"; } ``` The interesting thing is that I'm getting a warning when I try to compile this: warning: assignment makes integer from...
"\0"is astring literaland defines a character array of{'\0', '\0'}. It decays to a pointer if used without index. This pointer in turn then you are trying to assign tostring[...]which is an 8 bit integer, achar, hence the warning assignment makes integer from pointer without a cast To code a single character, achara...
I'm defining a char pointer in this manner. ``` char *s=(char *)malloc(10); ``` After I fill in all possible values that can fit here, I want to clear whatever I wrote to s and without using malloc again want to write in s? How can I do this? I need to update the contents but if in the last iteration not all value...
Be careful! malloc(sizeof(2*5))is the same asmalloc(sizeof(int))and allocates just 4 bytes on a 32 bit system. If you want to allocate 10 bytes usemalloc(2 * 5). You can clear the memory allocated bymalloc()withmemset(s, 0, 10)ormemset(s, 0, sizeof(int)), just in case this was really what you intended. Seeman mem...
This question already has answers here:Closed10 years ago. Possible Duplicate:Change bit of hex number with leading zeros in C++,(C) I have this number in hex string: ``` 002A05(7th bit is set to 0) ``` I need to invert 7-th bit of this number, so after conversion I will get ``` 022A05 ``` But in case ``` ABCDE...
Simplest way, but not necessarily the cleanest; Since only one char is affected, you can just do it using a simple string manipulation; assuming your input is in uppercase in the stringinput; ``` input[1] = "23016745AB*******89EFCD"[input[1]-48]; ```
I have tried this expression for identify a phone number: ``` ^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$ ``` but this validation is not working with C on Linux.
Check whether this works or not. I assume that you are using Extended Regular Expression (REG_EXTENDEDflag): ``` "^(?\\([0-9]{3}\\))?[-. ]?\\([0-9]{3}\\)[-. ]?\\([0-9]{4}\\)$" ``` ERE is a bit different in the fact that it treats(,)as literal(,)and\(,\)as grouping. References: http://www.kernel.org/doc/man-pages/o...
I'm trying to use theEigenC++ template library for linear algebra, I compiled and installed the library to the following path/usr/local/include I took a sample code from their site and I tried to compile with and without the-loption. ``` g++ -l /usr/local/include/eigen3 test.cpp -o mytest ``` but I'm getting the fo...
You want to use the-Ioption, not-l ``` g++ -I /usr/local/include/eigen3 test.cpp -o mytest ```
This question already has answers here:Removing trailing newline character from fgets() input(15 answers)Closed5 years ago. ``` fgets(input,sizeof(input),stdin); if (strcmp(input, "quit") == 0){ exit(-1); } ``` If I type quit, it does not exit the program; I'm wondering why this is the case. By the wayinputis dec...
The functionfgetsmight add a newline at the end of the string read. You'll have to check that: ``` size_t ln = strlen(input) - 1; if (input[ln] == '\n') input[ln] = '\0'; ``` or even ``` strtok(input, "\n"); ```
How can I get char array or char pointer from part of byte array? Let´s say I have variable-size string in byte array which begins at 18 bytes and ends 4 bytes from end of array. How can I get this? Edit: And what about dot? I should have dots in that byte array but when I copied by memcpy I get string without dots. ...
To extract a part of an array, you can usememcpy. ``` #include <string.h> char dst[4]; /* Here, we can assume `src+18` and `dst` don't overlap. */ memcpy(dst, src + 18, 4); ``` C11 (n1570), § 7.24.2.1 ThememcpyfunctionThememcpyfunction copies n characters from the object pointed to bys2into the object pointed to...
I'm looping through each line of a TCP socket input usingfdopenandfgetslike this: ``` int connfd = accept(listenfd, (struct sockaddr*)NULL, NULL); FILE *f; char line[1024]; f = fdopen(connfd, "a+"); while(fgets(line, sizeof(line), f) != NULL) { printf("%s", line); } printf("EOF"); fclose(f); ``` The problem is...
You'll only receive and end of file on a socket if the socket gets closed. If you need to stop reading while keeping the socket open, you need to define a protocol for that.
In thePGP 6.5.8 source codeI see a function defined like this: ``` static void sUnlockMemory( void * mem, PGPSize numBytes. PGPBoolean nonPageable ) { /* we always call VirtualLock() so always call VirtualUnlock() */ (void)wasLocked; VirtualUnlock ( mem, numBytes ); } ``` Note the period in the end of line 4. Wha...
In C, the only time you can have periods in a function prototype is when the function accepts a variable number of arguments, and that is always specified with three dots as the last parameter declaration. Any other use of a dot between the parentheses is a syntax error. E.g.: void fn(int arg1, ...);
i have a FAT16 image and i would like to copy the data stored at a specific memory location in this image in C. If opening the myfat16.img file with hexedit gives ``` 0000A320 44 54 FC 0C 19 85 13 E9 F6 D5 20 7F 56 24 EB A7 DC 2F 54 7A 20 10 9F 80 54 45 BB AE E9 C2 6E 08 08 4F 01 11 16 EF 1B A7 1E 00 00 ...
Using the C standard library open withfopenand go straight to the address of your interest usingfseek, and thenfreador whatever reading function is most convenient to you. If you instead have to use the POSIX syscalls directly you can use respectivelyopen,lseekandread.
I saw this line of code: ``` fputc("01234"[(int)tmp_seq[j][i]], opt->fp_bfast); ``` until now I thoughtfputcget a character and put it into the output stream. what does this line of code does
The code is indexing the string"01234"to choose a character by treating the string as a character array. The index is(int)tmp_seq[j][i]. Presumably(int)tmp_seq[j][i]holds a value between0and4inclusive, otherwise there will be an array indexing out-of-bounds error.
How to make sure, that my code is compatible with every gcc compiler set to the most strict level? Is there any tester tool or do I need to test it manually somehow? Thanks
Every gcc compiler is easy, just use an old one and it will compile for sure with the newer ones. If you want it to compile with any compiler it's a bit more hard. As suggested you might use the -ansi switch to disable gcc extensions.
I have achar nom[100];but when anom's size is less than 100 I have to use padding. I use the char '.' to proceed. But when I read data I see for examplea.txt.............................................................................................. How can I do to remove the padded '.' in C ?
You can either initialize your char *nom, like this: ``` char nom[100] = {'\0'}; ``` Or insert a '\0' after the length you want the string "nom" to have, like this: ``` nom[5] = '\0' ```
How can I open a.txtfile usingexecl()function? Is there any other function in c to open a file ingeditin Ubuntu. Regards
Is there any other function in c to open a file in gedit Th easiest would be ``` system("gedit file.txt"); ``` As a side-note you might want to look intoxdg-open.
I'm trying to use theEigenC++ template library for linear algebra, I compiled and installed the library to the following path/usr/local/include I took a sample code from their site and I tried to compile with and without the-loption. ``` g++ -l /usr/local/include/eigen3 test.cpp -o mytest ``` but I'm getting the fo...
You want to use the-Ioption, not-l ``` g++ -I /usr/local/include/eigen3 test.cpp -o mytest ```
This question already has answers here:Removing trailing newline character from fgets() input(15 answers)Closed5 years ago. ``` fgets(input,sizeof(input),stdin); if (strcmp(input, "quit") == 0){ exit(-1); } ``` If I type quit, it does not exit the program; I'm wondering why this is the case. By the wayinputis dec...
The functionfgetsmight add a newline at the end of the string read. You'll have to check that: ``` size_t ln = strlen(input) - 1; if (input[ln] == '\n') input[ln] = '\0'; ``` or even ``` strtok(input, "\n"); ```
How can I get char array or char pointer from part of byte array? Let´s say I have variable-size string in byte array which begins at 18 bytes and ends 4 bytes from end of array. How can I get this? Edit: And what about dot? I should have dots in that byte array but when I copied by memcpy I get string without dots. ...
To extract a part of an array, you can usememcpy. ``` #include <string.h> char dst[4]; /* Here, we can assume `src+18` and `dst` don't overlap. */ memcpy(dst, src + 18, 4); ``` C11 (n1570), § 7.24.2.1 ThememcpyfunctionThememcpyfunction copies n characters from the object pointed to bys2into the object pointed to...
I'm looping through each line of a TCP socket input usingfdopenandfgetslike this: ``` int connfd = accept(listenfd, (struct sockaddr*)NULL, NULL); FILE *f; char line[1024]; f = fdopen(connfd, "a+"); while(fgets(line, sizeof(line), f) != NULL) { printf("%s", line); } printf("EOF"); fclose(f); ``` The problem is...
You'll only receive and end of file on a socket if the socket gets closed. If you need to stop reading while keeping the socket open, you need to define a protocol for that.
In thePGP 6.5.8 source codeI see a function defined like this: ``` static void sUnlockMemory( void * mem, PGPSize numBytes. PGPBoolean nonPageable ) { /* we always call VirtualLock() so always call VirtualUnlock() */ (void)wasLocked; VirtualUnlock ( mem, numBytes ); } ``` Note the period in the end of line 4. Wha...
In C, the only time you can have periods in a function prototype is when the function accepts a variable number of arguments, and that is always specified with three dots as the last parameter declaration. Any other use of a dot between the parentheses is a syntax error. E.g.: void fn(int arg1, ...);
i have a FAT16 image and i would like to copy the data stored at a specific memory location in this image in C. If opening the myfat16.img file with hexedit gives ``` 0000A320 44 54 FC 0C 19 85 13 E9 F6 D5 20 7F 56 24 EB A7 DC 2F 54 7A 20 10 9F 80 54 45 BB AE E9 C2 6E 08 08 4F 01 11 16 EF 1B A7 1E 00 00 ...
Using the C standard library open withfopenand go straight to the address of your interest usingfseek, and thenfreador whatever reading function is most convenient to you. If you instead have to use the POSIX syscalls directly you can use respectivelyopen,lseekandread.
I saw this line of code: ``` fputc("01234"[(int)tmp_seq[j][i]], opt->fp_bfast); ``` until now I thoughtfputcget a character and put it into the output stream. what does this line of code does
The code is indexing the string"01234"to choose a character by treating the string as a character array. The index is(int)tmp_seq[j][i]. Presumably(int)tmp_seq[j][i]holds a value between0and4inclusive, otherwise there will be an array indexing out-of-bounds error.
How to make sure, that my code is compatible with every gcc compiler set to the most strict level? Is there any tester tool or do I need to test it manually somehow? Thanks
Every gcc compiler is easy, just use an old one and it will compile for sure with the newer ones. If you want it to compile with any compiler it's a bit more hard. As suggested you might use the -ansi switch to disable gcc extensions.
I have achar nom[100];but when anom's size is less than 100 I have to use padding. I use the char '.' to proceed. But when I read data I see for examplea.txt.............................................................................................. How can I do to remove the padded '.' in C ?
You can either initialize your char *nom, like this: ``` char nom[100] = {'\0'}; ``` Or insert a '\0' after the length you want the string "nom" to have, like this: ``` nom[5] = '\0' ```
How can I open a.txtfile usingexecl()function? Is there any other function in c to open a file ingeditin Ubuntu. Regards
Is there any other function in c to open a file in gedit Th easiest would be ``` system("gedit file.txt"); ``` As a side-note you might want to look intoxdg-open.
If I chdir within a thread, will that affect the cwd of the parent program?
Yes. If you need relative paths in a multithreaded application, it's safest to use theat()versions of functions. For example,openat()is likeopen(): ``` int openat(int dirfd, const char *pathname, int flags); ``` The first parameter is the fd to a directory. The path is relative to that directory.
I want to handle SIGUSR1 signal so I do everything what it needs and it´s working. But in my program I am waiting at recvfrom and when I handle signal and return then to recvfrom I got -1 from this function. Is it possible to return back to waiting at this function?
Your system call is beinginterruptedby the signal. Unless you are consistently setting up signal handlers usingsigactionwith theSA_RESTARTflag, it is a good idea to retry system calls using a loop such as: ``` while ((size = recvfrom(...)) == -1 && errno == EINTR) ; ```
I have no idea what to call it, so I have no idea how to search for it. unsigned int odd : 1; Edit: To elaborate, it comes from this snippet: ``` struct bitField { unsigned int odd : 1; unsigned int padding: 15; // to round out to 16 bits }; ``` I gather this involves bits, but I'm still not all the way u...
They are bitfields.oddandpaddingwill be stored in oneunsigned int(16 bit) whereoddwill occupy the lowest bit, andpaddingthe upper 15 bit of theunsigned int.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. trying to figure out the advantage ...
There are no advantages except simplicity of implementation -- but only for single-threaded code.errnodates from before exceptions existed in any popular language. EDIT: Nowadayserrnoactually evaluates to a macro that extracts a per-thread error state, so it's safe to use in multithreaded code (thanks Jesus Ramos and...
I am working on a Linux character device driver for a school assignment and am not sure how to print the*ppospassed into my read function which is of typeloff_t. I know I must useprintkrather than the standard libraryprintffrom within the kernel but I can't seem to figure out the proper format specifier.
loff_t is just a typedef. To determine which format specifier to use, you should look for its definition: typedef __kernel_loff_t loff_ttypedef long long __kernel_loff_t Then you can refer to theKernel's documentationto see how to format a "long long" (%lld).
I have a function that allocates string and returns its pointer. When I use it directly in call of other function, do I need to free the memory? For example: ``` char *getRow(){ char *someString = (char*) malloc(sizeof(char) * 10); strcpy(someString , "asdqwezxc"); return someString; } int main(){ ...
Even if you have returned from the function, the memory is not deallocated unless you explicitly do so. So you must store the return value and callfree. ``` int main(){ char* str = getRow(); printf("%s", str); free(str); } ```
``` int threads = 5; pthread_t * thread = malloc(sizeof(pthread_t)*threads); for (i = 0; i < threads; i++){ int ret = pthread_create(&thread[i], NULL, &foobar_function, NULL);} ``` I'm not in a position to run the code right now. But I saw this as part of an online example and was a litt...
Yes. threadis pointing at a block of memory allocated bymallocthat is large enough to holdthreadspthread_tobjects. An array ofthreadspthread_tobjects can be represented in exactly this way.
I know that the function fseek() can be used to output data to a specific location in a file. But I was wondering if I use fseek() to move to the middle of the file and then output data. Would the new data overwrite the old data? For example if I had a file containing 123456789 and I used fseek() to output newdata aft...
Writing data in the "middle" of a file will overwrite existing data. So you would have '12345newdata'. EDIT: As mentioned in the comments below, it should be noted that this overwrites data without truncating the rest of the file. As an extended version of your example, if you wrote newdata after the 5 in a file cont...
I'm reading a text file char by char using fscanf(); I've tried to pass my FILE pointer to a function, to keep reading there, but I'm getting stuck in a loop. ``` void keepReading(FILE *fp){ char c; fscanf(fp, "%c", &c); } /* main */ fscanf(fp, "%c", &c); while(c!='A'){ keepReading(fp); } ``` Any ide...
The variablecinkeepReading()is local to that function. Return the value to your loop and test that ``` char keepReading(FILE *fp){ char c; fscanf(fp, "%c", &c); return c; } /* main */ fscanf(fp, "%c", &c); while(c!='A'){ c = keepReading(fp); } ```
From my homework: Backup files are stored in a hidden directory called .mybackup, which your program creates, if necessary. To create a directory, use the mkdir() function (click here for details), but be sure to check whether the directory already exists (using stat() or checking for EEXIST). If the director...
mkdirreturns -1 for any error. So to distinguish between errors, that is, to discover if the directory already exists, you should either use thestatfunction or checkerrnoforEEXISTaftermkdirreturns -1. ``` if(mkdir(".mybackup", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1) { if(errno == EEXIST) { // Di...
Say I want to create a folder myFolder, and I want it to be hidden. I'm having trouble finding the answer to this for Unix.
Seeman 2 mkdirfor creating a folder in C. To make it hidden you must prefix the name with a dot. It's just a one-liner: ``` mkdir(".myFolder", 0755); ```
Say I want to create a folder myFolder, and I want it to be hidden. I'm having trouble finding the answer to this for Unix.
Seeman 2 mkdirfor creating a folder in C. To make it hidden you must prefix the name with a dot. It's just a one-liner: ``` mkdir(".myFolder", 0755); ```
Given a struct such as this: ``` struct a { int b; int c; my_t d[]; } ``` What do I have to pass tomallocto allocate enough memory for astruct awheredhasnelements?
``` struct a *var = malloc(sizeof(*var) + n*sizeof(var->d[0])) ``` Using the variables forsizeofwill ensure the size is updated if the types change. Otherwise, if you change the type ofdorvaryou risk introducing silent and potentially difficult-to-find runtime issues by not allocating enough memory if you forget to u...
I'm reading a txt file and getting all the chars that aren't space, transforming them to int using(int)c-'0'and that is working. The problem is if the number has more than 1 digit, because I'm reading char by char. How could I do to read like a sequence of chars, transform this sequence of chars into int? I tried u...
A convenient way to do the conversion is to read the whole number into a buffer (string) and then callatoi. Make triple sure that the string is properly null-terminated.
I just have a simple question, I cannot find what the key code is for space bar in curses.h. ex. I know the code for down is KEY_DOWN. can anyone help?
There is no macro for the space key. Just use ' ' to represent a space. You can find a complete list of curses key macroshere. Ex. ``` char mychar = ' '; if (mychar == ' ') {//Do this...} ```
I'm new to C but I have experience in Java and Android. I have a problem in my for loop. It will never end and just go on and on. ``` char entered_string[50]; char *p_string = NULL; gets( entered_string ); for( p_string = entered_string; p_string != '\0'; p_string++ ){ //.... } ``` I know that gets is unsafe, ...
Your test should be*p_string != '\0'; p_stringis a pointer, and your loop is checking if the pointer is!= '\0'. You're interested in if the value is!= '\0', and to get the value out of a pointer you have to dereference it with*.
Is there an ANSI-C compatible event loop, like libev or libevent? My requirement is to compile with -ansi flag. Thank you.
You cannot have any strictly ANSI compatible event loop on Linux, because the purpose of an event loop is to multiplex cleverly several inputs; on Linux to do that multiplexing, youhave tocall some syscalls likepoll(2),pselect(2)or friends, and all these syscalls are not standardized in ANSI C (or ISO C99, or ISO C201...
I'm a complete noob to C and I wondered why if I take a user input why it wont find the file but when I hard code it using: ``` const char * fn = "/Users/james/Documents/test.rtf"; ``` It seems to work fine? ``` char text[100]; fputs("File location: ", stdout); fflush(stdout); fgets(text, sizeof text, stdin); FIL...
fgetsreads a line and keeps the final newline character. You'll have to strip that off by ``` text[strlen(text) - 1] = '\0'; ``` (After doing the proper error checking, of course.)
In C, I want to create and open text files to write data into, but the problem is I want to name the files on the go, such as ``` FILE *ptr; for(i=0;i<1000;i++){ fopen_s(&ptr,"i.txt","w"); operations to fill data into file i.txt; fclose(ptr); } ``` such that I will create file 0.txt, 1.txt, 2.txt ... 999.t...
usesnprintfto set the file number: ``` FILE *ptr; char name[FILENAME_MAX]; for(i=0;i<1000;i++){ snprintf(name, sizeof(name), "%d.txt", i); fopen_s(&ptr, name, "w"); //operations to fill data into file i.txt; fclose(ptr); } ```
I've been trying to explore code folding options in Vim, and I have stumbled upon this stack-overflowquestion. While I have been able to put that into myvimrc, the problem I'm having is thatit doesn't fold the multi-line comments above a function. How do I solve this?
The defaultsyntax/c.vimprovides folding definitions. Unless you define ac_no_comment_foldvariable, this also folds multi-line comments. To activate this, just put ``` :setlocal foldmethod=syntax ``` into~/.vim/after/ftplugin/c.vim.
I am writing in C WinAPI a 'Go To Line' dialog of the notepad. I created a number only edit control. But I can still paste words into the edit control! The dialog in the windows notepad does stop this kind of pasting. So how can I do the same thing as it in the notepad?
Subclass the edit control, and when WM_PASTE is received: ``` OpenClipboard GetClipboardData GlobalLock ``` Now use the returned pointer from GlobalLock to check for non numeric characters. If a non number is found, inform user then: ``` GlobalUnlock CloseClipboard ``` and return 0 from the callback to prevent pa...
Let's say that I have a buffer of chars and I want to avoid using memcpy, and access to it through an int* variable: ``` char buffer[100]; strcpy(buffer,"Hello"); int* __restrict ptr=(int*)buffer; *ptr= 97; printf("%s",buffer); ``` Now this of course prints "a".Am I allowed to do this without encountering an undefin...
Now this of course prints "a". Well, only on little endian machines. And strict aliasing would have nothing do with your example as one of the type ischarandcharmay alias anything if the goal ofrestrictwasn't toincreasethe number of cases where the compiler may assume that there is no alias, i.e. even when typing in...
I am broadcasting a pointer to an array ``` MPI_Bcast(&xd_sim_send, Nooflines_Sim, MPI_FLOAT, root, MPI_COMM_WORLD); ``` from process 0 and receiving this broadcast from processes other than 0 ``` MPI_Bcast(&xd_sim_recv, Nooflines_Sim, MPI_FLOAT, root, MPI_COMM_WORLD); ``` I get segmentation fault 11 when I try to...
It doesn't make sence to send a pointer, since that pointer will be invalid in the other parallel process, send the buffer instead: ``` MPI_Bcast(xd_sim_send, Nooflines_Sim, MPI_FLOAT, root, MPI_COMM_WORLD); ```
I finished the programming of a class project, but I still need to get the running time. I tried clock() function, but it didn't work. ``` int main() { clock_t start_time=clock(); (my codes) clock_t end_time=clock(); printf("The running time is %f", end_time-start_time); } ``` I guess this is the right way t...
clock_tis not afloat, but an integer type, most probably along. So you might use%ldtoprintf()it. Alsoclock()does not return seconds, but CPU ticks. So to get seconds the value returned byclock()shall be devided by the system constantCLOCKS_PER_SEC.
Is there a way, to get the PIDs of the child processes? I mean, if i open a cmd prompt using CreateProcess, i know its PID because i can get it from the returned ProcessInformation structure. But is it possible to get the PIDs of the processes too, which were opened from this command prompt? Thanks!
you can use theCreateToolhelp32Snapshotfunction passing theTH32CS_SNAPPROCESSvalue, then call theProcess32Firstmethod , and finally you must iterate over the collection returned and compare the value of theth32ParentProcessIDfield against the PID of the cmd.exe. Another option is use theWin32_ProcessWMI Class using th...
What should I do if I want to use identifierNULLingdb's call statement? Is it because I didn't include stdio.h in gdb? I have tried :call #include <stdio.h>but this doesn't seem to work.
Just use0or(void*)0. Nothing fancy.
I have a number of living threads in my application for which I havepthread_tIDs and can get other IDs if necessary. Those are stored in a separate array. How can I determine the ID/number of the CPU that a specific thread is currently running (or one it was recently run on) calling from another thread. sched_getcpu...
At least on Lnux you could get thetidfor every thread by callinggettid(). Then look up the CPU id by reading the 39th element from/proc/<pid>/task/<tid>/stat. (wherepidis read viagetpid()) See also: How to get the CPU id via /proc file system?How to get the LW-process id for a thread?
I am trying to split my string and the (\n)new line and want to get the new string without \n.My code is as below.Thanks. ``` token = strtok(NULL,"") ``` The above snippet will store "some string and \n" where as I need just "some string". My data looks like this. ``` 1,v1,p1,182,1665,unkn ```
If you data looks like this ``` char line[] = "1,v1,p1,182,1665,unkn\n"; ``` you could do something like this (in C) ``` char* p = line + strlen(line) - 1; for (;*p != ','; --p) { ; } char* lastword = strtok(p + 1,"\n"); ```
I have a C program which gives some output. I am compiling the C program via the shell but I need the output from therunC program and store in shell. Edit. Save the output to a shell Variable.
I assume that you want to store the output of the program in a variable. Unix shells offer a facility that's calledcommand substitutionto do just that. Depending on your shell, you can do either : ``` output=$(./run) ``` or ``` output=`./run` ``` Bash supports both. If, however, you want to save the output to a fi...
Clang has the following test cases: ``` #if 0 #ifdef D #else 1 // Should not warn due to C99 6.10p4 #endif #endif #if 0 #else 1 // expected-warning {{extra tokens}} #endif ``` The first#else 1indeed is fine because it's in a skipped group, but as far as I can see the second one should be an error - it does...
The standard does not have notions of "error" and "warning", it only knows "diagnostic". It is up to implementation to define what constitutes a diagnostic. Most implementations of C, including clang and gcc, define diagnostics to include both errors and warnings.
I have long value of 12 digits as output from an arithmetic operation. So i want only the middle 4 value. for example i got 823954957346 and i only want 5495 to store in a variable. can i do this in C or C++ ?
You can use something like: ``` main() { unsigned long i = 823954957346; printf ("%lu\n", i); printf ("%lu\n", i / 10000 % 10000); } ``` Output: ``` 823954957346 5495 ```
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. Using C, how can I generate a rando...
As a decent starting point, you could userand(). To generate a random number between -2 and +2, you can do: ``` float f = 4 * ((rand() / (float)RAND_MAX) - 0.5f); ``` If you repeat this process, you can get anxand ay: ``` float x = 4 * ((rand() / (float)RAND_MAX) - 0.5f); float y = 4 * ((rand() / (float)RAND_MAX) -...
hi i have this function ``` int printofarray(int *j,double *n) { int x,k; k=*j; if(n==NULL) { printf("array was not created\n"); return 1;} for(x=0;x<k;x++){ printf("%.2lf\n",*(n+x));} return 0; } ``` when i use it the output is like this ``` 34.77 6114.05 410.70 ``` but i want to write them this way ``` 34.77 ...
Offhand, try %f instead of %lf for f1. Edit: %lf is for double.
This question already has answers here:Closed10 years ago. Possible Duplicate:Macro definition error in C? I'm new to programming and hope someone can help me with this: Why is it giving an output : 5 .Here is the code snippet: ``` #include <stdio.h> #define max 5; int main(){ int i=0; i = max+1; printf("\n%d",i)...
Because the macro has a semi-colon. Code is equivalent to: ``` i = 5; + 1; ``` Remove the semi-colon from the macro.
Let's say that I have a buffer of chars and I want to avoid using memcpy, and access to it through an int* variable: ``` char buffer[100]; strcpy(buffer,"Hello"); int* __restrict ptr=(int*)buffer; *ptr= 97; printf("%s",buffer); ``` Now this of course prints "a".Am I allowed to do this without encountering an undefin...
Now this of course prints "a". Well, only on little endian machines. And strict aliasing would have nothing do with your example as one of the type ischarandcharmay alias anything if the goal ofrestrictwasn't toincreasethe number of cases where the compiler may assume that there is no alias, i.e. even when typing in...
I am broadcasting a pointer to an array ``` MPI_Bcast(&xd_sim_send, Nooflines_Sim, MPI_FLOAT, root, MPI_COMM_WORLD); ``` from process 0 and receiving this broadcast from processes other than 0 ``` MPI_Bcast(&xd_sim_recv, Nooflines_Sim, MPI_FLOAT, root, MPI_COMM_WORLD); ``` I get segmentation fault 11 when I try to...
It doesn't make sence to send a pointer, since that pointer will be invalid in the other parallel process, send the buffer instead: ``` MPI_Bcast(xd_sim_send, Nooflines_Sim, MPI_FLOAT, root, MPI_COMM_WORLD); ```
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. I want to know if I can see how the...
C and C++ do not have garbage collection.
I have a server which needs to transfer a large amount of data (~1-2 gigs) per request. What is the recommended amount of data that each call to send should have? Does it matter?
The TCP/IP stack takes care of not sending packets larger than the PATH MTU, and you would have to work rather hard to make it send packetssmallerthan the MTU, in ways that wouldn't help throughput: and there is no way of dsicovering what the path PTU actually is for any given connection. So leave all consideration of...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. I want to know if I can see how the...
C and C++ do not have garbage collection.
I have a server which needs to transfer a large amount of data (~1-2 gigs) per request. What is the recommended amount of data that each call to send should have? Does it matter?
The TCP/IP stack takes care of not sending packets larger than the PATH MTU, and you would have to work rather hard to make it send packetssmallerthan the MTU, in ways that wouldn't help throughput: and there is no way of dsicovering what the path PTU actually is for any given connection. So leave all consideration of...
This may be a dumb question, and I'm shocked I had trouble Googling it, but here goes: What happens in this situation: ``` int foo(void){ char x = 1; if (x == 1} goto apple; } else{ goto banana; } apple: printf("apple"); banana: printf("banana"); return 0; }...
If x==1 will the output be ``` apple banana ``` Yes, it will. Labels (eithergotoorswitchlabels) fall through.