Posts

Showing posts with the label C++

A Simple Explanation Of What Is MinGW

Answer : MinGW is a complete GCC toolchain (including half a dozen frontends, such as C, C++, Ada, Go, and whatnot) for the Windows platform which compiles for and links to the Windows OS component C Runtime Library in msvcrt.dll. Rather it tries to be minimal (hence the name). This means, unlike Cygwin, MinGW does not attempt to offer a complete POSIX layer on top of Windows, but on the other hand it does not require you to link with a special compatibility library. It therefore also does not have any GPL-license implications for the programs you write (notable exception: profiling libraries, but you will not normally distribute those so that does not matter). The newer MinGW-w64 comes with a roughly 99% complete Windows API binding (excluding ATL and such) including x64 support and experimental ARM implementations. You may occasionally find some exotic constant undefined, but for what 99% of the people use 99% of the time, it just works perfectly well. You can also use t...

C11 In GCC?

Answer : The standard C11 header for threading is <threads.h> , not <thread.h> . See section 7.26 of the N1570 draft. Most of the C standard library, including stdio for example, is not included in the gcc distribution. Instead, gcc depends on whatever runtime library is provided by the operating system. That generally includes both the headers (like <threads.h> ) and the actual code that implements the library. For most Linux systems (or GNU/Linux if you prefer), the library is GNU's glibc; for other systems it will be something else. So the real question is probably when glibc, or whichever C library you're using, will support C11's threading features. glibc adds support for C11 threads in version 2.28. Ubuntu 18.04.1 LTS system currently still uses glibc 2.27. Again, this applies only to implementations using GNU libc, not to all gcc-based implementations. Mentioned by WorldSEnder in a comment. UPDATE: Ubuntu 18.10 (not an LTS (Long Term Su...

C: Linux Command Executed By Popen() Function Not Showing Results

Answer : Since the output is going to stderr you need to redirect stderr like so: FILE* file = popen("ntpdate 2>&1", "r"); this will redirect stderr to stdout and so you will see output from both. Second issue fscanf will stop at the first space so you can replace with fgets : fgets(buffer, 100, file); As Shafik Yaghmour correctly diagnosed, the output you see from ntpdate is written (correctly) to its standard error, which is the same as your programs standard error. To get the error messages sent down the pipe, use: FILE *file = popen("ntpdate 2>&1", "r"); That sends the standard error output from ntpdate to the standard output of the command, which is the pipe you're reading from. Of course, it looks like using ntpdate isn't going to work well until you've configured something.

C: How To Free Nodes In The Linked List?

Answer : An iterative function to free your list: void freeList(struct node* head) { struct node* tmp; while (head != NULL) { tmp = head; head = head->next; free(tmp); } } What the function is doing is the follow: check if head is NULL, if yes the list is empty and we just return Save the head in a tmp variable, and make head point to the next node on your list (this is done in head = head->next Now we can safely free(tmp) variable, and head just points to the rest of the list, go back to step 1 Simply by iterating over the list: struct node *n = head; while(n){ struct node *n1 = n; n = n->next; free(n1); }

C Function To Convert Float To Byte Array

Answer : Easiest is to make a union: #include <stdio.h> int main(void) { int ii; union { float a; unsigned char bytes[4]; } thing; thing.a = 1.234; for (ii=0; ii<4; ii++) printf ("byte %d is %02x\n", ii, thing.bytes[ii]); return 0; } Output: byte 0 is b6 byte 1 is f3 byte 2 is 9d byte 3 is 3f Note - there is no guarantee about the byte order… it depends on your machine architecture. To get your function to work, do this: void float2Bytes(byte bytes_temp[4],float float_variable){ union { float a; unsigned char bytes[4]; } thing; thing.a = float_variable; memcpy(bytes_temp, thing.bytes, 4); } Or to really hack it: void float2Bytes(byte bytes_temp[4],float float_variable){ memcpy(bytes_temp, (unsigned char*) (&float_variable), 4); } Note - in either case I make sure to copy the data to the location given as the input parameter. This is crucial, as local variables will not exist after you return (alt...

C : Typedef Struct Name {...}; VS Typedef Struct{...} Name;

Answer : There are several things going on here. First, as others have said, the compiler's complaint about unknown type may be because you need to define the types before using them. More important though is to understand the syntax of 3 things: (1) struct definition, (2) struct declaration, and (3) typedef. When Defining a struct, the struct can be named, or unnamed (if unnamed, then it must be used immediately (will explain what this means further below)). struct Name { ... }; This defines a type called "struct Name" which then can be used to Declare a struct variable: struct Name myNameStruct; This declares a variable called myNameStruct which is a struct of type struct Name . You can also Define a struct, and declare a struct variable at the same time: struct Name { ... } myNameStruct; As before, this declares a variable called myNameStruct which is a struct of type struct Name ... But it does it at the same time it defines the type str...

.c Vs .cc Vs. .cpp Vs .hpp Vs .h Vs .cxx

Answer : Historically, the first extensions used for C++ were .c and .h , exactly like for C. This caused practical problems, especially the .c which didn't allow build systems to easily differentiate C++ and C files. Unix, on which C++ has been developed, has case sensitive file systems. So some used .C for C++ files. Other used .c++ , .cc and .cxx . .C and .c++ have the problem that they aren't available on other file systems and their use quickly dropped. DOS and Windows C++ compilers tended to use .cpp , and some of them make the choice difficult, if not impossible, to configure. Portability consideration made that choice the most common, even outside MS-Windows. Headers have used the corresponding .H , .h++ , .hh , .hxx and .hpp . But unlike the main files, .h remains to this day a popular choice for C++ even with the disadvantage that it doesn't allow to know if the header can be included in C context or not. Standard headers now have no extension ...

C Char Array Initialization

Answer : This is not how you initialize an array, but for: The first declaration: char buf[10] = ""; is equivalent to char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; The second declaration: char buf[10] = " "; is equivalent to char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0}; The third declaration: char buf[10] = "a"; is equivalent to char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0}; As you can see, no random content: if there are fewer initializers, the remaining of the array is initialized with 0 . This the case even if the array is declared inside a function. Edit: OP (or an editor) silently changed some of the single quotes in the original question to double quotes at some point after I provided this answer. Your code will result in compiler errors. Your first code fragment: char buf[10] ; buf = '' is doubly illegal. First, in C, there is no such thing as an empty char . You can use double quote...

C/C++ Why To Use Unsigned Char For Binary Data?

Answer : In C the unsigned char data type is the only data type that has all the following three properties simultaneously it has no padding bits, that it where all storage bits contribute to the value of the data no bitwise operation starting from a value of that type, when converted back into that type, can produce overflow, trap representations or undefined behavior it may alias other data types without violating the "aliasing rules", that is that access to the same data through a pointer that is typed differently will be guaranteed to see all modifications if these are the properties of a "binary" data type you are looking for, you definitively should use unsigned char . For the second property we need a type that is unsigned . For these all conversion are defined with modulo arihmetic, here modulo UCHAR_MAX+1 , 256 in most 99% of the architectures. All conversion of wider values to unsigned char thereby just corresponds to truncation to the leas...

C Warning Implicit Declaration Of Function 'exit'

Answer : Add: #include <stdlib.h> to the top of your program. Do you have this preprocessor? If not, add it. #include <stdlib.h> exit() is a library function, the respecive prototypes are present in the stdlib.h header file, inoder to call the process to specified code for exit function, you need to attach the as #include stdlib.h header in your program. that is the reason we should add the stdlib.h header. eventhough you can run the program, but it shows the warning message like below: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default] but, this kind of program not recommended, we need to take care of what we are given in the program,be cautious. warning may leads runtime error.

C Puts() Without Newline

Answer : Typically one would use fputs() instead of puts() to omit the newline. In your code, the puts(input); would become: fputs(input, stdout); puts() adds the newline character by the library specification. You can use printf instead, where you can control what gets printed with a format string: printf("%s", input); You can also write a custom puts function: #include <stdio.h> int my_puts(char const s[static 1]) { for (size_t i = 0; s[i]; ++i) if (putchar(s[i]) == EOF) return EOF; return 0; } int main() { my_puts("testing "); my_puts("C puts() without "); my_puts("newline"); return 0; } Output: testing C puts() without newline
Answer : Two errors here: first, you're trying to declare arrays[63] for storing 64 elements, as you've probably confused the size of array ( n ) with the maximum possible index value (that's n - 1 ). So it definitely should be litera[64] and liczba[64] . BTW, you have to change this line too - while (i<=64) : otherwise you end up trying to access 65th element. And second, you're trying to fill char value with %s format specifier for scanf, while you should have used %c here. Also, can't help wondering why you declare liczba array as one that stores int s, that initialize it with array of char s. All these '1', '2', etc... literals represent NOT the corresponding digits - but the charcodes for them. I doubt that was your intent.

Convert Unsigned Int To Signed Int C

Answer : It seems like you are expecting int and unsigned int to be a 16-bit integer. That's apparently not the case. Most likely, it's a 32-bit integer - which is large enough to avoid the wrap-around that you're expecting. Note that there is no fully C-compliant way to do this because casting between signed/unsigned for values out of range is implementation-defined. But this will still work in most cases: unsigned int x = 65529; int y = (short) x; // If short is a 16-bit integer. or alternatively: unsigned int x = 65529; int y = (int16_t) x; // This is defined in <stdint.h> I know it's an old question, but it's a good one, so how about this? unsigned short int x = 65529U; short int y = *(short int*)&x; printf("%d\n", y); @Mysticial got it. A short is usually 16-bit and will illustrate the answer: int main() { unsigned int x = 65529; int y = (int) x; printf("%d\n", y); unsigned short z = 65529; short...

C Read Binary Stdin

Answer : What you need is freopen() . From the manpage: If filename is a null pointer, the freopen() function shall attempt to change the mode of the stream to that specified by mode, as if the name of the file currently associated with the stream had been used. In this case, the file descriptor associated with the stream need not be closed if the call to freopen() succeeds. It is implementation-defined which changes of mode are permitted (if any), and under what circumstances. Basically, the best you can really do is this: freopen(NULL, "rb", stdin); This will reopen stdin to be the same input stream, but in binary mode. In the normal mode, reading from stdin on Windows will convert \r\n (Windows newline) to the single character ASCII 10. Using the "rb" mode disables this conversion so that you can properly read in binary data. freopen() returns a filehandle, but it's the previous value (before we put it in binary mode), so don't use i...

C - Freeing Structs

Answer : Simple answer : free(testPerson) is enough . Remember you can use free() only when you have allocated memory using malloc , calloc or realloc . In your case you have only malloced memory for testPerson so freeing that is sufficient. If you have used char * firstname , *last surName then in that case to store name you must have allocated the memory and that's why you had to free each member individually. Here is also a point it should be in the reverse order; that means, the memory allocated for elements is done later so free() it first then free the pointer to object. Freeing each element you can see the demo shown below: typedef struct Person { char * firstname , *last surName; }Person; Person *ptrobj =malloc(sizeof(Person)); // memory allocation for struct ptrobj->firstname = malloc(n); // memory allocation for firstname ptrobj->surName = malloc(m); // memory allocation for surName . . // do whatever you want free(ptrobj->surName); free(ptrobj-...

Convert ASCII Character To X11 Keycode

Answer : This question has an old, wrong answer (from @oldrinb), that oddly has never been challenged. As stated in the comment, you can't use XStringToKeysym to map chars to KeySyms in a general way. It will work for letters and numbers, but that's about it, because the KeySym name happens to map directly for those ASCII characters. For other ASCII characters such as punctuation or space it won't work. But you can do better than that. If you look at <X11/keysymdef.h> you find that for ASCII 0x20-0xFF, the characters map directly to XKeySyms . So, I'd say it's simpler to just use that range of characters directly as KeySyms , and just map the remaining 32 characters to their corresponding KeyCodes . So I'd say the code should more properly be: Display *display = ...; if ((int)c >= 0x20) { XKeysymToKeycode(display, (KeySym)c); } else { ... // Exercise left to the reader :-) } The 'else' clause will require multiple KeyCodes since f...

C Implementation Of Matlab Interp1 Function (linear Interpolation)

Answer : I've ported Luis's code to c++. It seems to be working but I haven't checked it a lot, so be aware and re-check your results. #include <vector> #include <cfloat> #include <math.h> vector< float > interp1( vector< float > &x, vector< float > &y, vector< float > &x_new ) { vector< float > y_new; y_new.reserve( x_new.size() ); std::vector< float > dx, dy, slope, intercept; dx.reserve( x.size() ); dy.reserve( x.size() ); slope.reserve( x.size() ); intercept.reserve( x.size() ); for( int i = 0; i < x.size(); ++i ){ if( i < x.size()-1 ) { dx.push_back( x[i+1] - x[i] ); dy.push_back( y[i+1] - y[i] ); slope.push_back( dy[i] / dx[i] ); intercept.push_back( y[i] - x[i] * slope[i] ); } else { dx.push_back( dx[i-1] ); dy.push_back( dy[i-1] ); slo...