Consider this implementation ofstrtok()in C ``` char *pt; pt = strtok(line, ":"); if (pt != NULL) { pt = strtok(NULL, ":"); } ``` why doesn'tpthave to be explicitly allocated memory? Likept[128]orpt = malloc(...)? I would have thought the above implementation would segfault. Do I have to worry about deallocation?
linehas to reference modifiablechararray and moststrtokimplementations are using this memory. It is the reason why you do not have to provide any additional memory for this operation. Remember thatlinewill be modified (destroyed) during this operation. ptwill hold (if notNULL) the reference to one of the elements of the array referenced byline
I am trying to extract two last characters from achararray and has been unable to do so. The array will be given to me and I don't have control over it. I only know the lastnpositions of the array are digits. In the following casen=2: ``` char c[5] = "xyz45" char d[2]; d[0] = c[3]; d[1] = c[4]; int e = atoi(d); ``` Clearly the value oferequired is45. Any way to solve this? (The above approach is a representative way about how one might go about doing this in python. I am looking for an elegant way to do this.)
I only know the lastnpositions of the array are digits. A simple loop suffices (assuming no overflow insum): ``` char c[] = ... int len = ... // length of the array int n = ... int sum = 0; for (int i = len - n; i < len; i++) { sum = sum * 10 + (c[i] - '0'); } printf("%d\n", sum); ```
I am trying to figure out this issue: I tried to run this two easy codes ``` int main(void) { while(1) { printf("Do nothing\n"); } return 0; } ``` When I execute it my memory RAM runs out. Then I tried this variation: ``` int main(void) { while(1) { // do nothing } return 0; } ``` And on that case my code runs without running out RAM. My question is: why does it happen? Doesprintfoccupied memory or maybe I am overloadingstdout?Thanks!
If the terminal that is running out of memory, then yes, the terminal isn't clearing the stdout properly. If it's the program itself running out of memory, then i don't know actually.
I understand that normally arrays are unassignable. However I recently came across this ``` struct S { int arr[6]; }; ``` And this lets me do something like this ``` struct S a = {1, 2, 3, 4, 5, 6}; struct S b; b = a; // b.arr is now a deep clone of a.arr? ``` This seems odd because I would have thought such assignment would result in a shallow copy being stored in b, as only the address of the first element of a.arr would be copied?
Arrays are strange in C. They're distinct from pointers, but many operations on them make them implicitlydecayinto pointers, which can misguide you to think they the same. This array is stored inline into eachstruct Sinstance. Upon assignment, its copied in its entirety, just like any otherintmembers that might be inside the struct instance. There's no shallow-copy vs deep-copy distinction here, because there is no out-of-line pointer-referenced data to be worried about.
I know thatprintf(user_input)is dangerous, but what aboutprintf("%s", user_input)? Is this generally safe as longuser_inputis NUL terminated?
I know thatprintf(user_input)is dangerous, but what aboutprintf("%s", user_input)? Is this generally safe? The latter is among the replacements commonly recommended for the former. It resolvesthe issue that makesprintf(user_input)particularlydangerous. There remain more general issues such as what happens ifuser_inputis not a pointer to a null-terminated string, or if the string contains characters that elicit special behavior from the output device, or if the standard output stream has been closed, or maybe other things. I'm not sure "generally safe" is a good description of all that, but perhaps it is indeed what you meant.
I found the result ofnextafter(0., 1.)with data typedoubleandfloatare not the same. ``` #include <math.h> #include <stdio.h> int main(){ double a; float b; a=nextafter(0., 1.); b=nextafter(0., 1.); printf("default %e\n",nextafter(0., 1.)); printf("double %e\n",a); //double 4.940656e-324 printf("float %e\n",b); //float 0.000000e+00 return 0; } ``` Why the smallestfloatbigger than 0.0 is 0.000000e+00 ?
When you callnextafter(0., 1.)and store the result in afloat, implicit type conversion happens. The function returns the smallest positive subnormaldouble, which is 4.940656 x 10⁻³²⁴. This value is then rounded tofloat, but it's too small to be represented as afloat, leading to zero. To get the correctfloatresult, you should usenextafterf(0.f, 1.f): ``` float b = nextafterf(0.f, 1.f); ``` This will give you the smallest positive subnormalfloat.
If I write my prime check function like her., ``` for(int i=2; i<=sqrt(n); ++i) {//code} ``` Will that sqrt() calculated for every iteration or the C compiler is smart enough to calculate the sqrt once and store the result ? Assume n as a constantI know register could be used for loop variableMine is gcc lastest version compiler Any suggestion would be really helpful. Thank you
If the compiler can reliably establish thatnindeed never changes, it is free to optimise it by calculating it up front. This behaviour (an implementation basically rewriting your code for efficiency as long as theeffectis the same) is true of all code. However, this "reliable establishment" maynotbe as easy as you think :-) If you don't want to concern yourself with the possibility that it may not be detected as constant, simply do it yourself with something like: ``` double sqrn = sqrt(n); for (int i = 2; i <= sqrn; ++i) { //code } ```
I am new to C so I hope I am using the right terminology. I have seen a number of resources suggesting that one should use VLA syntax for function parameters that should be non-null pointers like so ``` void foo(char bar[static 1]) ``` meaningbarshould be a non-null pointer to a char because pointer decay. Some compilers might emit a warning about passing a null-pointer. I am wondering how I would then declare the parameter as aconstpointer to aconstchar. So what would be the VLA syntax equivalent of ``` void foo(char bar* const) ``` This works for pointer toconst char ``` void foo(const char bar[static 1]) ``` but ``` void foo(const char const bar[static 1]) ``` emits a warning about duplicateconst.
You need to put theconstkeyword inside of the square brackets: ``` void foo(const char bar[static const 1]) ``` This is (more or less) equivalent to: ``` void foo(const char * const bar) ```
I'm working on a C project in Visual Studio Code and I would like to use GNU formatting in the project. Is there any extension to achieve this or any way to go about it?
TheC/C++ extensionhasClangFormatincluded with it, and there is a setting calledC_Cpp.clang_format_stylethat allows you to set the formatting to select options including GNU: In your case, you would want to set this particular setting toGNU. Settings JSON: ``` { "C_Cpp.clang_format_style": "GNU" } ```
In this loop I print each of the values in an array "values." They appear as 93832734557896 instead of 9383 2734 557 896, etc: ``` for( n = 0 ; n < num_values; n++ ) { printf("%llu", values[n]); } ``` I want to print a space after each number, not a newline. How can I do that with printf? Thanks
To print a space between the numbers only, without a leading or trailing space for the entire data printed, you can use a variable separator string: ``` const char *separator = ""; for( n = 0 ; n < num_values; n++ ) { printf("%s%llu", separator, values[n]); separator = " "; } ``` Note that the separator starts as a zero-length string, is printedbeforethe value, and is then set to a string that contains a single space. This technique is also well-suited for printing comma-separated data.
My cyclomatic complexity in this C program is supposed to be 1, so I can't write if else statements. ``` #include <stdio.h> int main() { int U,V; scanf("%d %d",&U,&V); printf("%0d",(U*V)/2); } ```
The expression(U*V)/2performs integer division since all operands are integers. This truncates any fractional part. If you want to round up, you first need to perform floating point division, which you can do by changing one operand to a floating point type. Then you can pass the result to theroundfunction which rounds to the nearest integer, with the .5 case being rounded up. ``` printf("%0d",(int)round((U*V)/2.0)); ```
I am writing software that needs to compare two _mm256 vectors for equality. However, I would like there to be a margin of error +/- 0.00001. Eg, 3.00001 should be considered equal to 3.00002. Is there a simple way to do this using SSE/AVX/AVX2 instructions?
Subtract values being compared, mask out sign with*_and_*or*_andnot_*, compare with*_cmpgt_*against your margin populated with*_set1_*
Let's say I have a header file calleda"b.hora>b.h, how do I escape the"or>character in an include directive? ``` // this does not work #include "a\"b.h" ```
>character is not allowed as part of filename when using#include <filename>directive (and respectively,"is not allowed as part of filename in#include "filename"). There is no standard way to escape any characters in the sequence, any such feature would be a compiler extension.cppreference link. For the specific case of filenamea>b.h, you can change it to#include "a>b.h"and it should work. Filenamea"b.his out of luck - even in#include <a"b.h>it's implementation-defined how"character is treated (or if supported at all). Aside from", also using characters',\,//or/*in filename part of#includedirective is implementation-defined and may be unsupported.
I am studying max heap and in it there is a createheap function. In it , there is a for loop like this ``` for (i = 0; i < capacity; i++) { h->arr[i] = nums[i]; } ``` if size of nums is not equal to capacity then does the variable i gives the size of nums or is it equal to capacity? (the for loop runs tilliis equal to capacity ,right?)
...the for loop runs till i is equal to capacity ,right? ~~No.~~ Maybe. Whencapacityexceeds "the size of nums", onceiis equal to "the size of nums", further iterations lead toundefined behavior(UB). Anything may happen, including executing untili == capacity, crashing due to accessing memory it doesn't own,replacing your hotel with a football stadium, etc.
I found the following answer:Convert void* to double However, I am getting segmetation fault. Why is that? Code: ``` void * p = (void *) 1234; double n = *(double *)p; ```
Pointerpis assigned to address 1234 that you chose atrandom?. You are then referencing arandomaddress. It does not correspond to a valid allocated chunk of memory.
``` #include <stdio.h> void main(){ int *i = (int *) malloc(12); *i[0] = 1; printf("%d", *i[0]); } ``` iis supposed to be a pointer. So then why doesn't this code work? and why does this code 👇 work? ``` void main(){ int *i = (int *) malloc(12); i[0] = 1; printf("%d", i[0]); } ```
When you add index operator "[]" after a poitner - you are telling the compiler "Hey, take this pointer, then do pointer arithmetic on it with the value within the [] bracets, and dereference the address it points to". Saying it with other words - when you add index operator "[]", your pointer gets treated as regular variable, and does not need additional dereferencing operator. It's already dereferenced.
In the bookC How to Program, 8/eby Paul and Harvey Deitel it is written, under the section Initializing and Assigning Values to Pointers, that "When 0 is assigned, it’s first converted to a pointer of the appropriate type. The value 0 is the only integer value that can be assigned directly to a pointer variable." It is also written in thisanswer. What do they mean by the it? What does it mean for zero to be converted to a pointer of the appropriate type? Can a value be type converted?
It simply means that a C compiler must treat the literal integer value0to indicate a NULL pointer. i.e. ``` int * x = 0; ``` and ``` int * x = NULL; ``` ... are guaranteed to be equivalent, even onunusual hardwarewhere the address pointed to by a NULL pointer isn't actually address zero.
I am trying to unit test code on x86 that uses uint_least8_t. On one of the targets this is actually a uint16_t so I'd like to be able to unit test with uint_least8_t being both uint8_t and uint16_t. What's a good way of redefining uint_least8_t (and variants) to 16-bit types? I tried to do a simpletypedef uint16_t uint_least8_t;but the compiler complains about the redefinition. I could replace all uint_least8_t with yet another type (ie.my_uint_least8_t), but would prefer not to have to modify all the code. Is there an easy way to achieve this? (C11, GCC)
Create your ownstdint.hfile in some test dir. Add the path to that to compiler include path with-Iforthe whole project. In thatstdint.hdo#include_next <stdint.h>. After that in thatstdint.h#undefall preprocessor macros when needed and#define uint_least8_t uint16_t.
I have a c-code where I define some variables for pre-processing using the#definecommand. However, I think that there are ways to toggle between float and double data types by doing for example: ``` #define 1.0f // float data type ``` or ``` #define 1.0 // double data type ``` Is there a way I can use it to set a variable of long double data types?
Suffix thefloat constantwithlorLto give it typelong double: ``` 1.0L ``` Do note that float constants only have meaning to C. As far as thepreprocessoris concerned, that's just a string of four characters, no different from any other.
``` #include <stdio.h> #define LINE_FILE ("Line %d of file %s", __LINE__, __FILE__) int main(void) { const char* str = LINE_FILE; printf("%s\n", str); printf("Line %d of file %s\n", __LINE__, __FILE__); } ``` First print statement only prints the file name and not the complete line.
If you want a string pre-formatted like that, here's how you do it: ``` #include <stdio.h> #define STR_IMPL(x) #x #define STR(x) STR_IMPL(x) #define LINE_FILE ("Line " STR(__LINE__) " of file " __FILE__) int main() { printf("%s\n", LINE_FILE); } ```
Suppose we have many C functions with the same signature and return type: ``` R f(X x,Y y){...} R g(X x,Y y){...} R h(X x,Y y){...} ``` whereXandYare the types of the arguments andRis the type of the result. We can declare those functions, for instance in a header file or as forward declarations, like this: ``` R f(X,Y);R g(X,Y);R h(X,Y); ``` or more concisely: ``` R f(X,Y),g(X,Y),h(X,Y); ``` or, avoiding most repetition: ``` typedef R F(X,Y); F f,g,h; ``` Can that be done in a single statement, without a separatetypedef?
I have not checked yet but maybe in C23 there is possible to write ``` typeof( R( X, Y ) ) f, g, h; ```
This question already has answers here:Undefined behavior and sequence points(5 answers)Closedlast month. If post fix decrement(--x) is equal to (x-1) so why when I changefactorial(n-1)tofactorial(--n)it gives me a logical error ofoutput = 0 ``` #include<stdio.h> int factorial (int n) { int fact=1; if (n>=1) { fact=n*factorial(n-1); } return fact; } void main (void) { int x , y ; printf("Please Enter a Number : "); scanf("%d",&x); y=factorial(x); printf("Factorial = %d ",y); } ```
Making that change: ``` fact=n*factorial(--n); ``` Results in an expression which both reads and writesnwithout an intervening sequence point, which triggersundefined behaviorin your code.
This question already has answers here:C - Printing negative int values as hex produces too many characters(3 answers)Closedlast month. I had expected each memory address contain 1-byte data. But on below code, I getting 4-byte hex value. Why this happened? I'm aware of negativeintrepresentation. ``` char num = -25; char *ptr = &num; printf("%02X", *ptr); ``` Output : FFFF FFE7 Expected : E7 Edit : Another good answer in here :
``` printf("%02X", *ptr); ``` *ptris being converted tointand printed asint You need to use the correct printf format: ``` printf("%02hhX", *ptr); ```
How to make fabs() for __m128 vector ? Does I have to use sign bits to multiply the original vector by 1.0f/-1.0f ? Didn't find any instruction set to do it. I don't want __m256 or 512. I'm searching for __m128 data type
A single AND-NOT using a prepared constant to turn off the sign bits suffices: ``` #include <stdio.h> #include <xmmintrin.h> int main(void) { static const __m128 MinusZero = { -0.f, -0.f, -0.f, -0.f }; __m128 x = { +1, -2, +3, -4 }; __m128 y = _mm_andnot_ps(MinusZero, x); printf("%g %g %g %g\n", y[0], y[1], y[2], y[3]); } ``` Output: ``` 1 2 3 4 ```
Segmentation error in stdio.h ``` #include <stdio.h> int main() { char arr[4]={"abcd"}; char *p; p=arr; for(int i;i<4;i++) { printf("%s\n",p[i]); } return 0; } ``` i dont know why it is showing as segmentation error in my stdio.h file while im just doing a simple code............................................................................
There are two mistakes: ``` for (int i = 0; i < 4; i++) { // i must be initialized printf("%c\n", p[i]); // use %c instead of %s } ``` When leavingiuninitialized it has an indeterminate value and reading from it makes the program have undefined behavior.Using%s(which expects aconst char*) when you supply anintalso has undefined behavior.%cis for printing a single character.
Suppose the memory address of a struct in C language is stored in a variable of sufficiently wide integer type, such asuintptr_t.I want to read the contents of struct by casting the integer to a struct pointer and dereferencing that. Can the original struct be reconstructed using this approach?
Yes, just do it and it works. ``` uintptr_t v = …; struct someStruct *s = (void *)v; struct someStruct valueOfS = *s; ``` As for whether it is legal by the spec, it depends on how you got the value ofv.
I am studying strings and found that string ends with a null character - "\0". Is it possible to change this default null character by something else like "\1"? I was performing the following code - ``` #include<stdio.h> #include<string.h> int main(){ const char *str = "App\0le"; printf("%c", *(str+5)); } ```
Yes and no. You can use any sentinel in your char arrays but it will not be used instring literals. You will have to write your own string functions (file too). ``` size_t mystrlen(const char *str) { const char *end = str; while(*end != '\1') end++; return end - str; } int main(void) { char *str = "12345\0006789\01"; // it will still append \0 to the end printf("%zu\n", mystrlen(str)); } ```
This question already has answers here:Why Am I Getting Link Errors When Calling Function in Math.h?(3 answers)Closedlast month. I am trying to find the the ceil of a variable which was been assigned a value but when I pass the function ceil("variable name") it throws an error. ``` #include <stdio.h> #include <math.h> int main() { double num = 8.33; int result; result = ceil(num); printf("Ceiling integer of %.2f = %d", num, result); return 0; } ``` And the error which I am gettin is-- ``` /usr/bin/ld: /tmp/ccG3j9iB.o: in function `main': maximumRebounding.c:(.text+0x1f): undefined reference to `ceil' collect2: error: ld returned 1 exit status ```
With the developer tools you are using, you must include-lmon the command that builds the executable file to tell the linker to use the math library. Put it on the command after object modules and libraries that use routines from the math library.
I have some code that gets file handles (and uses them) and allocates memory to the heap. If I were to press ctrl-c in the terminal that it is running in, and the code has not yet progressed to the part where it frees the memory and closes the handles before safely exiting, will they be still be freed, or do I need to create my own handler as shownin this post?
When you are executing as a user in a normal modern general-purpose multi-user operating system, the operating system will reclaim all resources when the program terminates regardless of the means by which the program terminates. That is a principal job of the operating system. It operates the system.
``` typedef struct { string color; int age; }Dog; int main(void) { Dog cookie = ("brown", 6); cookie.color = "blue"; cookie.age = 12; } ``` Hello, I'd like to know if there's a way to edit multiple structure values as such, while only using a single line instead of repeating "structName.varName" over and over. Would there be a similar method for changing multiple values for objects in C as well? Thank you so much.
You can assign multiple struct members a value at once, by using acompound literaltemporary object: ``` cookie = (Dog) { "blue", 12 }; ``` Or for increased readability, combine this withdesignated initializers(equivalent code): ``` cookie = (Dog) { .color = "blue", .age = 12 }; ```
I am tasked with creating a C program that writes a python program (which prints "hello world") and executes it. I have completed the first part (writing the python program to a file) but when I try to execute the python program from C, nothing happens. I directly tested the created file and it has the expected input so I am likely doing something wrong when attempting to execute the python program. I am attempting to use system() in order to execute the python program: ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main() { FILE *pfile; pfile = fopen("", "w"); fprintf(pfile, "print(\"hello world\")"); int system(const char *command); system("python3"); return 0; } ```
As the comments suggest, ``` fclose(pfile); ``` fixes the issue
Today I just start learning C language. I try to run my code, but I don't know where my output is?. I follow every step in youtube that I watch, and it still the same. This is my code: ``` #include <stdio.h> int main() { printf("Helo"); } ``` and after I try to run, there is some notification show on my desktop this is notification: How do I fix this, and where can I see my output? Thank you.
Click on the ok button so that the program (compiler) can create the executable file (.exe) file on your disk drive. This .exe file will then be run by the terminal to output you the expected result.
I'm trying to reconstructHow can I debug functions in shared object libraries with GDB?answer MINGW64 gdb - and I cannot: ``` $ cat add.c long add(long x, long y) { return x + y; } $ gcc -shared -o -fPIC add.c $ gdb GNU gdb (GDB) 13.2 ... (gdb) file Reading symbols from (gdb) starti Starting program: C:\msys64\tmp\ Error creating process C:\msys64\tmp\, (error 193: unknown win32 error (193)) ``` So, how would I go about calling a function in MINGW64gdb, in an .so file like this one, compiled with MINGW64gcc?
MINGW64 gdb - and I cannot: Your problem isnotthat you can't set a breakpoint; your problem is that you are trying toruna.sofile. You need an actualexecutable(which either depends on your.soor loads it dynamically). Theupvoted answeriswrong. Theother answeris correct.
I am confused about following C function, f_2(). It is written in .c file, code can be compiled by gcc. What is the name of this function style? How to interpret the meaning of this function? Is this standard C or some gcc extension? Thanks. ``` void f_1() { } int (*f_2(void *param)) (int, void *) { return 0; } int main() { f_2(NULL); return 0; } ```
The functionf_2takes avoid *arguments, and returns a pointer to a function. The pointer thatf_2returns is a pointer to a function that takes two arguments (anintand avoid *) and returns anint. It's equivalent to: ``` // Create a type-alias for a function pointer typedef int (*function_pointer_type)(int, void *); // Define a function that returns a pointer to a function function_pointer_type f_2(void *) { return NULL; } ```
I am trying to get the y value of a Vector3 (the camera), and i have looked at the documentation and haven't found a function to get a single value from the Vector3. I have tried using it like a list, but that obviously doesn't work. I have found some C++ documentation, but i am using plain C, and I don't want to mess with C++. Thanks!
AVector3is atypedef of a struct: ``` // Vector3, 3 components typedef struct Vector3 { float x; // Vector x component float y; // Vector y component float z; // Vector z component } Vector3; ``` So you can access theyfield as with any other struct. Ifmy_vect3is aVector3then you can access it withmy_vect3.y, and ifmy_vect3_pis a pointer to aVector3you can access it withmy_vect3_p->y.
I have ``` FILE *file = fopen("/proc/cmdline", "r"); struct stat st; fstat(file, &st); char buffer[st.st_size]; fgets(buffer, st.st_size,file); printf("%s", buffer); ``` By luck this prints out the contents of cmdline but I have an int pointer conversion warning at thefstat()function. If I tryfstat(fileno(file), &st);the buffer has gibberish meaning st.st_size wasn't properly set. Like wise seeking to the end of file to get it's size also is not setting the size of the buffer properly It seems st.st_size contains a number with a leading zero eg 01315 hence gibberish out put
How to read file size of /proc/cmdline (Assuming Linux) like so (error checking omitted for brevity): ``` #include <limits.h> ... char buf[ARG_MAX]; FILE *fp = fopen("/proc/cmdline", "rb"); size_t len = fread(buf, sizeof(buf), 1, fp); ```
This question already has answers here:Undefined, unspecified and implementation-defined behavior(9 answers)Closedlast month. What is the difference between ``` int *arp = NULL; int c; ++arp[c]; ``` And ``` int *arp = NULL; int c; arp[c]; c++; ``` Please I need to know the meaning of this increment++arp[c];
``` ++arp[c]; ``` This dereferencesarp[c](same as*(arp + c)) and then uses the pre-increment operator to increase the value inarp[c]by 1.cremains unchanged. ``` arp[c]; c++; ``` This dereferencesarp[c]but doesn't do anything with it so it's pointless. After that it uses the post-increment operator to increasecby 1.arp[c]remains unchanged. Note: Both snippets have undefined behavior becausearppoints atNULLandcis unintialized when you read from it.
Based on llvmlite docs I can create static array like in a code snippet bellow. ``` ir.Constant(ir.ArrayType(ir.ArrayType(i8, STR_SIZE), ARR_SIZE), elements) ``` But can I create dynamic array in llvmlite or convert variable above toi8.as_pointer().as_pointer()type?
char**isn't an array, it's a pointer to pointer tochar. C programs often use such a pointer and pretend that the type pointed to is something else. LLVM lets you do the same, and in a fairly similar way. If you look closely at thegetelementptrinstruction, you'll notice that it takes both a pointer argument and a type argument. The type is the type pointed to. If you pass gep an array type, a pointer and an index, it pretends that the pointer points to that type and returns a pointer to an array entry with the specified index, which you can thenloadand treat as a Value.
Why the indirection/dereferencing operator (*) is used with a pointer of any data type except a string? 'char' In the following program the letter 'A' and the string "Computer" are stored using the character pointers but only for the pointer 'a' the dereferencing operator (*) is used. Why is that? ``` #include <stdio.h> int main() { char *a, *b; *a = 'A'; b = "Computer"; printf("%c %s", *a, b); return 0; } ``` Why is the*operator not needed while assigning a string to a pointer?
Becauseb = "Computer";does not copy the string."Computer"is called"string literal"and it is a char array. You assign pointerbwith reference to the first string literal character. It is an equivalent of: ``` char *b; const char literal[] = {'C', 'o', 'm', 'p', 'u', 't', 'e', 'r', 0}; b = &literal[0]; ```
I am trying to check validity of pointers in C, specifically if a pointer is trying to access memory outside the known program space. Is there a way to get the addresses of the allotted program stack's bounds (hopefully a cross platorm method), so that before dereferencing a pointer we can at least make sure the pointer is in program space? I have no clue where to start and Google hasn't helped me so far.
First of all, comparing pointers (except equality) using pointers not referencing the same array is undefined. You would have (knowing the boundary of the available address space - which is a separate problem) to iterate through all the addresses and check for non-equality. It would be rather expensive and not practical... Is it possible in C (not invoking UB) to check if two objects overlap?
I am trying to run code that use zlib on Debian by using this command ``` gcc -o new double.c -lz -lm ``` But I have these errors : how to fix the errors please? ``` /usr/bin/ld: cannot find -lz collect2: error: ld returned 1 exit status ```
You need to install the library and the associated header files. This can be done using the following command: ``` sudo apt-get install zlib1g-dev ``` Note that you have indicated you have a file namedzlib.hin your project directory. This is wrong. Delete it, and use#include <zlib.h>instead of#include "zlib.h". This will use the correctzlib.h, the one installed by the above command.
I want to use command line: gcc {filename.c} -o {filename.exe} to compile source code but the real directory is too long, I need a way to minimize it, I need some guide if someone else faced the same problem. Below is my implementation. I'm coding on Window. ``` PS E:\CodingWorkspace\VScodeC> gcc LinkedList.c -o LinkedList.exe gcc.exe: error: LinkedList.c: No such file or directory gcc.exe: fatal error: no input files ``` I'm expecting a built LinkedList.exe and run it in Terminal Powershell
I figured out the problem, I have a folder in which store another folder that contains the file.c I need to run, but the terminal is open with the directory of the external folder, not the last folder that contains the file. This is the adjusted terminal code. It workedPS E:\CodingWorkspace\VScodeC\1000BaiCode> gcc Stack.c -o StackPS E:\CodingWorkspace\VScodeC\1000BaiCode> ./Stack
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closedlast month.Improve this question I had something like this in mind but I don't know how to implement it. As i'm a beginner (on the CS50 course), i don't really understand other answers I have came upon. Thanks for your help! ``` for (int i = 1; i < 16; i++) { int Ai= number % (10 * i); } ```
No, you cannot do this, but you can create an array and append the values to the array. For example: ``` #include <stdio.h> int A[15]; for (int i = 1; i < 16; i += 1) { //The reason for using i-1 as the index of the array is that i starts as 1, not 0 (array indices start at 0). A[i - 1] = number % (10 * i); } //The code below only prints the array. for (int i = 0; i < 15; i += 1){ printf("A%d: %d\n", i+1, arr[i]); } ```
Here is my code ``` char *sptr = "abc", *tptr; *tptr = *sptr; printf("ch = %c\n", *tptr); ``` Now, when we declare a pointer, no memory is allocated to store char variable. So, this code does run and'a'is printed on the console. I know that"abc"is a string literal and its a read only memory. But when I execute*tptr = *sptr, where is*tptris stored ?
The assignment*tptr = *sptr;invokes undefined behavior, since you're storing through an undefined pointer. It's a severe bug. Instead, you can dotptr = sptr;, which givestptrthe same value assptr.
red arrow shows up upon hover :'stdio.h' file not foundcompiles without any errorsI am pretty new to c (just started).I checked in cygwin directory the files do exist idk why this shows up tho. Should i be worried ? My code compiles and runs like normal. I did look up the files and they do exist in the right directory but idkupon searching the directory of cygwin
The Cygwinincludedirectory you found is probably not configured as one of the include paths in your editor. You seem to be using CodeLite, in which case look under: SettingsProject settingsCompilerInclude Paths/Additional search paths Thedocumentation sitehas screenshots and more options.
I have an assembly file that calls a C function that takes the argumentsint argc, char *argv[], with the assumption that whatshouldalready be on the stack (the command line arguments) will be passed to the function. But instead, it segfaults the moment the function is called. Any wisdom? Assembly: ``` extern func ; stuff over here _start: call func ; nothing manually pushed into stack. ; stuff over here ``` C: ``` struct of_my_creation func(int argc, char *argv[]) { printf("check"); // never runs; SIGSEGV comes first. } ``` OS: Parrot Linux Compiler: GCC 10 Architecture: x86-64 Thanks.
Thanks to A. Loiseau Passing the arguments intordiandrsiinstead of stack worked. New assembly: ``` extern func ; stuff over here _start: pop rdi lea rsi, [rsp] call func ; stuff over here ```
How would one get the master device of a network device they have an index of? I have looked into rtnetlink, but would prefer a simpler and more concise solution
Given the interface name you can read the value of/sys/class/net/<interface>/master. For example, on my system I have container with interfaceveth3c732e7. To find the associated bridge: ``` $ readlink /sys/class/net/veth3c732e7/master ../br-3d442aed4b81 ``` We can confirm that information with theip linkcommand: ``` $ ip link show veth3c732e7 510: veth3c732e7@if509: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br-3d442aed4b81 state UP mode DEFAULT group default link/ether 3e:66:b1:62:31:11 brd ff:ff:ff:ff:ff:ff link-netnsid 4 ``` If you want to know how to do this without using/sys, theiptool itself is open source. The relevant functions appear to behereandhere; it involves sending a netlink message and then receiving and parsing the response.
Recently i came across a problem written in C where there was some undefined behaviour due to which there was some segmentation error. While other people who helped me debugging it were getting warnings from their compiler which was GCC too. In my case while running that same problem in VS Code it gives no warnings and not even a single error and sadly no output. The execution starts and then closes own its own in the terminal. I use Windows 11. I want this kinds of warnings.People who helped me got this kind of warnings
You should try adding-Wall -Wextrawhen you compile, like this: gcc main.c -o executable.exe -Wall -Wextra Those options tell compiler to be more strict and show you more warnings. You can see what exactly they do on thispage
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed2 months ago.Improve this question I need to do complex numbers operation. After I defined a variable, named 'squareRoot', using "complex.h" stadard library, however, Visual Studio 2022 told me identifier 'squareRoot' is undefined. It made me comfused! What's wrong with my code?enter image description here I just want to know how to define a complex variable, even though I have referenced some similar codes that define that complex number.
Your code is fine as far as C is concerned, but Microsoft has always been a bit out of step with C standards. It seems that the functions fromcomplex.hare supported in VS2022, but you will have to use_Dcomplexin place ofdouble complex. You can read more aboutsupport forcomplex.hin Visual Studio 2022 here.
I am trying to make freetype But configure with an error My command ./configure --host=arm-buildroot-linux-gnueabihf --prefix=$PWD/tmp The error info ``` checking whether to build shared libraries... yes checking whether to build static libraries... yes checking for windows.h... no checking for x86_64-pc-linux-gnu-gcc... no checking for gcc... no checking for cc... no configure: error: cannot find native C compiler make: *** [builds/unix/ setup] Error 1 ``` What should I do to fix it?
Reload another Ubuntu iso can fix it
I wrote the following short Assembly LLVM code (I know it's not efficent only for testing purposes): ``` define void @main() { label_41: %t22 = add i32 0, 0 label_43: %t23 = add i32 0, 0 } ``` When I try to run it like this I get an error: ``` Downloads % /usr/local/opt/llvm/bin/lli t02.out /usr/local/opt/llvm/bin/lli: lli: t02.out:4:1: error: expected instruction opcode label_43: ^ ``` What's the problem, which opcode is missing?
A label in LLVM starts a new block. And each block must end with aterminator instructionsuch asretorbr. LLVM is giving the error because it reached a label but the preceding block didn't end with a terminator instruction. To get this to compile, you need to add terminator instructions beforelabel_43:and before the end of the function.
good day everyone, one of the required test quality metrics that we use for the C-Sources are statement and decision coverage. As the applied test tool does not provide the call coverage metric, can one argument that 100 % statement coverage of the given function implies 100% call coverage within this function ?
You cannot make that assumption. A statement can include conditional calls: ``` float kelvin = celsius ? c2k(deg) : f2k(deg); ``` Covering that statement alone will not ensure that all calls are made. PS: I once argued that that - if anything - full condition coverage (e.g. 100 % MC/DC) would give you the confidence of full call coverage. But I cannot find the blog article anymore.
I studied the manual for DirectX 9 and DirectX 11 and C++ was used there, I was wondering if there is DirectX support in C? I have studied C well enough and I want to try to write a small renderer on it. I don't really like OpenGL, DirectX is much more attractive to me.
Youcanuse DirectX COM interfaces from C, but the experience is generally unpleasant as it requires a lot of macros. COM interfaces map well to C++ abstract classes and single-inheritance hierarchies. It's also not well-tested as basically all users of DirectX use C++ and not C. The support that is there is basically whatever legacy behavior the MIDL compiler throws in there for C. You don't need to know much modern C++ to use them, so you could consider just using "C++ as a better C" for your code, and then take advantage of the more natural COM interface behavior.
I'm using OpenMPI for a little project, and I've got a doubt.When I use MPI_Ibcast to send an array to all the other processes, can I start computing on the same array? Example: ``` MPI_Ibcast(array, ... &request); compute(array); MPI_Wait(&request); ``` If I get it right, MPI_Ibcast does not save the array in a buffer, so I couldn't do that, but I'm not sure.
ForanyMPI_Iwhateveroperation you should not touch the buffer before the completion (theMPI_Waitwhatevercall). If it's a sending call (including abcastif you're the root) the data may not have been sent; if it's a receiving call (includingbcastif you're not the root) there is no guarantee that the data has arrived.
I want to change MCLK fsrates for 44100 sample rate audio on STM32F703. Right now my clock in STM32 is 207.36MHz I2S PLL values:N=147, R=2, Q=2 and PLLI2SDivQ=10 I2S clock is supplied with PLLI2SR which clock is 112.896. I have changed PLLI2SDivQ values but it doesn't affect the I2S MCLK clock I have observed it on Oscilloscope and its 112.896MHz even when PLLI2SDivQ is 10 or 5
The I2S clock determines thebit rate, not thesample_ratefor for 44.1ksps 16 bit stereo, you would need a bit rate of 1.4112x106bps The clock rate generator is as follows: Ref: STM32F72xx/3xx RM0431 With your stated configuration I2SxCLK is 11.2896MHz And the sample rate is calculated per: Ref: STM32F72xx/3xx RM0431 So for 44.1ksps you need the denominator in the appropriate formula above to be 11.2896MHz / 44.1ksps = 256 So for I2S mode 16-bit x 2, MCKOE=0: 32 x ((2 × I2SDIV) + ODD) = 256is achieved when I2SDIV = 4 and ODD=0.
When developing a library for PlatformIO and ESP32 (but also other platforms/environments), what ifdef macro name can be used to determine if the code is being compiled using PlatformIO? For example,#ifdef ESP32can be used to determine whether the build target is an ESP32. Is there a similar#ifdef PLATFORM_IOmacro that PlatformIO automatically sets that determines whether it's being built using PlatformIO? I tried Googling for a macro set by PlatformIO, but no results.
You could add your own inbuild_flags. Since such a macro would be defined in platformio.ini, it would be implicit that it is a PlatformIO build environment. Otherwise inspect platformio.ini, there may already be a suitable macro.Thissuggests thatPLATFORMIOmay be defined, further suggests:pio run -vorpio run -t envdumpto check macros predefined in the build environment. YMMV - I'm just Googling this stuff!
Am working on Renesas RH850F1KM microcontroller. Am doing coding for Safety Mechanism for Code Flash ECC module. In our code we are using __GETSR() function to store the PSW address for future use. But am facing the following error. function __GETSR declared implicitly More info: Compiler we are using : Green Hills Compiler (C:\ghs\multi_716\multi.exe)
The problem is lack of __GETSR() symbol defined. As you have noticed, the correct definition is in v800_ghs.h header file, which has to be included.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed3 months ago.Improve this question I am very new to C programming. I was going through some practicing and I was creating a program that will count the number of lines of text written. I used the getchar() function. I don't know why I can't print that value. Also, I tried to print the same value inside the loop and it did print. But that outputs a lot of values. So, I wanted to print the last value of the linecount. Here is my programHere's the output Why doesn't printf print the value outside that while loop??
What's happening is that your program is not getting out of the while loop. Did you try entering ``` Ctrl+z ``` followed by an enter. ??
I want to run gcc on Windows + MSYS2|UCRT64 with the-gcodeview flag, to generate pdb files. Those are required, to generate stacktraces including line numbers in source files. But gcc/g++ always reports, that the debug level is unrecognized:g++: error: unrecognized debug output level ‘codeview’ Do I have to compile and configure gcc with a specific flag to support CodeView?
The version of the GCC documentation you linked to is for thedevelopmentbranch 14.0. The currentrelease, 13.1.0,doesn't include-gcodeviewin its debug options. So it's something new added for 14. My MSYS2/mingw64 installation is using gcc 13.1.0; I assume the ucrt64 version is too. So, basically, to generate codeview debug information, you either need to install a development version of gcc (Possibly having to build it from source) and hope it's in a usable state, or wait for 14.1 to be released and adopted.
Here's a program that doesn't compile on MacOS, butshould: ``` #include <fcntl.h> int main () { open("main.c", O_RDWR | O_RSYNC); } ``` Looking at the provided system man-page, it doesn't mentionO_RSYNC, and it also doesn't mentionO_DSYNCandO_SYNC, but this compiles: ``` #include <fcntl.h> int main () { open("main.c", O_RDWR | O_SYNC | O_DSYNC); } ``` so my question is: what gives? Is this a common practice, for things not to be POSIX compliant and also to have undocumented options? What behavior should I rely on here, and does anyone have any experience with this?
O_RSYNCis flagged with an "SIO" tag defined as [SIO] [Option Start] Synchronized Input and Output [Option End] The functionality described is optional. The functionality described is also an extension to the ISO C standard. POSIX doesn't require the implementation of this feature. Source
Here's a program that doesn't compile on MacOS, butshould: ``` #include <fcntl.h> int main () { open("main.c", O_RDWR | O_RSYNC); } ``` Looking at the provided system man-page, it doesn't mentionO_RSYNC, and it also doesn't mentionO_DSYNCandO_SYNC, but this compiles: ``` #include <fcntl.h> int main () { open("main.c", O_RDWR | O_SYNC | O_DSYNC); } ``` so my question is: what gives? Is this a common practice, for things not to be POSIX compliant and also to have undocumented options? What behavior should I rely on here, and does anyone have any experience with this?
O_RSYNCis flagged with an "SIO" tag defined as [SIO] [Option Start] Synchronized Input and Output [Option End] The functionality described is optional. The functionality described is also an extension to the ISO C standard. POSIX doesn't require the implementation of this feature. Source
I wrote a program using printfs() of "é" or "à" compiling with MinGW 4.9.1, I was usingsetlocale(LC_CTYPE, "fra");to display these characters and it worked well However when I compile the same program with MinGW 11.2 the accents are displayed this way : "é" "Ã" I tried withsetlocale(LC_ALL, "");and it doesn't work either Does anyone have a solution?
On Windows, you must explicitly set utf-8 as opposed to other platforms like Linux: ``` std::setlocale(LC_ALL, ".utf8") ``` Windows assume code pages in its locale configuration unless the program or the user selects it. Doing this activates windows support for utf-8 in the console.
I need to write algorithm, that multiplies numbers from a to b without input (scanf). Like this: ``` a = 2; b = 6; 2 * 3 2 * 4 ... 2 * 6 ``` I have my algorithm: ``` void main() { int dist = 1; int a = 2; int b = 5; for (int i = a; a <= b; a++) { printf("%d", a * a++); } } ``` but it doesn't work correct
This is because you are increasing a (a++) two times in your example above. Also you mixed upaandia little bit. Correct one is: ``` int a = 2; int b = 5; for (int i = a; i <= b; i++) { printf("%d * %d = %d\n", a, i, a * i); } ``` which prints: 2 * 2 = 42 * 3 = 62 * 4 = 82 * 5 = 10
I am on a device with 1 GB of memory and 16 GB of SSD disk space, but I want to use a 15 GB compressed PCAP file to stream IP data over the ethernet port. Obviously, I cannot just decompress the file as I haven't enough disk space for that, and even if I did, the decompression would take too long. Does the gz file format support some form of streaming decompression so that I can stream the file without running out of disk space?
Does the gz file format support some form of streaming decompression so that I can stream the file without running out of disk space? Yes, it is possible to decompress gzip format incrementally. This is in factZlib's normal mode of operation when decompressing gzip. Or for a higher-level approach,thezcatorgunzip -corgzip -dccommanddecompresses a gzipped file to its standard output.
Why does the following code display4-5as4and not-1? ``` #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int fun(int *a, int *b){ *a = *a+*b; *b = *a-*b; } void main(){ int a=4; int b=5; int *p=&a, *q=&b; fun(p,q); printf("%d\t%d",a,b); } ``` The sum comes as 9 (as expected), but why does the difference come as 4?
This assigns the result of*a + *bto*a, so after ``` *a = *a + *b; // 4 + 5 ``` then*ais9, so ``` *b = *a - *b; ``` makes it*b = 9 - 5, which is4. The problem has nothing to do with pointers. You would have the same problem if you did it without: ``` int a = 4; int b = 5; a = a + b; // assign the result of 4 + 5 (9) to a b = a - b; // assign the result of 9 - 5 (4) to b ``` Also note that the program has undefined behavior sincefunis declared to return anintbut it doesn't return anything.
``` FILE* file = fopen(some file) pcap_t* pd = pcap_fopen_offline(file) pcap_close(pd) fclose(file) ``` This code occurs double free error. Could you explain about this happening? My Guess is that pd and file pointers are sharing some datas.
As the documentation says, thepcap_closefunction closes the files associated with thepcap_tstructure passed to it. Closing the file again withfcloseis an error.
the master process starts the processes proc1, proc2, proc3. creating a signalfd for SIGCHLD in non-blocking mode. I kill child processes through your textpkill proc. Then different situations happen, from signalfd it is possible to read either 1 or 2 signals (the second signal reads after entering poll). where is the third signal? I don't understand what to try. no signal coming to fd?
where is the third signal? It's impossible to know from your description alone exactly what is happening, but very likely you're running into the fact that signals of the same type do not queue. For example, only oneSIGCHLDcan be pending for a given process at a time. If a second comes in while one is already pending, then one of the two is dropped.
I had a problem where have to print ASCII values of characters from 1 to 255 so I wrote this code: ``` #include<stdio.h> int main() { char a; while (a<=123) { printf("the ascii value of %c is %d\n",a,a); a++; } return 0; } ``` The code runs fine and prints the ASCII values till I think (a<=130) too but when I put the condition like while(a<=150) or while(a<=255) it keeps executing infinitely. What may be the reason it is happening? I was expecting that all the values will be printed.
Whethercharis signed or unsigned on any given platform is implementation-defined. A signedcharwould overflow ata == 127(which would be undefined behavior), soa <= 150can never become false. a <= 255can never become false regardless of the signedness ofchar. (Assuming 8-bit chars.)
It seems to be more productive, at the end of the header file you include the .c file in the following case ``` #ifndef CHIP8_H #define CHIP8_H //header struct here #include "chip8.c" #endif ``` the header file is included in the chip8.c file and you don't need to add the chip8.c file into the compiler, is it ill advised to do this?. If i include the .h file where i need, it just works.
No, no, a thousand times no. Here's why. Header .h filesdefinethe interface, the API. Source .c filesimplementit. The consumers of header files are other source files that use the stuff implemented in the source file. More recently dreamed-up languages have classes, public and private methods and properties, inheritance, interfaces, and traits, and all that really good interface definition stuff. But C -- old school Kernighan and Ritchie C -- has .h files and .c files for that.
Declaring a function asstaticmakes it only availiable in its file, and compiling a program with-smakes all the global functions and variables in it unnaccessible from outside the app. So if I just compile an app with-s, does it have the same effect as making everything static or is it more complicated than that? To put it in other words, would these two produce the same executable: ``` /*** cc -s main.c ***/ #include <stdio.h> void a(){ printf("Hello world!\n"); } int main(void){ a(); return 0; } ############################### /*** cc main.c ***/ #include <stdio.h> static void a(){ printf("Hello world!\n"); } int main(void){ a(); return 0; } ```
The -s option when compiling does not affect the accessibility of functions and variables from outside the application. -s only strips symbols, so the executable will be a bit smaller.
I know that pthread_cond_signal/pthread_cond_broadcast should be called after changing the condition variable to indicate a condition change, but if they both happen with lock held, does the order matter? For example pthread_mutex_lock(&mutex);pthread_cond_signal(&cond);condition = truepthread_mutex_unlock(&mutex); the waiter's wakeup must happen after step 4(to retrieve the mutex), so the waiter must have seen the update condition variaable
I think you are right. If the code checking this condition is written in a correct way, this should not be a problem. e.g. ``` pthread_mutex_lock(&lock); while(!state) { pthread_cond_wait(&cond, &lock); } pthread_mutex_unlock(&lock); ```
Could you explain how alignment in map file works? I thought that alignment works like that: I have a variable/section that is one byte in size, but due to 4 bytes of alignment it occupies 4 bytes. But according to the map file from the screenshot, "OS_DATA_CORE0_VAR_INIT_PAD" section starts in the address that should be assigned to "OS_DATA_CORE0_VAR_INIT_SEC" section due to the 16 bytes of alignment.
I thought that alignment works like that: I have a variable/section that is one byte in size, but due to 4 bytes of alignment it occupies 4 bytes. It's rather that if you have a section with alignment e. g. 4, this starts at an address which is a multiple of 4, so this alignment introduces a gap between the preceding section and this section unless the preceding section ends at an address divisible by 4.
When using cs50 library,get_stringfunction doesn't work properly. ``` uppercase.c:6:19: error: too few arguments to function 'get_string' string name = get_string("hey? "); ^~~~~~~~~~ In file included from uppercase.c:2:0: c:\mingw\include\cs50.c:78:8: note: declared here string get_string(va_list *args, const char *format, ...) ^~~~~~~~~~ ``` How can I make this work?
The error message suggest that <cs50.c>. The correctusageis to include the header file#include <cs50.h>and link the implementation library-lcs50when you build your program. The documentation says: If, when compiling a program, you see /usr/bin/ld: cannot find -lcs50: Add export LIBRARY_PATH=/usr/local/lib to your .bashrc. You normally specify the library search path with-L/usr/local/libor whatever path you installed the library to.
When using cs50 library,get_stringfunction doesn't work properly. ``` uppercase.c:6:19: error: too few arguments to function 'get_string' string name = get_string("hey? "); ^~~~~~~~~~ In file included from uppercase.c:2:0: c:\mingw\include\cs50.c:78:8: note: declared here string get_string(va_list *args, const char *format, ...) ^~~~~~~~~~ ``` How can I make this work?
The error message suggest that <cs50.c>. The correctusageis to include the header file#include <cs50.h>and link the implementation library-lcs50when you build your program. The documentation says: If, when compiling a program, you see /usr/bin/ld: cannot find -lcs50: Add export LIBRARY_PATH=/usr/local/lib to your .bashrc. You normally specify the library search path with-L/usr/local/libor whatever path you installed the library to.
When inline function gets executed, which memory area they will use Let me give some example int sum(int a,int b) {return a+b; } Where the variables a and b are stored ?
Most likely no memory is used at all. If the arguments ofsum()are in registers at the time of the "call", then they will simply be added and the sum put in another register, or one of those registers if the contents are not needed after that. For example, this: ``` inline int sum(int a, int b) { return a + b; } int main(int argc, char **argv) { (void)argv; int a = argc; int b = a * 5; return sum(a, b); } ``` Compiles to this: ``` _main: ; @main .cfi_startproc ; %bb.0: add w8, w0, w0, lsl #1 lsl w0, w8, #1 ret .cfi_endproc ``` All done in the registers. Nothing stored in memory. (And the optimizer added instead of multiplied.)
For example,the default is "yytext",but I want to rename it to "aatext",how can I do this?
It seems like the Flex manual would be the natural place to look. Google offers several versions ofLexical Analysis with Flex, for various versions of Flex. For example, The manual has a nice table of contents, which lists a chapter "Scanner options", which sounds promising, and a section within named "Code-Level and API Options", which seems like it would be just the thing. And Lo! In that section we can find documented theprefixoption, which can be spelled-PPREFIXor--prefix=PREFIXon the Flex command line, or%option prefix="PREFIX"in the input file, and which changes the default 'yy' prefix used by flex for all globally-visible variable and function names to instead be 'PREFIX'. Do read the rest of the documentation for that option, too.
I am trying to get pipeline topology but when I create it I usegst_pipeline_newwhich returns a GstElement, on the other hand GST_DEBUG_BIN_TO_DOT_FILE expects a GstBinGST_DEBUG_BIN_TO_DOT_FILE
gst_pipeline_new()returns aGstPipeline*, a subclass ofGstBinwhich is a subclass ofGstElement. The reason it returns aGstElement*is just because most people usually callGstElementmethods on it afterwards, and since C doesn't support polymorphism, you have to cast. This brings us to the answer for your question:GstPipelineis just a subclass ofGstBin, so you can just cast the type using usual C casts (e.g.(GstBin *) pipeline) or using the GObject casting macros (which do a runtime type check (e.g.GST_BIN (pipeline))
I'm reading this document about the secret of printf in order to write my own printf and I found the 2nd("%5.0f.", e)withe = 2.718281828printf floating point format and what it producesconfusing, why is there four spaces before the 3 and the decimal point? I thought the output would be 3. with three spaces before the number 3 as the decimal point takes one space itself.
In the format string"%5.0f."there are two parts: a floating point specifier%5.0fand a literal.. The two are not attached in any way. The first part prints 4 spaces followed by the number2, and the second part just prints.independently of the first part.
This is a simple way of sorting an array in ascending order in C. but after sorting when i print the array it comes as 1 5 11 14 1533. Can someone explain me where the 33 comes from since i have not initialized 33 in my array ``` #include<stdio.h> int main() { int arr [6]={11,1,5,125,15,14}; int i, j, k, temp; for (i=0; i<6; i++){ for(j=i+1; j<7; j++){ if (arr[i]>arr[j]){ temp = arr[i]; arr[i] = arr[j]; arr[j]=temp; } } } for (k=0; k<6; k++){ printf("%d ", arr[k]); } } ```
The defined indices of an array declaredint arr[6]are 0 to 5, inclusive. The loopfor(j=i+1; j<7; j++)letsjgo to 6, and the program usesjto index the array. So the program accessesarrout of bounds, and the behavior of the program is not defined by the C standard.
``` #include <stdio.h> int main() { unsigned char c = 'a'; c = c + 3; printf("%c ", c); printf("%zu",sizeof(c)); return 0; } ``` Output:d 1 when integer promotion takes place implicitly in c. then why the size of char is printing 1(in bytes) rather 4(in bytes), since the size should increase to 32bits right? Iam thinking that the output shall be: d 4
It's correct that the calculation ofc + 3involves integer promotion, i.e. the type of the result isint. However, when you store that result in yourcharvariable usingc = will be converted back to acharagain. The assignment will not (can not) change the size of your variable. Try this code: ``` char c = 'a'; printf("%zu\n", sizeof(c)); printf("%zu\n", sizeof(c + 3)); c = c + 3; printf("%zu\n", sizeof(c)); ``` On my system it gives: ``` 1 4 1 ```
Looking through some old code that is not mine, I ran into this line: ``` if (ungetc(getc(in), in) != EOF) ``` Whereinis a file pointer. I'm unfamiliar with these functions and their use. Am I interpreting this correctly as if (the end of the file hasnotyet been reached) ?
It "peeks" at the streaminlooking for EOF, without removing the character from the buffer. Or rather it grabs a character then puts it back. Am I interpreting this correctly as if (the end of the file has not yet been reached) ? Yes.
I have 32 byte char buffer when printed in hexadecimal using function ``` void print_buffer_in_hex(const char* buffer, size_t size) { for (int i = 0; i < size; i++) { printf("%02x", (unsigned char)buffer[i]); } printf("\n"); } ``` it is shown as below ``` 5ca6d40011278e3ff84fd94dd80e370cd90f2a304e9cefb946082ab82ff0dbde ``` how can I convert above data to string of 64 bytes (i.e., character array of 64 byte buffer) instead of printing to console. Thanks for your inputs
As a comment mentioned, you can usesprintf(3), which writes the usual printf-formatted output to a buffer: ``` char buf[65] = {0}; for (int i = 0; i < size; i++) { sprintf(buf + i*2, "%02x", (unsigned char)buffer[i]); } buf[64] = 0; ``` Thei*2stands for the offset of the buffer you want to write to.
Consider this array: ``` unsigned char* array[] = { (unsigned char[5]){}, (unsigned char[5]){} }; ``` Doesarray[0]andarray[1]still point to a valid memory even after the complete definition ofarray? Meaning, afterwards I am allowed to do for examplememcpy(array + 1, "\x01\x02\x03\x04\x05", 5);
If that declaration appears outside of any function, thenarrayand the compound literals have static storage duration, so they exist for the duration of program execution, and you can use them at any point in the program. If the declaration appears inside of a function, thenarrayand the compound literals have automatic storage duration associated with the enclosing block. Using the memory of the compound literals is defined as long as usingarrayis defined. Note that{}is not a strictly conforming initializer; you should give at least one value, as in{0}. (GCC and other compilers may accept{}.)
I have a bunch of test cases I want to divide in 2 source files. These tests use fake functions created by FFF. When I try to include my fake headers in the 2 different source files, I get linker errors:multiple definition of ... first defined here. They are first defined in the source file that already included these mocks. I need all mocks to be visible in both files. How can I include them?
I have found itin this section, in the FFF README file. Basically, using theDECLARE_FAKE_*andDEFINE_FAKE_*macros
I have two threads working on the same socket, one for read and the other for write. The socket is non-blocking and uses epoll. When write encounters error, it will close the socket. My question is, at this point will the read thread return from the epoll wait with error?
This behavior is platform-specific, so take this with a grain of salt. Generally, the answer isusuallyyes, but itmaybe no, too. Closing a socket prevents any further reading and writing on it, so if the writing thread decides to close the socket, the reading thread can't read from the same socket anymore. This willusuallycause a read error. However, I have been informed of cases here and there where this is not always true. So, best not to rely on this behavior, if you can help it.
I am talking about the method, url, and http-version. I want a struct that looks like this: ``` struct http_rq { char method[?]; char url[?]; char version[?]; } ``` But I don't know how big each value "can" be.
Reading longest method isCONNECTandOPTIONSwhich is 7 bytes. I do not see any limit onurl, so I believe infinity. AlthoughHTTP's version number consists of two decimal digits separated by a "."I do not see any limitation on the digits. So I would say that version is also a potentially infinite string. Overall, I would make method anenum, makeurldynamically allocated string and I would replaceversionby two integers.
I have code :get_transaltion(&(arr[1/2]) ) The array is of structures that each contain an array of 3 places, which places does the function accept? I edited the array in the first place in the structure with an array of 3 places and I didn't get what I edited ``` struct vector { float data[3]; }; arr[1 / 2u].data[0] = 1 + 0.1; arr[1 / 2u].data[1] = 1 + 0.2; arr[1 / 2u].data[2] = 1 + 0.3; ```
The result of the/operator is the quotient from the division of the first operand by the second. Here: ``` arr[1 / 2u].data[0] = 1 + 0.1; ``` 1 / 2uevaluates to 0. So it's equivalent to writing: ``` arr[0].data[0] = 1 + 0.1; ```
I am trying to initialize a bitmap to all bits on. My idea was to initialize an array of the buffer size and then usememcpy; however: ``` #include <stdio.h> #define SIZE 5 int main () { int i[SIZE] = { ~0 }; for (int j = 0 ; j < SIZE ; j++) { printf("%d\n", i[j]); } return 0; } ``` results in: ``` -1 0 0 0 0 ``` my expectation was that I would see all-1. Why does this not work, and how can I accomplish my goal?
This: ``` int i[SIZE] = { ~0 }; ``` Explicitly initializes only the first element of the array to~0. The rest are implicitly set to 0. If you want all bits to be set, you need to usememset: ``` memset(i, ~0, sizeof i); ```
I have this code in c and it's working properly. ``` char* str2 = string + (str_len - end_len); ``` str_lenandend_lenare two integers andstringis another char pointer string. I don't understand why I am able to add an integer to a character pointer string. Shouldn't this give a type error?
str2will be assigned the pointer value ofstring+(str_len - end_len). Ifoffset = str_len - end_len< 0 oroffset> size ofstring(array) + 1 then it's undefined behavior (note:sizeof "hello "counts the trailing '\0' for a string hence the-1). Here's an example: ``` #include <stdio.h> int main() { char string[] = "hello world"; char *str2 = string + (sizeof "hello " - 1); printf("%s\n", str2); } ``` prints: ``` world ```
Reading through, I noticed that the result of fread() is compared with==. I saw people use<before, so the obvious question presented itself of whether the error value can be MORE than the number of items that were asked of the function? The man page for fread/fwrite says: If an error occurs, or the end of the file is reached, the return value is a short item count (or zero). This is a strong implication that it might be true, but I would prefer a more official confirmation if possible, or at least a confirmation that what the man page says can be taken seriously.
§ ¶3 of the ISO C11 standardstates the following: The fread function returns the number of elements successfully read, which may be less than nmemb if a read error or end-of-file is encountered. Therefore, the return value will never exceed the value of thenmembfunction argument (which is the third function argument).
I am working on a Program that needs to manually issue a USB packet to a specific device. Since I need a handle for the device to send a control code to the driver, I need to find the Device Path using only the devices Vendor and Product ID. Thus far I have found the SetupDi* family of functions, but they don't appear to allow me to narrow it down without further information being available, like the Device Instance ID.
As the code inthe threadshowed, theDevicePathconsists of Vendor ID and Product ID. You can grab the Vendor ID and Product ID of the device based on the device path and compare them with specified IDs.
I have the following code snippet in c: ``` for (int a = 1; a < thiz->fft_length; a++) { *pPL += fL->real; *pPR += fR->real; pPL++; pPR++; fL++; fR++; if (pPL - thiz->oBufL > thiz->bufLen - 1) { /*NOT EVALUATED*/ pPL -= thiz->bufLen; } if (pPR - thiz->oBufR > thiz->bufLen - 1) { /*NOT EVALUATED*/ pPR -= thiz->bufLen; } } ``` The lines marked/*NOT EVALUATED*/are never evaluated, even though QuickWatch of the exact expressions of the if clauses e.g. (pPL - thiz->oBufL > thiz->bufLen - 1) show as TRUE. I can only think that the code may not be up to date but have checked that the latest compile was successful so there should be no discrepancy.
As it turns out, one side of the comparison was returning a negative number, but this got wrapped around into a huge positive number in Watch but not the actual code, resulting in the discrepancy.
Should I install gcc or other c compiler after installing nim to compile my code to an executable file or it contains? If it contains, which c compiler it uses? gcc, tcc, clang etc. Don't get me wrong, I dont want to convert my nim code to c. I just want to know what compiler it uses after translating nim to c to make mashin code. I don't want to install it before I'm getting sure, how it really works.
Fromthe install on Linux/Unix/macOS page: The Nim compilerneeds a C compilerin order to compile software.You must install this separatelyand ensure that it is in yourPATH. [Emphasis mine] So yes you need to install a C compiler for it to work. There's no mention aboutwhichcompiler to install or use, so it probably uses the common aliasccto build the C source. You can install the default compiler for your platform and it should work. The Windows download pagerecommends MinGW, which is GCC.
I don't get it, how is the 'connection' made if there is no .h file. Here is the code: file main.c: ``` void Run( void ) ; int main(void) { Run() ; } ``` file: run.cpp: ``` static MyClass gMyClassInstance; extern "C" { void Run( void ) { gMyClassInstance->Run(); } } ``` Searched forRunin the entire project, never appears again and not in any .h file. How does it do it?
.hfiles are used to avoid duplicating the declarations from.c/.cppfile to.c/.cppfile (declarationsare required by the compiler when the functions are notdefinedlocally). In your example, there is a single declarationvoid Run( void );, directly inmain.crather than in a separate.h, and this is enough for the compiler. The connection with theRunfunction defined inrun.cppwill be made by the linker (as an entry point named_Run). Header files are by no means mandated in C/C++ programming.
I was experimenting with some ~2005 C code (using OpenSSL 0.9.8, I think) and I triedmake-ing it with OpenSSL 3.0.2 on Ubuntu 22.04. Minimum example: ``` #include <openssl/bn.h> struct fraction { BIGNUM numerator; BIGNUM denominator; } ``` Expected: everything builds, just as intended. Actual: complier complains about incomplete type declaration for both fields. Why does this happen? Is this not a valid declaration? Or is it something else?
Later versions of OpenSSL made several types opaque, includingBIGNUM, which means you can't instantiate them directly in user code. TheBIGNUMtype in particular became an opaque type starting with version 1.1.0. You would instead need to use pointers: ``` struct fraction { BIGNUM *numerator; BIGNUM *denominator; }; ``` And use the appropriate functions to create and destroy them, as well as use the relevant accessor functions to access the members.
I have a kernel module(in c), which is working and would like to: accept input from a user for a process numbermark that process as SIGNAL_UNKILLABLE as inthe linux source code #define SIGNAL_UNKILLABLE 0x00000040 /* for init: ignore fatal signals */ I created a kernel module in c and searched online, but no working results.
How can I flag a process from a kernel module? Looking at, should be super normally. ``` struct task_struct *t = find_task_by_vpid(thepid); t->signal->flags |= SIGNAL_UNKILLABLE; ```
I'm trying to work throughthis C coding exercise, but I want to do so in Zig. In the exercise they#import <nmmintrin.h>(@~18:15) to use__builtin_popcount. From a brief search it looks likethis is a gcc-specific header file? Not sure what compiler they're using, but IIUC Zig compiles C code via clang/LLVM != gcc/GNU, right? =_= How do I use this header from Zig? Are gcc headers supported?
You wouldn't, as some comments mention these refer to GCC builtins which aren't available in Zig. Zig does expose most of these types of instructions via its own builtins though, so for instance you have@popCount,@ctz,@clz... and vector operations via the builtin@Vectortype. If for some reason you doneedto use C builtins instead of the equivalents from Zig, you can always write the code using that in C and call that code from Zig (although you shouldn't have to, if a useful instruction is missing you can raise that as an issue on the compiler).
i had try to print the following pattern but i only able to decrease the letters from the one side but not from both the side Please someone help me with this : to print this pattern this is the code that i use: ``` #include <stdio.h> #include <string.h> int main() { char str[] = "Programming"; int len = strlen(str); for (int i = 0; i < len; i++) { for (int j = i; j<len; j++) { printf("%c", str[j]); } printf("\n"); } return 0; } ```
KISS Principlesolutions have the advantage of both running fast and being easy to read all at once: ``` #include <stdio.h> #include <string.h> int main (void) { char str[] = "Programming"; int len = strlen(str); for (int i = 0; str[i]!='\0'; i++) { puts(&str[i]); str[len-i-1] = '\0'; } } ``` Make a copy ofstrfirst in case the data needs to be preserved.
I created a white image with this code: ``` #include "stb_image/stb_image.h" #include "stb_image/stb_image_write.h" int main(void){ int width = 1440; int height = 1080; int j, l; float *img_slopes = (float *)malloc(width * height * sizeof(float)); for (l = 0; l < width; l++) { for (j = 0; j < height; j++) { *(img_slopes + j * width + l) = 255; } } stbi_write_bmp("answer_blank.bmp", width, height, 1, img_slopes); } ``` Those cycles should scroll through each and every pixel. But the output is: png screen-capture of the answer_blank.bmp Why is that? Why do I have black columns? What exactly is happening here? If it's not clear enough from the print-screen, every other column is black.
As user @Gerhadh kindlymentioned, the .bmp don't usefloatvales. It should be anunsigned charmatrix instead.
When Immapa block of memory, the returned pointer might be something like2607194112or3614339072(both actual values I've gotten). Why are these values seemingly so random? It's all virtual anyway, so why not just give me address4096to start us off? I suppose this question extends also to something likemalloc, but that will use one of these under the hood anyways.
You're observingAddress Space Layout Randomization. In order to prevent an attacker from reliably jumping to, for example, a particular exploited function in memory, ASLR randomly arranges the address space positions of key data areas of a process

This is a collection of ~40k QA's in C Language from StackOverflow. The data has been initially cleaned, and each response is with Accepted Answer. All data is <1000 in length.

The questions and answers were organized into a one-line format. A sample format is shown below:

    "question": "```\nFILE* file = fopen(some file)\n\npcap_t* pd = pcap_fopen_offline(file)\n\npcap_close(pd)\n\nfclose(file)\n```\n\nThis code occurs double free error.\n\nCould you explain about this happening?\n\nMy Guess is that pd and file pointers are sharing some datas.\n",
    "answer": "As the documentation says, thepcap_closefunction closes the files associated with thepcap_tstructure passed to it. Closing the file again withfcloseis an error.\n"
Downloads last month
Edit dataset card