question
stringlengths
25
894
answer
stringlengths
4
863
I'm not sure what I'm doing wrong, but I'm not able to read a double from the console. Reading an it works fine for some reason. I'm using Xcode. ``` double n1; // get input from the user printf("Enter first number: "); scanf("%f", &n1); printf("%f", n1); ``` This will always print 0 no matter what I enter.
%fis looking for a float, not a double. If you want to use a double, use the format%lf. As a somewhat interesting aside, clang warns about this without any extra flags, gcc 4.6 won't warn about it even with-Wall -Wextra -pedantic.
I am writing a client/server program using C sockets. I am specifying that the server can listen on any network interface by using INADDR_ANY in sockaddr_in.sin_addr.s_addr. This is equivalent to an IP of 0.0.0.0. Is it possible for me to get the actual IP that the server is listening on? (e.g. 192.168.1.100)
When you bind a listening socket toINADDR_ANY, the socket listens on all available local IPs. There is no way to determine from the socket which IP(s) it is listening on. If you need that information, then you have to enumerate the local IPs separately (in which case you could justbind()each IP to its own socket ind...
If I want to create a 2D array, with dimensions specified by user input, can't I just do this sequentially in the main function? Once I have the dimensions by using scanf, I then create an array with those dimensions? From what I understood, malloc is supposed to be used when the space required is not known at runtime...
Generally there are three reaons to use dynamic allocation in C: The size is not known until runtime (another alternative isVLA's, but that's C99 and potentially dangerous, see reason 2).The size is (most likely) too big for the stack, risking stack overflow.The object needs to live on the heap giving it a longer lif...
I know thatcdis a shell built-in ,and I can run it by usingsystem(). But is that possible to run thecdcommand by theexec()family, likeexecvp()? Edit: And I just noticed thatsystem("cd")is also meaningless。Thanks for the help of everyone.
execloads anexecutable fileand replaces the current program image with it. As you rightly noted,cdisnotan executable file, but rather a shell builtin. So the executable that you want to run is the shell itself. This is of course whatsystem()does for you, but if you want to be explicit about it, you can useexec: ``` e...
For testing purposes, I need to share some definitions between Tcl and C. Is it possible to include C style include file in Tcl scripts? Any alternative suggestion will be welcomed, but I prefer not to write a parser for C header file.
SWIG supports Tcl so possibly you can make use of that. Also I remember seeing some code to parse C headers on the Tcl wiki - so you might try looking at theParsing Cpage there. That should save you writing one from scratch.
Suppose I declared an array as following: ``` int myArr = [someSize]; ``` Now I put n elements(where n is not known exactly but n < someSize)in it like this ``` myArray[0] = 12; myArray[1] = 23; and so on ..... ``` Now I want to know is there any way to find out exactly how many elements have been entered by the...
You can't get any such information from the array. If you need it, you'll want to record it. When I've needed this, I've usually used something like: ``` struct myArray_t { size_t next_element; int arr[somesize]; }; ``` When you create this, you setnext_elementto 0, and to add an element, you use something ...
I have declaredtypedef void (*DoRunTimeChecks)(); How do I store that as a field in a struct? How do I assign it? How do I call the fn()?
Just put it in like you would any other field: ``` struct example { int x; DoRunTimeChecks y; }; void Function(void) { } struct example anExample = { 12, Function }; ``` To assign to the field: ``` anExample.y = Function; ``` To call the function: ``` anExample.y(); ```
when I read ucos source files, I find this code in ucos_ii.c ``` #include "os_core.c" #include "os_mbox.c" #include "os_mem.c" #include "os_q.c" #include "os_sem.c" #include "os_task.c" #include "os_time.c" ``` what's the advandage of including .c files?
By doing this, they may be allowing the compiler to do more inlining and/or space optimization. uCos is an embedded operating system, so anything that saves space or time is a good thing. (Within reason, of course)
I have extracted a MAC address into achar*array such that each section of the array is a pair of char values. ``` mac[0] = "a1" mac[1] = "b2" ... mac[5] = "f6" ``` Basically I need to take the char arrays and convert them to an unsigned char such that the hex representation is the same as the original char values. ...
My C isn't the best, but this works using strtol(start, [stop], base) ``` #include <stdlib.h> #include <stdio.h> int main(char ** argv, int argc) { char * input = "a1"; printf("%d\n", (unsigned char)strtol(input, NULL, 16)); } ```
I want a debug function-macro that works like this: ``` int myVar = 5; PRINTVAR(myVar); // macro // which expands to something like... print("myVar: "); println(myVar); ``` Basically, I want to use the identifier as a string literal as well as a variable. I'm just getting a bit sick of repeating myself when I want...
The "stringizing operator" is designed for precisely this case: ``` #define PRINT_VAR(x) (print(#x ": "), println(x)) ```
In a makefile, there is a line: ``` CFLAGS += $(shell $(CC) -fno-stack-protector -E -x c /dev/null >/dev/null 2>&1 && echo -fno-stack-protector) ``` What's the use ofshell $(CC) -fno-stack-protector -E -x c /dev/null >/dev/null 2>&1? It seems to do nothing. And how the whole line works? Thanks in advance.
It tests whether-fno-stack-protectoris a valid command-line option for your C compiler, and if it is it then appends this option toCFLAGS, otherwise it does nothing.
programming my arduino microcontroller board in C, I noticed a strange behaviour. Because of an logic mistake in my program the controller accessed the-1th element of an integer array. ``` int array[5]; array[4] = 27; // array[-1] gives 27 now. ``` Is it correct that I get the last element of an array by using-1...
No, accessing elements outside of the index range is undefined behavior. In your case, the element at the address just prior to the beginning of your array is set to 27. Since accessing array elements in C is nothing more than doing "straight" pointer arithmetic, passing negative indexes is not disallowed. You could ...
I'm not sure what I'm doing wrong, but I'm not able to read a double from the console. Reading an it works fine for some reason. I'm using Xcode. ``` double n1; // get input from the user printf("Enter first number: "); scanf("%f", &n1); printf("%f", n1); ``` This will always print 0 no matter what I enter.
%fis looking for a float, not a double. If you want to use a double, use the format%lf. As a somewhat interesting aside, clang warns about this without any extra flags, gcc 4.6 won't warn about it even with-Wall -Wextra -pedantic.
I am writing a client/server program using C sockets. I am specifying that the server can listen on any network interface by using INADDR_ANY in sockaddr_in.sin_addr.s_addr. This is equivalent to an IP of 0.0.0.0. Is it possible for me to get the actual IP that the server is listening on? (e.g. 192.168.1.100)
When you bind a listening socket toINADDR_ANY, the socket listens on all available local IPs. There is no way to determine from the socket which IP(s) it is listening on. If you need that information, then you have to enumerate the local IPs separately (in which case you could justbind()each IP to its own socket ind...
If I want to create a 2D array, with dimensions specified by user input, can't I just do this sequentially in the main function? Once I have the dimensions by using scanf, I then create an array with those dimensions? From what I understood, malloc is supposed to be used when the space required is not known at runtime...
Generally there are three reaons to use dynamic allocation in C: The size is not known until runtime (another alternative isVLA's, but that's C99 and potentially dangerous, see reason 2).The size is (most likely) too big for the stack, risking stack overflow.The object needs to live on the heap giving it a longer lif...
I know thatcdis a shell built-in ,and I can run it by usingsystem(). But is that possible to run thecdcommand by theexec()family, likeexecvp()? Edit: And I just noticed thatsystem("cd")is also meaningless。Thanks for the help of everyone.
execloads anexecutable fileand replaces the current program image with it. As you rightly noted,cdisnotan executable file, but rather a shell builtin. So the executable that you want to run is the shell itself. This is of course whatsystem()does for you, but if you want to be explicit about it, you can useexec: ``` e...
For testing purposes, I need to share some definitions between Tcl and C. Is it possible to include C style include file in Tcl scripts? Any alternative suggestion will be welcomed, but I prefer not to write a parser for C header file.
SWIG supports Tcl so possibly you can make use of that. Also I remember seeing some code to parse C headers on the Tcl wiki - so you might try looking at theParsing Cpage there. That should save you writing one from scratch.
Suppose I declared an array as following: ``` int myArr = [someSize]; ``` Now I put n elements(where n is not known exactly but n < someSize)in it like this ``` myArray[0] = 12; myArray[1] = 23; and so on ..... ``` Now I want to know is there any way to find out exactly how many elements have been entered by the...
You can't get any such information from the array. If you need it, you'll want to record it. When I've needed this, I've usually used something like: ``` struct myArray_t { size_t next_element; int arr[somesize]; }; ``` When you create this, you setnext_elementto 0, and to add an element, you use something ...
I have declaredtypedef void (*DoRunTimeChecks)(); How do I store that as a field in a struct? How do I assign it? How do I call the fn()?
Just put it in like you would any other field: ``` struct example { int x; DoRunTimeChecks y; }; void Function(void) { } struct example anExample = { 12, Function }; ``` To assign to the field: ``` anExample.y = Function; ``` To call the function: ``` anExample.y(); ```
when I read ucos source files, I find this code in ucos_ii.c ``` #include "os_core.c" #include "os_mbox.c" #include "os_mem.c" #include "os_q.c" #include "os_sem.c" #include "os_task.c" #include "os_time.c" ``` what's the advandage of including .c files?
By doing this, they may be allowing the compiler to do more inlining and/or space optimization. uCos is an embedded operating system, so anything that saves space or time is a good thing. (Within reason, of course)
I have extracted a MAC address into achar*array such that each section of the array is a pair of char values. ``` mac[0] = "a1" mac[1] = "b2" ... mac[5] = "f6" ``` Basically I need to take the char arrays and convert them to an unsigned char such that the hex representation is the same as the original char values. ...
My C isn't the best, but this works using strtol(start, [stop], base) ``` #include <stdlib.h> #include <stdio.h> int main(char ** argv, int argc) { char * input = "a1"; printf("%d\n", (unsigned char)strtol(input, NULL, 16)); } ```
I want a debug function-macro that works like this: ``` int myVar = 5; PRINTVAR(myVar); // macro // which expands to something like... print("myVar: "); println(myVar); ``` Basically, I want to use the identifier as a string literal as well as a variable. I'm just getting a bit sick of repeating myself when I want...
The "stringizing operator" is designed for precisely this case: ``` #define PRINT_VAR(x) (print(#x ": "), println(x)) ```
If I want to create a 2D array, with dimensions specified by user input, can't I just do this sequentially in the main function? Once I have the dimensions by using scanf, I then create an array with those dimensions? From what I understood, malloc is supposed to be used when the space required is not known at runtime...
Generally there are three reaons to use dynamic allocation in C: The size is not known until runtime (another alternative isVLA's, but that's C99 and potentially dangerous, see reason 2).The size is (most likely) too big for the stack, risking stack overflow.The object needs to live on the heap giving it a longer lif...
I know thatcdis a shell built-in ,and I can run it by usingsystem(). But is that possible to run thecdcommand by theexec()family, likeexecvp()? Edit: And I just noticed thatsystem("cd")is also meaningless。Thanks for the help of everyone.
execloads anexecutable fileand replaces the current program image with it. As you rightly noted,cdisnotan executable file, but rather a shell builtin. So the executable that you want to run is the shell itself. This is of course whatsystem()does for you, but if you want to be explicit about it, you can useexec: ``` e...
For testing purposes, I need to share some definitions between Tcl and C. Is it possible to include C style include file in Tcl scripts? Any alternative suggestion will be welcomed, but I prefer not to write a parser for C header file.
SWIG supports Tcl so possibly you can make use of that. Also I remember seeing some code to parse C headers on the Tcl wiki - so you might try looking at theParsing Cpage there. That should save you writing one from scratch.
Suppose I declared an array as following: ``` int myArr = [someSize]; ``` Now I put n elements(where n is not known exactly but n < someSize)in it like this ``` myArray[0] = 12; myArray[1] = 23; and so on ..... ``` Now I want to know is there any way to find out exactly how many elements have been entered by the...
You can't get any such information from the array. If you need it, you'll want to record it. When I've needed this, I've usually used something like: ``` struct myArray_t { size_t next_element; int arr[somesize]; }; ``` When you create this, you setnext_elementto 0, and to add an element, you use something ...
I have declaredtypedef void (*DoRunTimeChecks)(); How do I store that as a field in a struct? How do I assign it? How do I call the fn()?
Just put it in like you would any other field: ``` struct example { int x; DoRunTimeChecks y; }; void Function(void) { } struct example anExample = { 12, Function }; ``` To assign to the field: ``` anExample.y = Function; ``` To call the function: ``` anExample.y(); ```
when I read ucos source files, I find this code in ucos_ii.c ``` #include "os_core.c" #include "os_mbox.c" #include "os_mem.c" #include "os_q.c" #include "os_sem.c" #include "os_task.c" #include "os_time.c" ``` what's the advandage of including .c files?
By doing this, they may be allowing the compiler to do more inlining and/or space optimization. uCos is an embedded operating system, so anything that saves space or time is a good thing. (Within reason, of course)
I have extracted a MAC address into achar*array such that each section of the array is a pair of char values. ``` mac[0] = "a1" mac[1] = "b2" ... mac[5] = "f6" ``` Basically I need to take the char arrays and convert them to an unsigned char such that the hex representation is the same as the original char values. ...
My C isn't the best, but this works using strtol(start, [stop], base) ``` #include <stdlib.h> #include <stdio.h> int main(char ** argv, int argc) { char * input = "a1"; printf("%d\n", (unsigned char)strtol(input, NULL, 16)); } ```
I want a debug function-macro that works like this: ``` int myVar = 5; PRINTVAR(myVar); // macro // which expands to something like... print("myVar: "); println(myVar); ``` Basically, I want to use the identifier as a string literal as well as a variable. I'm just getting a bit sick of repeating myself when I want...
The "stringizing operator" is designed for precisely this case: ``` #define PRINT_VAR(x) (print(#x ": "), println(x)) ```
I'm writing a module which exports an interface similar tosendandrecv. Since those functions are supposed to return respectively the number of sent and received bytes, I cannot do proper error management as I would do normally (i.e. using enumeratives and returning mnemonic values). In a situation like this should I...
This is a bit old, buterrno - manual section 3says that you can directly assign to it, even though it is a macro, and it will be thread local
In other words, if I fill twounordered_map, orunordered_set, objects with exactly the same content and the same hashing function, will iterating over them give the same sequence of key/value pairs? If so, then what are the conditions for this to hold (e.g. same hashing function, same keys, not necessarily same values...
No. There is no requirement, for example, that objects that have the same hash be placed in any particular order. In fact, in general it's impossible for an unordered map to do this because the only information it has access to is the hash value.
I am getting a compilation error for the following statement: ``` void read_text(int & c1, int & c2, string file1, string file2 ) ``` I seem to get error when passing the address; the error message is below: ``` Error 13 error C2143: syntax error : missing ')' before '&' \\vmware-host\shared folders\school\misc...
C does allow passing a pointer, which is the usual mechanism for parameter references. However, the syntax is not as used in C++, which you have used. Instead it is: ``` void read_text(int * c1, int * c2, string file1, string file2) ```
I have a struct which has several arrays within it. The arrays have type unsigned char[4]. I can initialize each element by calling ``` struct->array1[0] = (unsigned char) something; ... struct->array1[3] = (unsigned char) something; ``` Just wondering if there is a way to initialize all 4 values in one line. SOL...
If you really mean "initialize" in the sense that you can do it at the time you declare the variable, then sure: ``` struct x { unsigned char array1[4]; unsigned char array2[4]; }; struct x mystruct = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; ```
This question already has answers here:C/C++: Pointer Arithmetic(7 answers)Closed5 years ago. Why is the difference between the two addresses wrong?http://codepad.org/NGDqFWjJ ``` #include<stdio.h> int main() { int i = 10, j = 20; int *p = &i; int *q = &j; int c = p - q; printf("%d\n", p); printf("...
First, pointer arithmetic isn't defined when performed on unrelated pointers. Second, it makes sense. When subtracting pointers you get the number of elements between those addresses, not the number of bytes. If you were to try that with ``` char *p1 = &i, *p2 = &j; ``` you would get a different result. As a si...
I have to correct an existing C file which has a bunch of format specifiers compilation errors. Can anyone tell the correct format specifiers for the following cases: u_char(*) [10](I tried %s, but didn't work)char(*) [10](I tried %s and %c, but didn't work) Thanks.
Both are pointers to arrays, so you can dereference them to become arrays, which decay to pointers-to-first-element: ``` char arr[10]; char (*pa)[10] = &arr; printf("%s", *pa); // or &((*pa)[0]) ``` To spell it out: the type ofpaischar(*)[10], and the type of*paischar[10], and the latter decays to achar*of value&...
I have a file lets say "c:\file1.txt" that has an ADS file lets say stm so "c:\file1.txt:stm" now I want to delete the stm without modifying file1 I read somewhere that I need to have an old copy of file1.txt without ADS in order to remove the ADS by replacing file1 with stream with the one that doesnt have one ... ...
All you need to do is delete the stream by name. Using the Windows API that would be: ``` DeleteFile("c:\\file1.txt:stm"); ``` You could use plenty of other APIs to do the same thing though, or the command line. Helpful reference:http://www.flexhex.com/docs/articles/alternate-streams.phtml
If I have an C++ enum: ``` enum Foo { Bar, Baz, Bork, }; ``` How do I tell the compiler to use auint16_tto actually store the value of the enum? EDIT: Does GCC support this feature in its implementation of C++11?
You cannot do this in C++98/03. C++11 does allow you to do it, andwithoutenum classthe way everyone else seems to keep telling you: ``` enum EnumType : uint16_t { Bar, Baz, Bork, }; ``` Again, you don't have to useenum class. Not that it's a bad idea, but you don'thaveto. Does GCC support this feature in it...
I have the binary number 1010 1011. I know that this is AB in hex and I know that A = 10 and B = 11 in decimal. But how do I get from 10 and 11 in decimal to the final number of 171? With hex I would do ``` A B 0xAB = (10 * 16^1) + (11 * 16^0) = 171 ``` Can I do something similar with the decimal numbers...
I don't think there's a much easier way than A × 16 + B.
I'm using MPI for performing parallel processing, after i compile the application using mpicc, where do i copy the executable file on other machines?
You don't. The MPI implementation will invoke it for you on the remote machines when you call thempirun(or equivalent) command to launch your application.
my question is will garbage collector will free a memory if the variable allocated is malloced again without freeing the memory. eg: ``` ptr1 = malloc(100) ptr1 = malloc(200) ``` In this case will the first allocated memory will be deallocated by garbage collector?? If yes then when..???
No, it will result in a memory leak. There is no garbage collector in C.You have to do the memory management yourself. ``` ptr1 = malloc(100); free(ptr1); ptr1 = malloc(200); ... ... free(ptr1); ```
like the plots in:http://www.cs.berkeley.edu/~ballard/cs267.sp11/hw1/results/ Using some statistics tool(such as R, matlab) could achieve this, but it is not convinent enough. I mainly use C, java and python for algorithm implementation.
Caliperis really good at measuring the performance of Java programs, and generates nice plots in a cute web interface. (You can see examples on its home page, both of how to write a benchmark, and of the plots it generates.)
I'm trying to write some C code which is portable only so far as the user hasgcc, and hasglibinstalled. From all my research, I've found that withgcc, awchar_tis always defined as 4 bytes, and withglibagunicharis also 4 bytes. What Ihaven'tfigured out is if like agunichar, awchar_tis encoded as UCS4 as well. Is this...
If you use GLib, don't usewchar_t. Use its unicode support, it'sa lotbetter than the C standard library's support. wchar_tis 4 bytes on Linux and Mac OS (and a few others), not on Windows (it's 2 bytes there) and some others. Portable code means avoidingwchar_tlike the plague.
If I would want to operate on pointers which point to one byte should I use void* or char*, because I heard that ``` sizeof(char) ``` isn't always 1 byte, and what about void*? If I do ``` void *p ++p ``` will it point everywhere one byte further?
In Cpointer arithmetic is not defined for void pointers. Pointer arithmetic is intrinsically tied to the size of the pointed type. And forvoid *the size of the pointed type is unknown. To see how pointer arithmetic works for different objects, try this: ``` int obj[5]; int *ip = obj; char *cp = (char *)obj; ip++; c...
``` static uint8_t togglecode[256] = { [0x3A] CAPSLOCK, [0x45] NUMLOCK, [0x46] SCROLLLOCK }; ``` What's the meaning of[0x3A]here? I have only learned statements likeint a[2] = {1, 2};
It means initialise then-th element of the array. The example you've given will mean that: ``` togglecode[0x3A] == CAPSLOCK togglecode[0x45] == NUMLOCK togglecode[0x46] == SCROLLLOCK ``` These are called"designated initializers", and are actually part of the C99 standard. However, the syntax without the=is not. From...
i am making a module which would generate and transmit ip packets for voice. I know i had to set some value to the type of service field . what would be that value ?
That value should bex.
I have found this line of code in a game that I study ``` int charaCode = arc4random() % (126-'!'+1)+'!'; ``` I know what arc4random is but the expression is strange to me. What is the purpose of ``` (126-'!'+1)+'!' ``` It always evaluates to 127.
You interpreted it wrong: the%operator has a higher precedence than+. So, in effect, you have: ``` int charaCode = (arc4random() % (126-'!'+1))+'!'; ``` which clips the function result to0..93and shifts it so that it starts with'!'. So the effective range of what you get is33..126(which is the range of all visible...
I want my program to open a file if it exists, or else create the file. I'm trying the following code but I'm getting a debug assertion at freopen.c. Would I be better off using fclose and then fopen immediately afterward? ``` FILE *fptr; fptr = fopen("scores.dat", "rb+"); if(fptr == NULL) //if file does not ...
You typically have to do this in a single syscall, or else you will get a race condition. This will open for reading and writing, creating the file if necessary. ``` FILE *fp = fopen("scores.dat", "ab+"); ``` If you want to read it and then write a new version from scratch, then do it as two steps. ``` FILE *fp = ...
I am searching for the way to download concrete pieces of file (e.q. first or last 1Mb) via bittorrent programmically. C / C++, Java or Ruby libraries would be good solutions for me. Is there any solution in opensource world?
Azureusis written in Java, and is provided onSourceForge http://azureus.sourceforge.net/download.php
I am trying to runindent -kr -i8on all files in my current directory. Being a C programmer, the idea that came to my mind was to fork processes equal to the number of fles, the run exec on them. But I know things can be simplified with shell scripts. Any kind of help is appreciated.
Can you not just: ``` indent -kr -i8 *.c ``` You mention forking processes, so if you wanted to do it concurrently: ``` for f in *.c do indent -kr -i8 $f & done ``` But that will trash the cpu if you've got a load of files. So in batches: ``` limit=10 for f in *.c do indent -kr -i8 $f & (( count = count...
Is there a way to get my hands on the intermediate source code produced by the OpenMP pragmas? I would like to see how each kind of pragmas is translated. Cheers.
OpenMp pragmas is part of a C / C++ compiler's implementation. Therefore before using it, you need to ensure that your compiler will support the pragmas ! If they are not supported, then they are ignored, so you may get no errors at compilation, but multi-thread wont work. In any case, as mentioned above, since they a...
fromhere ``` 48 struct snd_card *snd_cards[SNDRV_CARDS]; 49 EXPORT_SYMBOL(snd_cards); ``` I am not getting whats the meaning of it and why that is used. I tried to search about it but not understanding the meaning of that.
It makes a symbol accessible to dynamically loaded modules (provided that said modules add anexterndeclaration). Not long ago,someone asked how to use it.
When I add ``` #pragma GCC diagnostic error "-Wreturn-type" ``` the compiler produces warnings, not errors for each missingreturn. How can I make it turn this particular warning into an error? Test code: ``` #pragma GCC diagnostic error "-Wreturn-type" int foo(int x) { if (x) return 8; } int main(int narg, c...
Try passing-Werror=return-typeto gcc!
Are there any best practices for the use of higher-level Python constructs such asthreading.Condition, andcollections.dequefrom modules written in C? In particular: Avoiding dict lookup costs, for methods and membersAccessing parts of these constructs thatarein C directly where possibleWhen to reimplement desired fun...
String lookups on a dict are very cheap in Python, but if desired you can cache them in a struct.There usually is no provision for doing so, since these libraries are meant to be accessed via Python and not C. It is still possible to generate your own headers that match the definitions in the C modules, but they would...
I have a union type of array of three integers (4 bytes each), a float (4 bytes), a double (8 bytes) and a character (1 byte). if I assign 0x31313131 to each of the three integer elements and then printed the union's character, I will get the number 1. Why ? I don't understand the output I know that the bits of 3 0x...
Because '1' == 0x31. You are printing it as character, not integer. since it is a union all the int and char share the same memory location (the float and double does not matter in this context). So assigning 0x31313131 to the intdoesaffect the char value -- nothing much confusing there.
What's the difference between ``` char* name ``` which points to a constant string literal, and ``` const char* name ```
char*is amutablepointer to amutablecharacter/string. const char*is amutablepointer to animmutablecharacter/string. You cannot change the contents of the location(s) this pointer points to. Also, compilers are required to give error messages when you try to do so. For the same reason, conversion fromconst char *tochar...
I am trying to design a multithreaded web server in C using Pthreads and i am having a problem in accepting more incoming connections without serving them. I want to put the file descriptor of each recieved connection in a buffer to be pocessed by a thread, Im using default accept(2) for accepting clients connections...
A common way of doing multi-threaded servers is to create a new thread right after you accept a new connection, and pass the new socket to that thread. Something like this: ``` int main(int argc, char *argv[]) { /* ... */ int client_socket = accept(server_socket); pthread_create(&thread, NULL, my_connect...
Basic question.. had to ask. Any help will be appreciated. Q: Why can't I dereference the pointer to a multidimensional array like this: ``` int arr [2][2] = { {1, 2} , {3, 4} }; printf("%d ", *arr); ```
Youcandereference it, it is just that the result is not going to be what you'd expect:*arris not anint, it's apointer to anint(OK, a one-dimensional array). If you want to see1printed, add another star: ``` printf("%d ", **arr); ```
``` u_int32_t ip6_address[1][4] = { {0x00000001, 0x0, 0x0, 0x12345678} }; ``` How would the above look in a RAM hex-dump byte-by-byte when running on an x86 PC CPU?
Sometimes it's easiest to just look: ``` $ cat example.c #include <stdint.h> uint32_t ip6_address[1][4] = { {0x00000001, 0x0, 0x0, 0x12345678} }; $ make example.o clang -Wall -Wextra -pedantic -c -o example.o example.c $ otool -d example.o example.o: (__DATA,__data) section 0000000000000000 01 00 00 00 00 00 0...
Is there a good library for parsing dates from a string in Haskell or ANSI C? Something like PHP's strtotime, or Ruby's Time.parse or Chronic, or whatever. If it can parse "next week", etc, then that's ideal, but even if it can just figure out for itself what format a complete date string is in and return the result...
After much hunting, I discovered that the date code in Git is pretty good and not very dependent on the rest of Git, so I pulled it out and madehttp://hackage.haskell.org/package/git-date I'm willing to use a better solution if there is one :)
I have seen thatXGetKeyboardMapping()would let me do that, but the documentation is opaque and I haven’t been able to find any examples. Any idea?
You are looking for: KeyCodeXKeysymToKeycode(display, keysym) Display *display; KeySym keysym; keycode1 = XKeysymToKeycode(display, XK_dead_acute); Also see this answer
While looking for ways to find the size of a file given aFILE*, I came acrossthis articleadvising against it. Instead, it seems to encourage using file descriptors andfstat. However I was under the impression thatfstat,openand file descriptors in general are not as portable (After a bit of searching, I've found somet...
In standard C, thefseek/ftelldance is pretty much the only game in town. Anything else you'd do depends at least in some way on the specific environment your program runs in. Unfortunately said dance also has its problems as described in the articles you've linked. I guess you could always read everything out of th...
I have a parse tree for my compiler, and i was wondering what traversal of my parse tree will give me the same order in which my Source Code was tested for the generation, I think it should be Pre-order, but i am told it is in-order , can someone tell me why. Also, if i want to find out that in my parser, when was s...
to get it clear, you parse something like: ``` x = a + b ``` the preorder is: ``` (=, (+, a, b)) ``` and inorder is ``` (x, =, (a, +, b)) ``` right? I am not sure what you mean with "the same order in which my Source Code was tested for the generation", but I really guess that you ask for the inorder of your ex...
Out of curiosity is it possible to temporarily add a character that should be interpreted as EOF? For example using the read() syscall in a loop, and have it abort on'\n'by register the new line character as EOF temporarily.
Nope, not possible. If you want to read from a file descriptor until you encounter a specific character, and avoid reading anything past it (so as not to consume input needed later by another process, for instance) the only solution is to perform 1-byte reads. It's slow but that's how it is.
I got 10 C files. 10 h files all in one folder. I need those files to create 1 executable in the same folder using unix makefile. EDIT : the soultion create a file named "makefile" write the following make sure you have a single TAB before the word "gcc" this will create a.out executable ``` all: gcc *.c ``` i...
I don't think you want what you say you want, but how about: ``` all: gcc *.c ```
I can understand the difference between asigned charand anunsignedone. But dont the pointers of the corresponding type equivalent in their operation? Cossizeof(char)andsizeof(unsigned char)is always the same ( Or are there any counter examples? ) For pointers, only the size of the data type should matter. Are there a...
Here is a counter example based on the difference in ranges of types pointed by each pointer type: ``` #include <stdio.h> int main() { unsigned char *uc; char *c; unsigned char v = 128; uc = &v; c = &v; if (*uc != *c) printf("there is difference\n"); return 0; } ```
The outcome of the following macro is clear: ``` #define CRASH() do {\ *(int *)(uintptr_t)0xbbadbeef = 0;\ ((void(*)())0)();\ } while (false) ``` My question is, what does the line ``` ((void(*)())0)(); ``` break down to, in English? For example, "this is a function that returns a pointer to a...."
It looks like it casts0as a function pointer (with the signature that it takes not parameters and has void return type) and then invokes it. ``` ( ( void(*)() ) 0 ) (); /* cast..*/ /* fn pointer signature */ /*..cast 0 */ /* invocation */ ``` Which is another way to say...
I noticed today that I can't use*to pass width or precision arguments to Java's implementation ofprintf. That is, the following arguments toprintfare valid in C, but not Java: ``` "%*d", 10, 3 "%-*d", 10, 3 "%0*d", 10, 3 "%*.5f", 11, 1.0/9 "%-11.*f", 5, 1.0/9 "%0*.*f", 11, 5, 1.0/9 ``` Are there any other implement...
I wouldn't think of it as differences. I'd just read through theJava documentationcarefully and go entirely from that. Thinking in terms of differences is likely to lead to things slipping through the net. In other words, I'd treat thesimilaritiesas coincidences, and assume the two are different until proven otherwis...
Im currently developing with WebkitGtk+ Unstable Api I'm using Soupsession Object to conect Signals and Rertve Soupmessages to (again) hook signals to every Message to obtain time details of network events, my problem is how to monitor errors from this point. if I'm using just the signal, there is a way to detect whe...
Some time ago i figured it out. the errors are reported in the responce http code of the soup message https://developer.gnome.org/libsoup/stable/libsoup-2.4-soup-status.html I just needed to capture the status code in the soup message signal "finished" to know if the resource failed (and why) or if was successful
I want to trim a music file(mp3).I want to do it in c,c++ or Java.So what are the libraries that I can use to do this.I want it for my android application.So help me on how it can be integrated with my application.It is good if someone has some answers regarding this?
There are already several similar but not identical questions around: How to "Trim" an Audio File in Java, C# or PHP (For Browser) java mp3/audio editing/trimming library Crop MP3 to first 30 seconds and also ways to utilize them: ffmpeg for a android (using tutorial: "ffmpeg and Android.mk")
I can understand the difference between asigned charand anunsignedone. But dont the pointers of the corresponding type equivalent in their operation? Cossizeof(char)andsizeof(unsigned char)is always the same ( Or are there any counter examples? ) For pointers, only the size of the data type should matter. Are there a...
Here is a counter example based on the difference in ranges of types pointed by each pointer type: ``` #include <stdio.h> int main() { unsigned char *uc; char *c; unsigned char v = 128; uc = &v; c = &v; if (*uc != *c) printf("there is difference\n"); return 0; } ```
The outcome of the following macro is clear: ``` #define CRASH() do {\ *(int *)(uintptr_t)0xbbadbeef = 0;\ ((void(*)())0)();\ } while (false) ``` My question is, what does the line ``` ((void(*)())0)(); ``` break down to, in English? For example, "this is a function that returns a pointer to a...."
It looks like it casts0as a function pointer (with the signature that it takes not parameters and has void return type) and then invokes it. ``` ( ( void(*)() ) 0 ) (); /* cast..*/ /* fn pointer signature */ /*..cast 0 */ /* invocation */ ``` Which is another way to say...
I noticed today that I can't use*to pass width or precision arguments to Java's implementation ofprintf. That is, the following arguments toprintfare valid in C, but not Java: ``` "%*d", 10, 3 "%-*d", 10, 3 "%0*d", 10, 3 "%*.5f", 11, 1.0/9 "%-11.*f", 5, 1.0/9 "%0*.*f", 11, 5, 1.0/9 ``` Are there any other implement...
I wouldn't think of it as differences. I'd just read through theJava documentationcarefully and go entirely from that. Thinking in terms of differences is likely to lead to things slipping through the net. In other words, I'd treat thesimilaritiesas coincidences, and assume the two are different until proven otherwis...
Im currently developing with WebkitGtk+ Unstable Api I'm using Soupsession Object to conect Signals and Rertve Soupmessages to (again) hook signals to every Message to obtain time details of network events, my problem is how to monitor errors from this point. if I'm using just the signal, there is a way to detect whe...
Some time ago i figured it out. the errors are reported in the responce http code of the soup message https://developer.gnome.org/libsoup/stable/libsoup-2.4-soup-status.html I just needed to capture the status code in the soup message signal "finished" to know if the resource failed (and why) or if was successful
I want to trim a music file(mp3).I want to do it in c,c++ or Java.So what are the libraries that I can use to do this.I want it for my android application.So help me on how it can be integrated with my application.It is good if someone has some answers regarding this?
There are already several similar but not identical questions around: How to "Trim" an Audio File in Java, C# or PHP (For Browser) java mp3/audio editing/trimming library Crop MP3 to first 30 seconds and also ways to utilize them: ffmpeg for a android (using tutorial: "ffmpeg and Android.mk")
I want to make a kernel module in which I would be able to send the packet from my kernel module. the thing is how should I populate the network_header, transport header and mac header?
If you are not so much concerned with the mac header, then have a look at this code to generate the packetsGenerating packets
My C is quite rusty. Consider the code above: must I free up the memory for buf or each call uses the same buf array ? What is the best practice ? ``` JNIEXPORT jstring JNICALL Java_test_version (JNIEnv *env, jobject obj, jint handle) { struct VersionNumber ver; versionNumber_get((void *) handle, &ver); ...
bufis a stack variable, it will be reclaimed as the method returns, there is nothing for you to do here. Also because it is a stack variable it will be allocated for each method call.
http://linux.die.net/man/2/mlockall mlockall() locks all of the calling process's virtual address space into RAM, preventing that memory from being paged to the swap area. why is this important in real time systems?
It ensures the memory isalwaysin RAM and never moved to the swap disk. This makes accessing those memory locationsmuchfaster as disks are extremely slow compared to RAM. In a realtime system (linux is NOT a RTS btw!) you need extremely low latencies so a memory access resulting in a disk access is usually not accepta...
What will be the order the function calls in the following expression: ``` a = f1(23, 14) * f2(12/4) + f3(); ``` Does it depend on the compiler?
Order of evaluation of each operand isunspecifiedin C and C++, which means, in your case, the order of function calling isunspecifiedas per the Standards. Note that it isunspecified,notimplementation-defined.
This question already has answers here:Closed11 years ago. Possible Duplicate:Why does printf print wrong values? ``` #include<stdio.h> int main(int argc, const char *argv[]){ float f1 = 125.2f; printf("\n [%f] [%d] [%g]",f1,f1,f1); printf("\n [%f] [%g] [%d]",f1,f1,f1); printf("\n [%g] [%f] [%d]",f...
printfis not type safe so using a incorrect format descriptor results inUndefined Behavior. An Undefined Behavior means that any observable behavior is possible because the code is not abiding the rules laid out by the standard.
I'm debugging a piece of (embedded) software. I've set a breakpoint on a function, and for some reason, once I've reached that breakpoint andcontinueI always come back to the function (which is an initialisation function which should only be called once). When I remove the breakpoint, andcontinue, GDB tells me: Progr...
The other possibility i can think of is: 1.Your process is runningmore than one thread. For eg - 2 say x & y. 2.Thread y hits the break pointbut you haveattached gdb to thread x. This case is a Trace/breakpoint trap.
I'm currently trying to port a C application toAIXand am getting confused. What are .a and .so files and how are they used when building/running an application?
Archive libraries (.a) are statically linked i.e when you compile your program with -c option in gcc. So, if there's any change in library, you need to compile and build your code again. The advantage of .so (shared object) over .a library is that they are linked during the runtime i.e. after creation of your .o file...
How can I get GDB to print all the source files that it recognises? I've tried setting a breakpoint: ``` break test.c:35 ``` but GDB complains: ``` No source file name test.c ``` However, I know that GDBhasrecognised this file because it recognises the functions defined in it.
You can do it byinfo sourcescommand. ``` (gdb) info sources Source files for which symbols have been read in: Source files for which symbols will be read in on demand: /root/test.cpp (gdb) ``` In your casetest.cshould be listed.
Why doesn't this code print "New time", more than once? And is it possible to fix, without calling clock() outside the loop? ``` #include <stdio.h> #include <time.h> int main(char argv[], int argc) { double lastTime = 0; while(1) { printf("New time:\n"); while(lastTime == (lastTime = (doub...
Your code seems to have been cut off. But your problem is with this logic: ``` while (lastTime == (lastTime = something)) ``` The test will always be true; you assign some value to lastTime, then compare it with itself.
is it possible to do calculation like this in C? ``` A*exp(i*(b+c)) + D*exp(i*(e+f)), ``` where A,b,c,D,e,f are real numbers.
C99 introduces support for complex numbers. Whether or not your compiler implements this feature I don't know.
I am using open/read functions, there's feof for fopen/fread to detect end-of-file, what's the equivalent way for open/read?
Fromman read: On success, the number of bytes read is returned (zero indicates end of file), ...
``` #define MAX 100 struct bs{ int ab; int ac; }be; struct s{ be b; int c; int d; int e; }fe; int a[MAX]; fe f; ``` Technique 1: ``` f.b.ab = a; memset(&a,0,sizeof(a)); f.b.ac = MAX; ``` Technique 2: ``` f.b.ab = a; f.b.ac = MAX; memset(&a,0,sizeof(a)); ``` Technique 3: ``` memset(&a,0,sizeof(a)); f.b.ab...
Technique 3: ``` memset(&a,0,sizeof(a)); f.b.ab = a; f.b.ac = MAX; ``` because bothaandfb.b.abwill have clear memories with onlyonememset()call. Any other kind of optimization you might been hoping for is insignificant.
This code running on Linux: ``` int r, c; ... assert(0 == (O_NONBLOCK & fcntl(sockfd, F_GETFL, 0))); errno = 0; r = read(sockfd, &c, 1); if (r == 0 && errno == 0) { printf("What gives?\n"); } ... ``` which is performing a read from a socket, will occasionally return zero (inr) and leaveerrnoset to zero (0) as w...
This means that the client finished sending data (eg: did ashutdownfor writing), and you already read all available data. RETURN VALUEOn success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number.
I've got a piece of C code: ``` Int32 tmp = atoi("314"); ``` It throws an error: ``` error: Int32 undeclared (first use in this function) ``` I have no idea why? Could you help me? Maybe it is problem with#includes: sys/socket.hnetinet/in.harpa/inet.hstdio.hstdlib.hstring.hstrings.h
There is no standard type calledInt32. You're probably looking for ``` int tmp = atoi("314"); ``` If you need a 32-bit integer, the standard type isint32_tdefined ininttypes.horstdint.h.
Why doesn't this code do anything when i execute it? It's supposed to count characters i even pressed ctrl+z which someone suggested and it still wont print how many characters after i entered random things. I'm using windows btw ``` #include <stdio.h> int main() { long nc; nc = 0; while (getchar() != EOF) ...
It works if you pressCTRL+Zand then enter. This triggersEOF. If you want it to end when you press enter, use ``` while( getchar() != '\n' ) ```
What is the best way to store a uint32_t, uint8_t in the shared memory in continuous successions? i.e. if we representuint32_tasaanduint8_tasb, i want to store it in shared memory as ababababababababababababab what is the best way to do this? should I use void* and then typecast it each time i write something to sha...
An array of a packed struct sounds like a good bet, no casting needed.
I want to use shared memory across processes and wanted to use therobust pthread mutexesfor the same, because, they can help with the problem when a process dies holding the mutex. My only concern is, are they portable across different platforms - different versions of linux and then on different operating systems too...
POSIX mandatespthread_mutexattr_getrobust. And hence allPOSIX compliant systemsshould support it. Also note thatpthread_mutexattr_getrobustwas first introduced in Issue 7. iePOSIX:2008Do check this on the systems where you want to port. On the latest linux variants, I think you should be safe.
I was wondering if there are any compilers that support a considerable amount of the new C11 standard. Looking for features like Generic Selection etc. Any suggestions?
Pelles C version 7.00 (Release Candidate is available now) http://www.smorgasbordet.com/pellesc/
Say I have this function: ``` int epic(int); ``` I know of these naming conventions, are these right? Do other very common ones exist? ``` long epicl (long); long long epicll (long long); unsigned int epicu (unsigned int); unsigned long epicul (unsigned long); unsigned long long epicull (u...
Sometimes, if the return type differs from the argument type(s), a prefix is used to indicate this. Consider for example the following (from C99): ``` double round(double x); float roundf(float x); long double roundl(long double x); long int lround(double x); long int lroundf(float x); long int lroundl(long double x...
As far as I know about data types in C/C++, while declaring a variable, we need to declare its data type, which tells the compiler to reserve the number of bytes in the memory accordingly. But in the case of pointers, we know that their size is constant (eg. 2 bytes in "Turbo Compiler"), irrespective of the data type...
The data type is needed whendereferencing the pointerso it knows how much data it should read. For example dereferencing acharpointer should read the next byte from the address it is pointing to while anintpointer should read 2 bytes.
This code running on Linux: ``` int r, c; ... assert(0 == (O_NONBLOCK & fcntl(sockfd, F_GETFL, 0))); errno = 0; r = read(sockfd, &c, 1); if (r == 0 && errno == 0) { printf("What gives?\n"); } ... ``` which is performing a read from a socket, will occasionally return zero (inr) and leaveerrnoset to zero (0) as w...
This means that the client finished sending data (eg: did ashutdownfor writing), and you already read all available data. RETURN VALUEOn success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number.
I've got a piece of C code: ``` Int32 tmp = atoi("314"); ``` It throws an error: ``` error: Int32 undeclared (first use in this function) ``` I have no idea why? Could you help me? Maybe it is problem with#includes: sys/socket.hnetinet/in.harpa/inet.hstdio.hstdlib.hstring.hstrings.h
There is no standard type calledInt32. You're probably looking for ``` int tmp = atoi("314"); ``` If you need a 32-bit integer, the standard type isint32_tdefined ininttypes.horstdint.h.
Why doesn't this code do anything when i execute it? It's supposed to count characters i even pressed ctrl+z which someone suggested and it still wont print how many characters after i entered random things. I'm using windows btw ``` #include <stdio.h> int main() { long nc; nc = 0; while (getchar() != EOF) ...
It works if you pressCTRL+Zand then enter. This triggersEOF. If you want it to end when you press enter, use ``` while( getchar() != '\n' ) ```
What is the best way to store a uint32_t, uint8_t in the shared memory in continuous successions? i.e. if we representuint32_tasaanduint8_tasb, i want to store it in shared memory as ababababababababababababab what is the best way to do this? should I use void* and then typecast it each time i write something to sha...
An array of a packed struct sounds like a good bet, no casting needed.
I want to use shared memory across processes and wanted to use therobust pthread mutexesfor the same, because, they can help with the problem when a process dies holding the mutex. My only concern is, are they portable across different platforms - different versions of linux and then on different operating systems too...
POSIX mandatespthread_mutexattr_getrobust. And hence allPOSIX compliant systemsshould support it. Also note thatpthread_mutexattr_getrobustwas first introduced in Issue 7. iePOSIX:2008Do check this on the systems where you want to port. On the latest linux variants, I think you should be safe.