Posts

Showing posts with the label C

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.

"-bash: Gcc: Command Not Found" Using Cygwin When Compiling C?

Image
Answer : You can install gcc by running setup-x86.exe or setup-x86_64.exe again. The gcc package is in the Devel category: Then you must go to System properties, System variables, and append the path to "C:\cygwin64\bin" in PATH If you have already added the gcc package you want you may also need to setup a symbolic link to a different gcc.exe binary. For example: $cd /usr/bin/ $ln -s i686-pc-cygwin-gcc.exe gcc $which gcc $/usr/bin/gcc You can add the gcc package through the 'Add Package' batch file.

Clear/truncate File In C When Already Open In "r+" Mode

Answer : With standard C, the only way is to reopen the file in "w+" mode every time you need to truncate. You can use freopen() for this. "w+" will continue to allow reading from it, so there's no need to close and reopen yet again in "r+" mode. The semantics of "w+" are: Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file. (Taken from the fopen(3) man page.) You can pass a NULL pointer as the filename parameter when using freopen() : my_file = freopen(NULL, "w+", my_file); If you don't need to read from the file anymore at all, when "w" mode will also do just fine. You can write a function something like this:(pseudo code) if(this is linux box) use truncate() else if (this is windows box) use _chsize_s() This is the most straightforward solution for your requirement. Refer: man truncate and ...

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 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 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 : 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...

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...

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...

Combining C++ And C - How Does #ifdef __cplusplus Work?

Answer : extern "C" doesn't really change the way that the compiler reads the code. If your code is in a .c file, it will be compiled as C, if it is in a .cpp file, it will be compiled as C++ (unless you do something strange to your configuration). What extern "C" does is affect linkage. C++ functions, when compiled, have their names mangled -- this is what makes overloading possible. The function name gets modified based on the types and number of parameters, so that two functions with the same name will have different symbol names. Code inside an extern "C" is still C++ code. There are limitations on what you can do in an extern "C" block, but they're all about linkage. You can't define any new symbols that can't be built with C linkage. That means no classes or templates, for example. extern "C" blocks nest nicely. There's also extern "C++" if you find yourself hopelessly trapped ins...

Codeblocks Can't Find My Compiler

Answer : I faced the same problem. I have fixed out by going to Setting -> Compiler -> Global Compiler Settings -> Toolchain Execuatables (tab) . There, click on Program Files and then rename C compiler to gcc.exe and C++ compiler to g++.exe . I know this is an old question but let me see if I can help. First of all, on the download page make sure you downloaded codeblocks-13.12mingw-setup.exe and NOT codeblocks-13.12-setup.exe. Of course the version numbers may change but pay attention to the name. Then after installing codeblocks, go to Settings->Compiler->Toolchain executables. From here, change the C compiler to gcc.exe and C++ compiler to g++.exe. Hope this helps anyone else going through this problem :-)

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-...

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

Atoi Implementation In C

Answer : << is bit shift, (k<<3)+(k<<1) is k*10 , written by someone who thought he was more clever than a compiler (well, he was wrong...) (*p) - '0' is subtracting the value of character 0 from the character pointed by p , effectively converting the character to a number. I hope you can figure out the rest... just remember how the decimal system works. Here is a specification for the standard function atoi . Sorry for not quoting the standard, but this will work just as fine (from: http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/ ) The function first discards as many whitespace characters (as in isspace ) as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many base-10 digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral n...

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...

CMake Zlib Build On Windows

Answer : According to https://wiki.apache.org/httpd/Win64Compilation a very similar error means: This means you have a typo in either -DASMV -DASMINF or your OBJ="inffasx64.obj gvmat64.obj inffas8664.obj" since inflate_fast is defined in inffas8664.c. I was able to successfully build with a simple: mkdir C:\Builds\zlib; cd C:\Builds\zlib cmake -G "Visual Studio 12 2013" -A x64 D:\Downloads\zlib-1.2.8\ cmake --build . I looked at my cmake cache and I see that AMD64 is set to false, unlike what your cmake-gui window shows. Setting it to true it results all kinds of build errors for me, though not the ones you show. CMakeLists.txt says this option is to enable an AMD64 assembly implementation. Just doing without this seems to be the easiest solution. You need contrib\masmx64\inffas8664.c included in visual studio project file. This file contains inflate_fast function which calls corresponding asm functions. Date: 20180804 ( Aug 4 th 2018 ) W...
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.

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/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...