question
stringlengths
25
894
answer
stringlengths
4
863
I currently have a queue struct defined as ``` typedef struct { int size; char** data; unsigned count; unsigned head; } queue; ``` It is initialized with ``` Q->size = DEFAULTSIZE; Q->data = malloc(sizeof(char*) * QSIZE); Q->count = 0; Q->head = 0; ``` Whenever I enqueue something, ``` //item is a char* Q->data[i] = malloc(sizeof(char) * item_length); Q->data[i] = item; //If I was to do free(Q->data[i]); at this point, I would get an error as stated below ``` The issue is that whenever I dequeue, and want to freeQ->data[i]I get a WRITE error on the line that I am freeing on. Although usingprintf("%s", Q->data[i]);seems to work fine telling me that I have access to that item. Any advice?
What you probably mean is this: ``` Q->data[i] = malloc(strlen(item) + 1); strcpy(Q->data[i], item); ```
I want to pass the file pointer as an argument to view function. And then I want to get the output the data on file from the view function. But every time telling me file not found. ``` #include<stdio.h> void view(FILE *file){ char c; file=fopen(file,"r"); if(file==NULL){ printf("file not found"); } else{ while(!feof(file)){ c=fgetc(file); printf("%c",c); } fclose(file); } } int main(){ FILE *file; file=fopen("hello.txt","w"); char s[]="hello world"; fprintf(file,"%s",s); fclose(file); printf("Enter 1 to read file"); int n; scanf("%d",&n); if(n==1) view(file); return 0; } ```
Your error is here: ``` file=fopen(file,"r"); ``` Use something like this: ``` file=fopen("file name","r"); ```
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.Closed2 years ago.Improve this question Does Memory allocation in C is a machine dependent? I want my program to be transferred from a UNIX system to another system without any problem.
As @mediocrevegetable1 said in the comments, as long as you use functions from the standard library, it should work. (But just make sure that you used an ANSI C compiler before, and to use an ANSI C compiler when compiling for another system. You can seeHerea list of ANSI C compilers.)
I am checking the existence of a file in a function. ``` int main(int argc, char* argv[]) { foo(argc, argv); // File exists // Do something } void foo(int argc, char** argv) { int f = open(argv[1], O_RDONLY); if(f == -1) { exit(1); } } ``` Does the file go out of scope or closes when the function call returns or will it stay open and affect the performance as I am writing a c code to copy the contents of one file to another with system calls.
The file doesn't close since there's no code to close it. The file doesn't go out of scope because only a variable or object can go out of scope. However, whenfgoes out of scope, the descriptor (or handle) used to access the file goes out of scope leaving no way to access or close it.
This question already has answers here:Printf variable number of decimals in float(3 answers)Closed2 years ago. as in the question, how do I round the float to a user-specified number of decimal points? My current code only prints out the float to 2 decimal places. Also, is there a built-in function for such a purpose? ``` #include <stdio.h> int main() { float x = 1.2345; int dp; printf("The float is: %f. How many decimal points to round to? ", x); scanf("%d", &dp); printf("Number: %.2f", x); } ```
You can put the*character in place of the precision, in which case the next argument will specify the precision. ``` printf("Number: %.*f", dp, x); ```
``` #include <stdio.h> #include <string.h> void printArray(char* p, int len) { for (p; p < p + len; p++) { printf("%c", *p); } printf("\n"); } int main(void) { char* msg = "hi jyegq meet me at 2 :)"; printArray(msg, strlen(msg)); getchar(); return 0; } ``` I've tried to switch some things but I can't understand the problem I need to fix this code and I think it's with the print of the pointer and I don't know how to print him with no problems
You could do this ``` #include <stdio.h> #include <string.h> void printArray(char* p, int len) { ; for (int i = 0; i < len; i++) { printf("%c", *(p++)); } printf("\n"); } int main(void) { char* msg = "hi jyegq meet me at 2 :)"; printArray(msg, strlen(msg)); getchar(); return 0; } ``` Use a counter so you wouldn't go somewhere you shouldn't in memory.
For example,the default alignment of a union is following: ``` union{ uint32_t v4; __uint128_t v6; }ip; //in memory //aaaa //bbbbbbbbbbbbbbbb ``` But I want to have a union right aligned: ``` // aaaa //bbbbbbbbbbbbbbbb ``` Is it possible to achieve this in C?
You can use a C11 anonymous struct for this. ``` union { #pragma pack(1) struct { char padding_[sizeof(__uint128_t) - sizeof(uint32_t)]; uint32_t v4; }; #pragma pack(0) __uint128_t v6; } ip; // usage ip.v4 = 0x7F000000; ```
I am attempting to compile code using the <gtk/gtk.h> header file using gcc. Whenever I do so I get the following error: gtk.c:3:10: fatal error: gtk/gtk.h: No such file or directory3 | #include <gtk/gtk.h> ^~~~~~~~~~~ I have looked in /usr/include/ and found gtk-1.2 gtk-2.0 and gtk-3.0 all of which have the header files within them necessary to compile the program I'm unsure why GCC can't find those files and how to reroute gcc to find the necessary header files.
GCC doesn't know which version you want to use. GTK recommends using pkg-config to compile programs. For example, for GTK 3 use: ``` gcc `pkg-config --cflags gtk+-3.0` yourprogram.c -o yourprogram `pkg-config --libs gtk+-3.0` ``` You could also specify the correct include and library paths yourself.
``` void Setup() { gameover = false; dir = STOP; x = width / 2; y = height / 2; fruitX = rand() % width; //display fruit in a random place fruitY = rand() % height; score = 0; } ```
Please use#include <stdlib.h>at the top of c code.
Take this snippet of a compound initializer in a function call ``` foo_make_person(ctx, &(foo_person_desc){ .name = "Bob", .age = 50, }); ``` How can I get clang-format to format this code exactly like that? Everything I tried always looks wrong. Such as ``` foo_make_person( ctx, &(foo_person_desc){ .name = "Bob", .age = 50, }); ``` or this ``` foo_make_person(ctx, &(foo_person_desc){ .name = "Bob", .age = 50, }); ``` or this ``` foo_make_person(ctx, &(foo_person_desc){ .name = "Bob", .age = 50, }); ```
After further research, I concluded that clang-format, as of the current version, just cannot do this kind of formatting.
Basically I am looking for a way to force a specific relative alignment i.e I want to gurantee that for some other valuems.tm>nalignment_of(foo) % 2^m == 2^ni.e: ``` .align 2^m; .global foo; .type foo, @function foo: // 2^n nops // actual function start ``` but hopefully without having entry have to go through a bunch of a nops. I need it to work with foo being linked with C code.
You can always add padding before the start of the function. The perhaps easiest way is to do something like this: ``` .p2align m .byte 0xcc .p2align n, 0xcc foo: ... ``` Here, I've explicitly padded the code with0xccbytes. You can use whatever padding you like or leave out the0xccto getnopinstructions of various lengths
Basically I am looking for a way to force a specific relative alignment i.e I want to gurantee that for some other valuems.tm>nalignment_of(foo) % 2^m == 2^ni.e: ``` .align 2^m; .global foo; .type foo, @function foo: // 2^n nops // actual function start ``` but hopefully without having entry have to go through a bunch of a nops. I need it to work with foo being linked with C code.
You can always add padding before the start of the function. The perhaps easiest way is to do something like this: ``` .p2align m .byte 0xcc .p2align n, 0xcc foo: ... ``` Here, I've explicitly padded the code with0xccbytes. You can use whatever padding you like or leave out the0xccto getnopinstructions of various lengths
Say I had a char* ptr with address of 0x7fffaf6aa87f, How can I round that down to a multiple of 8 so that it would be 0x7fffaf6aa878? or if it was 0x7fffaf6aa875, it would get rounded down to 0x7fffaf6aa870.
&~7 ``` #include <stdio.h> #include <stdint.h> int main(void) { uintptr_t x = 0x7fffaf6aa87f; uintptr_t y = x&~7; printf("%p\n", y); x = 0x7fffaf6aa875; y = x&~7; printf("%p\n", y); return 0; } ``` Result: ``` Success #stdin #stdout 0s 5368KB 0x7fffaf6aa878 0x7fffaf6aa870 ```
I was working with some code where I have to debug and fix the bugs. The example I am demonstrating is just an example so I understand what is wrong here. From my understanding when I check the value of if(check(input_num)) it should print 0 when it is even and 1 when it is odd. However, it is returning 1 wheh input is even and 0 when odd ``` #include <stdio.h> int check(int num){ if (num%2 == 0){ return 0; }else{ return 1;} } int main(){ int a; cin>>a; if(check(a)){ return 0; }else{ return 1;} return 0;} ```
In C,0is consideredfalseand all non-zero values are consideredtrue. So, in yourmainfunction, theifstatement evaluates totruewhen the function returns1(a non-zero value) and tofalsewhen it returns0. So inmainyou're returning0whencheckreturned1and vice-versa.
In this term, I have Microprocessors lectures and we're working on ARM Development with C/C++ and Assembly. For a while I've been looking for an alternative for Keil uVision which is compatible with Linux Distributions (now using Arch) and able to assemble ARM and flash, but could not find anything. The most related platform was Eclipse but it does not look supports ARM Assembly and nothing that I read about flashing to STM32. I don't want to work on Windows for ARM Development, is there any way to assemble ARM and flash it?
Very simple. Install STM32CubeIDE for linux and nucleotides board with your preferred STM32 uC. Follow the tutorials online
Is there way to get the autocomplete functions from OpenMp for 'c' files inside VSCode. I'm currently using ``` #include <omp.h> ``` But this shows a red-underline with the error that imports are not found. Using the-fopenmpwithgcccompiles my executable, by the way.
To get auto-completions from any Header File: You need to its path to option"C_Cpp.default.includePath"of the C/C++ extension on VScode.(This would only work for the microsoft extension) You could search for header using:find /usr -name omp.hand then add the appropriate path inside yourSettings.json ``` "C_Cpp.default.includePath": [ "/usr/lib/gcc/x86_64-linux-gnu/7/include/", ], ```
I am building commands withsnprintf()that i want to execute withsystem(). I noticed that the last character is missing when i use%sat the end of the format string but when i am adding an extra space after the%sit works as i would expect. Why does this happen? I think i am missing something. I appreciate your help! Here is an minimal example: ``` #define INTERFACE "can0" int size; char *command = NULL; size = snprintf(command, 0, "/sbin/ifdown %s", INTERFACE); command = malloc(size); snprintf(command, size, "/sbin/ifdown %s", INTERFACE); ```
snprintfreturns the number of characters printednot including the null terminator. Therefore when you pass that size back tosnprintfit figures out that your buffer is one char short. Fix it as follows: ``` size = snprintf(command, 0, "/sbin/ifdown %s", INTERFACE); command = malloc(size+1); snprintf(command, size+1, "/sbin/ifdown %s", INTERFACE); ```
The C standard library includes a method, strerror_r (https://linux.die.net/man/3/strerror_r). Depending on the "feature test macros" defined at compilation time, and compiling vs the GNU standard headers, one of two definitions gets included: int strerror_r(int errnum, charbuf, size_t buflen); /XSI-compliant */char *strerror_r(int errnum, charbuf, size_t buflen); /GNU-specific */The XSI-compliant version of strerror_r() is provided if: (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE Otherwise, the GNU-specific version is provided. Assuming I'm dynamically linking my application vs. the standard library, how does the linker correctly link vs. the proper definition of the function?
One of them is actually called__xpg_strerror_rand is redirected to be used asstrerror_rif needed, see:https://code.woboq.org/userspace/glibc/string/string.h.html#409
let's imagine we have the following code snippet ``` // myfile.c #include myfile.h static int global_static_value; bool check_it(int value) { if (global_static_value== value) { return true; } else { return false } } void set_value(int value) { global_static_value = value; } // myfile.h bool check_it(int value) void set_value(int value) ``` How to write google test for functionbool check_it(int value)in order to testtrueandfalsereturn value? PS: It is not allowed to#include myfile.cinto google test
``` TEST_F(MyTestClass, MyTest) { set_value(1); EXPECT_FALSE(check_it(2)); EXPECT_TRUE(check_it(1)); } ```
I have a multi-threaded C process running under Linux. Occasionally, i.e.: few times a month, one of the threads hangs (it does not reach the sleep which is placed at the end of each thread). How can I debug it? Is there a way to know what part of the code is executing when the thread gets stuck?
On Linux you can kill it withkill -11and then look at thecoredump. You can alsoattach a debuggerand see what it's currently doing. You can also add logging to see what it is doing.
I've a problem here . When I compiled a .exe file, the default icon of the application will be the windows console icon(like cmd.exe one). Is there any method I can change the icon to my custom icon?? I am using vscode and MinGW C compiler. Thank You!
You have to add a resource file to your project and define an icon there. The first icon will be used as the application icon by Explorer. The icons are sorted by their order and alphabetically, so you should give it a name that ensures that it is the first one. ``` AA_MYAPPICON ICON "sample.ico" ```
I tried to ran this code : ``` printf("Enter a character."); printf("\n"); do { ch = getch(); system("cls"); putchar(ch); } while(ch != '.'); ``` The above code works fine onCodeblocksbut it is not working onEclipseIDE. In fact theprintfstatement beforedo whileloop is not working, but if I disabledo whilestatement the printf statement working fine on eclipse. Could you explain why is this happening ?
Maybe try this? ``` printf("Enter a character.\n"); fflush(stdout); do { ch = getch(); system("cls"); putchar(ch); } while(ch != '.'); ``` I think it's because your output buffer (printf) is not flushed.
``` #include <stdio.h> int main() { char str[] = "[email protected], 22:44:45"; char user[45], email[45]; int h, m, s; sscanf(str, "%44s@%44s, %d:%d:%d", user, email, &h, &m, &s); printf("User: %s | Email: %s | Hour: %d | Minutes: %d | Seconds: %d\n", user, email, h, m, s); return 0; } ``` Output:User: [email protected], | Email: garbage | Hour: garbage | Minutes: garbage | Seconds: garbageWhy is it storing everything up to , into user?
%44s@doesn't stop reading the string when it gets to the@character. It means to read a string until whitespace, up to 44 characters. Then it needs to read a@character after that in order to continue parsing the rest of the string. To read characters up to@, use%44[^@]. Then follow this with@to skip over that character before extracting the next string. ``` sscanf(str, "%44[^@]@%44[^,], %d:%d:%d", user, email, &h, &m, &s); ```
I tried to ran this code : ``` printf("Enter a character."); printf("\n"); do { ch = getch(); system("cls"); putchar(ch); } while(ch != '.'); ``` The above code works fine onCodeblocksbut it is not working onEclipseIDE. In fact theprintfstatement beforedo whileloop is not working, but if I disabledo whilestatement the printf statement working fine on eclipse. Could you explain why is this happening ?
Maybe try this? ``` printf("Enter a character.\n"); fflush(stdout); do { ch = getch(); system("cls"); putchar(ch); } while(ch != '.'); ``` I think it's because your output buffer (printf) is not flushed.
``` #include <stdio.h> int main() { char str[] = "[email protected], 22:44:45"; char user[45], email[45]; int h, m, s; sscanf(str, "%44s@%44s, %d:%d:%d", user, email, &h, &m, &s); printf("User: %s | Email: %s | Hour: %d | Minutes: %d | Seconds: %d\n", user, email, h, m, s); return 0; } ``` Output:User: [email protected], | Email: garbage | Hour: garbage | Minutes: garbage | Seconds: garbageWhy is it storing everything up to , into user?
%44s@doesn't stop reading the string when it gets to the@character. It means to read a string until whitespace, up to 44 characters. Then it needs to read a@character after that in order to continue parsing the rest of the string. To read characters up to@, use%44[^@]. Then follow this with@to skip over that character before extracting the next string. ``` sscanf(str, "%44[^@]@%44[^,], %d:%d:%d", user, email, &h, &m, &s); ```
I need to get information about running processing Windows. What can I write to make the program give a list like this: working applications: Opera, Teamspeak. It's a little bit like task manager in Windows.
Get a list of processes withEnumProcesses(), which you can then iterate to get information on the individual processes using theProcess APIfunctions such asGetModuleBaseName()as described in the example athttps://learn.microsoft.com/en-us/windows/win32/psapi/enumerating-all-processes
So my task is to create a function that essentially performs the & operation, but only using ~ and |. So for example if my function is called binaryAnd, binaryAnd(6,5) should return 4. This is my function now: ``` int binaryAnd(int x, int y){ int result=~x|~y; return result; } ``` the logic is that taking the complement of the 2 numbers then doing | on them should return the same result as just doing &. But when I put 6 and 5 into this function it returns -7 instead of 4. Why is this? And how can I fix it?
Use theDe Morgan's laws ``` NOT A OR NOT B = NOT (A AND B) ``` This gives ``` NOT (NOT A OR NOT B) = NOT (NOT (A AND B)) = A AND B ``` You can change the return statement to this : ``` return ~result; ```
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 years ago.Improve this question I want to enter a string and delete everything before first "space". Here's an example: Before Hello world After world
To cover corner cases you need to do some checks. It will return NULL if the pointer passed is NULL or the character was not found in the string. ``` char *getstrafter(const char *str, char c) { if(str) { while(*str) { if(*str == c) break; } } return (char *)((str && !*str) ? NULL : str + 1); } char *getstrafter1(const char *str, char c) { if(str) { str = strchr(str, c); if(str) str++; } return str; } ```
I was looking for some alternative tosystem("cls")that works on MacOS and I found this: ``` printf("\e[1;1H\e[2J"); ``` However I do not know what this is doing. Post where I found this
\eis escape and what that printf() line is telling the terminal to move the cursor to line 1 column 1 (\e[1;1H) and to move all the text currently in the terminal to the scrollback buffer (\e[2J).These are ANSI escape codes and here's some resources:https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797https://bluesock.org/~willkg/dev/ansi.htmlhttps://en.wikipedia.org/wiki/ANSI_escape_code(suggested bytadman)Edit: I also recommend the use of\e[H\e[2J\e[3Jas that is what cls/clear prints. This tells the terminal to move the cursor to the top left corner (\e[H), clear the screen (\e[2J), and clear the scrollback buffer (\e[3J).
I was looking for some alternative tosystem("cls")that works on MacOS and I found this: ``` printf("\e[1;1H\e[2J"); ``` However I do not know what this is doing. Post where I found this
\eis escape and what that printf() line is telling the terminal to move the cursor to line 1 column 1 (\e[1;1H) and to move all the text currently in the terminal to the scrollback buffer (\e[2J).These are ANSI escape codes and here's some resources:https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797https://bluesock.org/~willkg/dev/ansi.htmlhttps://en.wikipedia.org/wiki/ANSI_escape_code(suggested bytadman)Edit: I also recommend the use of\e[H\e[2J\e[3Jas that is what cls/clear prints. This tells the terminal to move the cursor to the top left corner (\e[H), clear the screen (\e[2J), and clear the scrollback buffer (\e[3J).
Consider the line<type> array[SIZE_OF_ARRAY];. Later I need to use the size of an element of this array (ie for afwrite). However I might change the<type>in future, so can't have a fixed size. The solution I found was to usesizeof(array[0]). While it works for my case, it doesn't feel very pretty, and it would run into problems if the array could be empty. Is there a better alternative?
if the array could be empty. Is there a better alternative? Array may not be empty. It can be uninitialized. Nevertheless this expression ``` sizeof(array[0]) ``` is in any case valid because the operand is unevaluated expression in the sense that there is no access to the memory (though the expression itself can be evaluated at run time ifarray[0]is in turn a variable length array). An alternative expression can look like ``` sizeof( *array ) ``` You may use either expression with the same effect.
If we cross compile for arm platform, should we link the library files which compatible for the platform or we can use host compatible library files? Like the below example, if we do cross compilation for arm platform, then the curl library we are linking also should be the cross compiled one or our host compatible libraries? arm-v5te-linux-gnueabi-gcc -o main main.c -L/usr/local/curl
... then the curl library we are linking also should be the cross compiled one ... ? Yes. It should be the cross compiled one, not the host one.
We have the variablea, that is the typechar*, that storeschars in an array. How are*(a + 2)anda[1]related? a[1]points to the second element in the array and*(a + 2)points to the second element following the element pointed at to bya. So would the values of these two be the same?
These arenotthe same. The syntaxE1[E2]is exactly equivalent to*((E1) + (E2)). So*(a + 2)is the same asa[2]. It should now be clear that this is not the same asa[1].
We have the variablea, that is the typechar*, that storeschars in an array. How are*(a + 2)anda[1]related? a[1]points to the second element in the array and*(a + 2)points to the second element following the element pointed at to bya. So would the values of these two be the same?
These arenotthe same. The syntaxE1[E2]is exactly equivalent to*((E1) + (E2)). So*(a + 2)is the same asa[2]. It should now be clear that this is not the same asa[1].
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed2 years ago. Why does ``` int a, b = 10; b = b++; printf ("%d", b); ``` output 10 while ``` int a, b = 10; a = b++; printf ("%d", b); ``` outputs 11 how does this work? Why doesn't 'b' increment in first case?
b++ performs assignment with not-incremented value while ++b would do assignment with the incremented value. You only need b++; in your code without assignment to increment. As someone also pointed out b = b++; and b = ++b; are not good segments of code and you are at the mercy of the compiler.
I get anerror 139and asegmentation faultwhile trying to run, I'm a little baffled since I'm not accessing or creating any files or even getting input! I'm simply printing three arrays in order. ``` #include<stdio.h> int main(){ int i,x; //set the values of the names char nmbr[3][8]={ "Andrés", "Manuel", "Peter"}; //print characters of the name 1 by 1 for(i=0;i<3;i++){ while(nmbr[i][x]!='\0'){ printf("%c",nmbr[i][x]); x++; } putchar('\n'); } return 0; } ```
xis not initialized which is UB ``` for(i=0;i<3;i++){ x = 0; while(nmbr[i][x]!='\0'){ printf("%c",nmbr[i][x]); x++; } putchar('\n'); } ```
I want to do what I stated in the question. Is this possible? For example: ``` char number=5; char number_two=number*3; char x=number_two/15; ``` Can I do the arithmetic above?And if the answer to all of these is yes, would a char variable have a minimum value of 0 and a maximum value of 255? THANKS!...
Thechartype is an integer type, likeshort,int, andlong. It is implementation-defined whether it is signed or unsigned. If it is signed, it must support a range from −127 to +127, inclusive. If it is unsigned, it must support a range from 0 to 255, inclusive. (So a common range it must support whether it is signed or not is 0 to 127.) If you want to guarantee a range of 0 to 255, you should useunsigned char. (A C implementation may also provide larger ranges forcharandunsigned char.)
``` #include <stdio.h> void main() { int a = 11, b = 5; if(a == 7 || 10){ printf("True"); } else printf("False"); } ``` This is my problem, i saw it in a question and was asked what the output would be. i put false but the answer was true, im trying to understand why because a is not equal to any of them and the condition for it to be true is that a be equal to at least one of them
The expression in the if statement ``` if(a == 7 || 10){ ``` is equivalent to ``` if( ( a == 7 ) || ( 10 ) ){ ``` As10is not equal to0then the second operand of the logical OR operator||always evaluates to the logical true. So the whole expression used in the if statement has a result of the logical true. In fact asais not equal to7(due to its initialization) then the above if statement is equivalent to ``` if( 10 ){ ```
It returns halfway and shows--Process returned -1073741819 (0xC0000005) This code shows no error or warning also. Just want to know exactly why is it happening? ``` #include<stdio.h> void reverse(char*); int main() { char str[200]; printf("Enter a string : "); scanf("%s",&str); reverse(str); printf("Reversed string : %s",str); } void reverse(char *p) { char temp,*q; *p=*q; while(*p!='\0') { q++; } while(p<q) { temp=*p; *p=*q; *q=temp; p++; q--; } } ```
You never initialized q. It is pointing to something completely random. Fix ischar temp, *q = p;
I am using windows 10 and MinGW-x64 gcc 8.1.0. I was trying to take a long double as input using scanf. Here is the code: ``` #include<stdio.h> #include<stdlib.h> int main(int argc, char const *argv[]) { long double a; scanf("%Lf",&a); printf("%Lf",a); return 0; } ``` the output on the console is 0.000000. Why is that so? Is it a windows issue?
i guess in c mingw does not support long double datatype
We are having a Linux C program making use of OpenSSL APIs, acting as a TLS server. It currently has code as: ``` context = SSL_CTX_new(TLS_method()); ``` Which the OpenSSL v1.1.1 manual page says will support SSLv3, TLSv1, TLSv1.1, TLSv1.2 and TLSv1.3. While we now have a new requirement to only support TLS 1.3. Will setting SSL_CTX_set_min_proto_version(TLS1_3_VERSION) just do the trick? Or is there other practical way for the server to reject client connections with version lower than TLS 1.3?
CallingSSL_CTX_set_min_proto_version(context, TLS1_3_VERSION);is all that is needed. This restricts sessions created from this context to not use versions of TLS below 1.3. Also, you can useTLS_server_methodto create a context object that will create sessions that default to server mode.
I'm using Glade GTK2 to build an about dialog (but this is extendable to any GtkWindow). This is how I show it from my code: ``` GtkWidget *dialog_about = GTK_WIDGET(gtk_builder_get_object(builder, "dialog_about")); gtk_dialog_run(GTK_DIALOG(dialog_about)); gtk_widget_destroy(dialog_about); ``` Now, on Glade there is a label for showing the program version: Is it possible to replace that "1.0" value with another one from my code before showing it?
Solved by usinggtk_about_dialog_set_version: ``` GtkWidget *dialog_about = GTK_WIDGET(gtk_builder_get_object(builder, "dialog_about")); gtk_about_dialog_set_version (dialog_about, MY_VERSION); // <----- gtk_dialog_run(GTK_DIALOG(dialog_about)); gtk_widget_destroy(dialog_about); ```
``` #include<stdio.h> int main() { char arr[10]; printf("Enter your name: \n"); fgets(arr, sizeof(arr), stdin); puts(arr); return 0; } ``` I have achar arr[10]and usefgets(arr, sizeof(arr), stdin)to receive input. If I input say 20 characters, 9 chars will be written toarr[10]along with the null terminator added. But what happens to the remaining chars in the buffer? Do they get automatically flushed/cleared or are they left in the buffer forever? i.e. Can extra chars that are outside the bounds check cause a problem?
But what happens to the remaining chars in the buffer? They remain instdinfor the next read function. Do they get automatically flushed/cleared or are they left in the buffer forever? Left instdinuntil read or program ends. Can extra chars that are outside the bounds check cause a problem? Not directly. It depends on how your program copes will failing to read the excess input.
Trying to read various payment cards using PN532 NFC RFID Module. libnfc6 sucessfully polls most of the nfc cards and evenmobile payment methodis detected, but none of my Revolut cards are detected bynfc-pollapp. libnfc was compiled locally fromlibnfc-1.8.0 git tag. My current polling setup: ``` const uint8_t uiPollNr = 20; const uint8_t uiPeriod = 2; const nfc_modulation nmModulations[] = { { .nmt = NMT_ISO14443A, .nbr = NBR_106 }, { .nmt = NMT_ISO14443A, .nbr = NBR_212 }, { .nmt = NMT_ISO14443A, .nbr = NBR_424 }, { .nmt = NMT_ISO14443B, .nbr = NBR_106 }, { .nmt = NMT_FELICA, .nbr = NBR_212 }, { .nmt = NMT_FELICA, .nbr = NBR_424 }, { .nmt = NMT_JEWEL, .nbr = NBR_106 }, { .nmt = NMT_ISO14443BICLASS, .nbr = NBR_106 }, }; ```
Buying new PN532 NFC RFID Module solved the issue.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed2 years ago.Improve this question Is the ^ operator available in the C language? I have tried using it but it gives a faulty output. Does it denote raising an integer to the power of something
It works just fine and means bitwise XOR. That is,1^2gives 3. Unfortunately C doesn't provide a function to take power of integers. This is a known flaw of the language. You have to roll out such a function yourself either by using multiplication in a loop, or use the slow floating point functionpow.
I’m new to C, and I need to take an integer user input and increment its alternating digits by odd powers of 10without using arrays. For example, if the user types4906, I have to increment 0 and 4 by 1/10^1 and 1/10^3. ``` // Extracting alternating digits (User input e.g. 4906 stored in long number) (number / 10) % 10; // pow(10,1) (number / 1000) % 10; // pow(10,3) (number / 100000) % 10; // pow(10,5) ``` I do not know the size of the long the user will type in, therefore, I need to loop alternating digits of this number by (1 / odd powers of 10) % 10. Thank you so much.
``` //step 1 4906 % 10 = 6 4906 / 10 = 490 //step 2 490 % 10 = 0 490 / 10 = 49 //step 3 49 % 10 = 9 49 / 10 = 4 //step 4 4 % 10 = 4 4 / 10 = 0 //step 5 (last, after that you get only zeros) 0 % 10 = 0 0 / 10 = 0 ``` As you can see, noarrayandlengthinformation needed. Justmodanddivide(by ten) inside a loop until you hitzero.
I am new in C and tried checking the loop condition as to find on the internet, but I get this error I am not able to solve (no other questions/answers were helpful): ``` void main() { char* insert = malloc(30); printf("Insert a Molecular Formula:\n"); gets(insert); if (insert) { for (int i = 0; insert[i] != '\0'; i++) { } } } ``` I get the error 6011 in VS inside the for-loop when checkinginsert[i] != '\0'. I haven't found a good fix, I have tried cheking return of malloc likeif(!insert){ //above code here}but this didn't help. Thanks in advance.
Error C6011 is a warning, not an error, so your code will run, but it's not bad to handle these issues if Visual Studio is indicating them. To get the warning to go away, fix your loop like so: ``` if (insert) { for (int i = 0; insert[i] != '\0'; i++) { } } ```
Every time I compute the negative values are always counted. How to exclude negative numbers in an array so it wont get computed on finding the mean. ``` int getMean(int sum) { int result; result = sum / 5; return result; } int main() { int a[100] , sum = 0, mean, i; for (i = 1; i <= 5; i++) { printf("[%d]Enter numbers: ", i); scanf("%d", &a[i]); if (a[i] < 0) { printf("Whole numbers only, Try again\n"); i--; } if (a[i] > 0) { sum += a[i]; } } mean = getMean(sum); printf("Mean is: %d", mean); return 0; } ```
``` if (a[i] < 0) { printf("Whole numbers only, Try again\n"); i--; continue; } ``` I just added continue; at the end and it already did the job.
I am using the Linux stat function to find the length of a file in bytes and then I am trying the read the entire file (this is so I don't have to check for a null terminator and can create a perfect sized buffer to store the data) (I am not concerned about the file changing during the read). I tried using fgets but quickly remembered that it terminates at a new line and so this will not work. Is there a version of fgets that does not do this?
The standard C library routinefreadwill attempt to read a requested number of bytes (expressed as a number of objects of a given size) from a stream, and the Linux/Unix/POSIX routinereadwill attempt to read a requested number of bytes (expressed as a number of bytes) from a file descriptor.
I am using the Linux stat function to find the length of a file in bytes and then I am trying the read the entire file (this is so I don't have to check for a null terminator and can create a perfect sized buffer to store the data) (I am not concerned about the file changing during the read). I tried using fgets but quickly remembered that it terminates at a new line and so this will not work. Is there a version of fgets that does not do this?
The standard C library routinefreadwill attempt to read a requested number of bytes (expressed as a number of objects of a given size) from a stream, and the Linux/Unix/POSIX routinereadwill attempt to read a requested number of bytes (expressed as a number of bytes) from a file descriptor.
I am getting segmentation fault whenever I do this. I wonder if there is a way for me to assign a value to the struct without getting SegFault? ``` typedef struct _chunk { int lo; // lower bound int hi; // higher bound } chunk; chunk_stack = (chunk **)malloc(10 * 10 * sizeof(chunk **)); for (i = 0; i < chunk_per_thread; i++) { chunk_stack[myid][i].lo = 0; chunk_stack[myid][i].hi = 1; } ```
Suppose you need to allocate a 2D array of sizer * c.You need to first allocate memory for the double pointer which you did but have an error in it i.e., one extra * inside malloc function. ``` chunk **chunk_stack = (chunk **)malloc(r * sizeof(chunk *)); ``` Then you need to allocate memory for each of the rows separately. ``` for(int i = 0; i < r; i++){ chunk_stack[i] = (chunk*)malloc(c * sizeof(chunk)); } ```
My scanner is works fine but i couldn't find whats wrong with my parser ``` semi: "{" vallist "}" | "{" "}"" ; val: tSTR | tInt ; vallist: vallist , val | val ; ```
You have a number of problems, some of which are probably just typos in your copy-paste (what you have above will be rejected by bison). Your main problem is probably using"(double quotes) for your tokens, which for the most part doesn't do anything useful -- it creates a 'new' token that is not the same as the single character token your lexer probably returns. Instead, you want to use'(single quotes): ``` semi: '{' vallist '}' | '{' '}' ; val: tSTR | tInt | semi ; vallist: vallist ',' val | val ; ```
I've been working on a program that converts UTF-16 to UTF-8, but I've been having trouble converting big numbers like 14846106 to binary. All binary converters that I found on the web break if the decimal number is 4 digits or more. I used itoa, worked flawlessly but problem arose when I tried to compile the program on Linux. So are there any other alternatives (besides snprintf which isnt even capable of converting from decimal to binary)?
A simple recursiveto binaryalgorithm. ``` to_binary(unsigned x) { if (x > 1) { to_binary(x/2); } putchar(x%2 + '0'); } ```
I need to save a user input into a 2D array in a way where the user inputs something like '123456789' and I save that input into an array so that array[0][0] == 1, array[1][2] == 6 etc. Is there something like getchar() that I could use, but for numbers?
You can use getchar() itself, and convert it to integer using: ``` char c = getchar(); int arr[3][3]; arr[0][0] = c - '0'; ``` Referthisstackoverflow answer.
I have onepthread_mutex_taka lock in a structure and I create 2 structures. are those the same lock? Or are they a completely different lock?I have a function that uses the lock of the structure, can the one structure detect if the other structure lock is used?
are those the same lock?Or are they completly different lock? It deppends, if you have a pointer you can use the same mutex in both structures, if not, they are copies, using one will not reflect on the other. I have a function that uses the lock of the structure, can the one structure detect if the other structure lock is used? Again, if it's a pointer to the same mutex it's shared by both structures, lock/unlock is detected by both, if not, locking or unlocking one will have no effect on the other.
Let's say I declare a global array in my C program (i.e. it's not allocated in stack memory). What is the largest array I can create? Is it just a limitation of available memory on the machine? Or is there some other OS setting that typically controls this?
There is no single largest bound on an array size in C. In any particular implementation, it may be limited by actually available memory (either main memory or swap space on disk, according to operating system features and settings), policy set by the system operator, capability of the address space, limitations of the compiler, and possibly other factors. The limit may be available memory in one system and address space in another system.
I know that a pointer points to a memory address, but is it possible to just use the&symbol instead of a pointer?
&vwill get you the address of the variablev, but&vis an r-value, not an l-value. In order to have an l-value containing the address of a variable you would have to use the*syntax, as inT *p = &v;.
Write a function that prints out all the words in the array passed in as an argument that contain a sequence of 3 consecutive letters that are also consecutive alphabetically. For instance, the word costume should be printed, but not cost. The Array will end with Null which can be used to terminate the algorithm
if(asciiOne == asciiTwo -1 == asciiThree -2 || asciiOne == asciiTwo -1 == asciiThree -2) This is incorrect in C. If first condition is satisfied(asciiOne == asciiTwo -1) then it will give 1. After that, it will check1 == asciiThree -2which is ofcourse not what we want. The correct way to do this is: if((asciiOne == asciiTwo -1) && (asciiTwo == asciiThree -1)) This way it evaluate both conditions which are required in the problem. Edit - Added brackets to specify in what order conditions will be evaluated. We can also remove brackets since precedence of==is higher than&&. Source -C Operator Precedence
I am trying to make a constant all binary ones __m256d variable. I saw the postFastest way to set __m256 value to all ONE bitsbut it only handles the case of __m256i and __m256, not __m256d. Thank you for your help
You should fill the bits to one as you did and then cast it to the __m256d register: ``` __m256i a = _mm256_set1_epi64x(-1); __m256d b = _mm256_castsi256_pd(a); ``` Or simply: ``` __m256d b = _mm256_castsi256_pd(_mm256_set1_epi64x(-1)); ```
Using'linmath.h', I'm trying to rotate an image after a translation. However, after the translation, the image doesn't move at all. In the vextex shader, I have ``` gl_Position = transform * vec4(aPos, 1.0); ``` and in the program, I have ``` mat4x4 transform; mat4x4_identity(transform); mat4x4_rotate(transform, transform, 0.0f, 0.0f, 1.0f, (float) glfwGetTime()); mat4x4_translate(transform, 0.5f, -0.5f, 0.0f); ``` I want to point out that translating an image after a rotation (i.e., swapping the last two lines) works fine, so I don't know what could be wrong.
If you take a peek at thesource format4x4_translate, you can see it resets the matrix to identity first. You might be looking for the next function,mat4x4_translate_in_place.
I'm working on POSIX linux to learn. I'm using C Programming Languages. I want to read a folder, but instead of using readdir or opendir, I want to use pure open and read, I want to extract subfolders or files in this folder as names as string. Is this possible with open() and read() as open and read (without using dirent.h)?
Simply put: no, it's not. open()andread()operate on files, not directories. opendir()andreaddir()operate on directories, not files.
I was wondering if there's a easy way to define a variable inside an if block and then use it out of that if statement (like you can in Python). Like that: ``` int a = 2; if (a <= 1) { char string[10] = "foo"; } else { char string[10] = "bar"; } printf("%s", string); ``` Output ``` bar ```
You can not declare a variable inside anifstatement (or other compound block) and use it outside of it's scope. If you need the value outside, then you have to declare an appropriate variable and assign it in theifstatement. In your example this would looke like this: ``` char string[10]; if (a <= 1) strcpy(string, "Jahr"); else strcpy(string, "Jahren"); printf("%s\n", string); ```
``` #include <stdio.h> int f1(){ static int val=11; return --val; } int main() { for( f1(); f1(); f1()){ printf("%d",f1()); } } ``` The output of the program is :8 5 2 Could someone explain me what doesfor(f1();f1();f1())do?
``` #include <stdio.h> int foo(void) { static int val = 11; return --val; } int main(void) { int (*f1)(void) = foo; //4 function pointers to the same function int (*f2)(void) = foo; int (*f3)(void) = foo; int (*f4)(void) = foo; for (f1(); f2(); f3()) { printf("%d", f4()); } } ``` The execution goes like this ``` val = 11 f1() 10 f2() 9 "true" f4() print 8 f3() 7 f2() 6 "true" f4() print 5 f3() 4 f2() 3 "true" f4() print 2 f3() 1 f2() 0 "false" ```
Using'linmath.h', I'm trying to rotate an image after a translation. However, after the translation, the image doesn't move at all. In the vextex shader, I have ``` gl_Position = transform * vec4(aPos, 1.0); ``` and in the program, I have ``` mat4x4 transform; mat4x4_identity(transform); mat4x4_rotate(transform, transform, 0.0f, 0.0f, 1.0f, (float) glfwGetTime()); mat4x4_translate(transform, 0.5f, -0.5f, 0.0f); ``` I want to point out that translating an image after a rotation (i.e., swapping the last two lines) works fine, so I don't know what could be wrong.
If you take a peek at thesource format4x4_translate, you can see it resets the matrix to identity first. You might be looking for the next function,mat4x4_translate_in_place.
I'm working on POSIX linux to learn. I'm using C Programming Languages. I want to read a folder, but instead of using readdir or opendir, I want to use pure open and read, I want to extract subfolders or files in this folder as names as string. Is this possible with open() and read() as open and read (without using dirent.h)?
Simply put: no, it's not. open()andread()operate on files, not directories. opendir()andreaddir()operate on directories, not files.
I was wondering if there's a easy way to define a variable inside an if block and then use it out of that if statement (like you can in Python). Like that: ``` int a = 2; if (a <= 1) { char string[10] = "foo"; } else { char string[10] = "bar"; } printf("%s", string); ``` Output ``` bar ```
You can not declare a variable inside anifstatement (or other compound block) and use it outside of it's scope. If you need the value outside, then you have to declare an appropriate variable and assign it in theifstatement. In your example this would looke like this: ``` char string[10]; if (a <= 1) strcpy(string, "Jahr"); else strcpy(string, "Jahren"); printf("%s\n", string); ```
``` #include <stdio.h> int f1(){ static int val=11; return --val; } int main() { for( f1(); f1(); f1()){ printf("%d",f1()); } } ``` The output of the program is :8 5 2 Could someone explain me what doesfor(f1();f1();f1())do?
``` #include <stdio.h> int foo(void) { static int val = 11; return --val; } int main(void) { int (*f1)(void) = foo; //4 function pointers to the same function int (*f2)(void) = foo; int (*f3)(void) = foo; int (*f4)(void) = foo; for (f1(); f2(); f3()) { printf("%d", f4()); } } ``` The execution goes like this ``` val = 11 f1() 10 f2() 9 "true" f4() print 8 f3() 7 f2() 6 "true" f4() print 5 f3() 4 f2() 3 "true" f4() print 2 f3() 1 f2() 0 "false" ```
Let's say I have the following array: ``` int numbers[] = {-2,4,9,11}; int sum=sum_list(numbers); ``` If I were to pass pointers, I could add in aNULLat the end of the list to signal the size of it. However, in the above non-pointer list, is there a way to do that? If not, is the way around this just to explicitly pass the size of the array to the callee, for example: ``` int sum_list(int numbers[], size_z len); ```
When dealing with an array of non-pointer values such as this, you basically have two choices: Pass the length of the list to any function that also receives the listDesignate some value that is outside the range of acceptable values to use as an end-of-list indicator A third choice would be to implement a Pascal-type array where index 0 contains the length of the array.
In the IBM environment a hybrid C / Assembler compiler call Metal C exists and it permits C source programs to be intermixed with Assembler source programs and compiled as an executable. My question is this, ignoring all the external linkage references that the resultant executable might have for a moment, could the combined C / Assembler executable run on a z/Linux platform, its just machine instructions, right?
The underlying Operating System and its associated call stack determines compatibility. z/OS uses a specific calling convention, system calls and libraries that are fundamentally different than Linux. Thus they are not binary compatible. That said, if you are using languages that are available on both platforms then you may be able to simply recompile and "port" your application.
I want to calculate a number to the powerp, gotSegmentation faultas a result. This code is supposed to work: ``` #include <stdio.h> int my_power(int nb, int p) { if (nb != 0){ return nb*my_power(nb, p-1); } return 1; } int main(int argc, char argv[]){ printf("%d\n", my_power(5, 3)); return 0; } ```
In your code, your recursion never ends. Change the base case topb<=0and it will work.
I've been reviewing bit manipulation and have been looking at this page:http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs ``` int v; // we want to find the absolute value of v unsigned int r; // the result goes here int const mask = v >> sizeof(int) * CHAR_BIT - 1; r = (v + mask) ^ mask; ``` size of int is 4 and chars in byte is 8. So basically I gather this is a mask for a 32 bit integer. I understand for negative v this is supposed to create a mask of -1 and for positive numbers a mask of 0. My question is why only shifting 28 bits instead of 31 bits? Feel like I'm missing something here.
It is 31 bits, assuming thatsizeof(int) == 4andCHAR_BIT == 8. The binary*operator has higherprecedencethan binary-, so this is parsed as(sizeof(int) * CHAR_BIT) - 1, which is(4 * 8) - 1 == 31.
This question already has answers here:How to programmatically set IP address on Windows 7 using C(2 answers)Closed2 years ago. I want to change my IP address in Window with C, but only things I can find is the function like inet_pton(), or doing with C++. Can I use the latter with C or should I make some difference? If so, how should I do?
If you want to change the IP address of a network interface by program, you should find the correct Windows' system call. https://stackoverflow.com/a/33867268/7865574
Today I have the problem about how to quit the git bash input. The book wrote press Ctrl+D(UNIX) or Ctrl+Z(DOS) in the new line. I try it but failed. So I just ask the command to quit it.
Your program is written so that it quits when you enter '#' into the terminal. It cannot detect end of file because that would require a different condition. (You would have to test for EOF, and in addition declare the variablechasintbecause that is the actual return value fromgetchar()and becauseEOFis usually defined as -1.)
I made a separate file for all the labels to be used in the main window called Labels.vala Previously, I had created the labels inside the MainWindow.vala file, but now I wanted to make a separate file for the labels as the labels will change based on the location set by the user and that will make the code in the MainWindow.vala file too long. This is the code inside the Labels.vala file: Now, when I try to add this class to a grid inside the main window, it compiles with no errors but the labels are not displayed in the main window. This is how I add the labels grid in the main window grid. Link to source code:https://github.com/Suzie97/epoch
At the moment you're trying to attach an instance of theLabelsclass to theMainWindowgrid, but you need to use theLabels.labels_gridproperty that it exposes. ``` grid.attach (labels.labels_grid, 0, 4, 1, 2); ```
I want to know where to put command line arguments in VS Code for C. I know in Visual studio you can hit the project and add the command line arguments, but I do not know how to do that in VS Code.
``` { "name": "C Launch", "request": "launch", "program": "${workspaceFolder}/a.out", "args": ["arg1", "arg2"], "cwd": "${workspaceFolder}" } ``` put the above line in the.vscode/launch.jsonfile in your working directory. Be sure to replacea.outwith your name of program. For further details checkhere.
I want to parallelise this code: ``` #pragma omp parallel for for (i=0; i<=imax+1; i++) { // combined loops for (j=1; j<=jmax+1; j++) { umax = max(fabs(u[i][j]), umax); vmax = max(fabs(v[j][i]), vmax); } } ``` But there are race conditions forumaxandvmax. Is there a way to fix this without serializing the code with#pragma omp critical?
Yes, you just need to use the OpenMP reduction clause. ``` #pragma omp parallel for reduction(max:umax, vmax) for (i=0; i<=imax+1; i++) { // combined loops for (j=1; j<=jmax+1; j++) { umax = max(fabs(u[i][j]), umax); vmax = max(fabs(v[j][i]), vmax); } } ```
I want to parallelise this code: ``` #pragma omp parallel for for (i=0; i<=imax+1; i++) { // combined loops for (j=1; j<=jmax+1; j++) { umax = max(fabs(u[i][j]), umax); vmax = max(fabs(v[j][i]), vmax); } } ``` But there are race conditions forumaxandvmax. Is there a way to fix this without serializing the code with#pragma omp critical?
Yes, you just need to use the OpenMP reduction clause. ``` #pragma omp parallel for reduction(max:umax, vmax) for (i=0; i<=imax+1; i++) { // combined loops for (j=1; j<=jmax+1; j++) { umax = max(fabs(u[i][j]), umax); vmax = max(fabs(v[j][i]), vmax); } } ```
I used pointer while printing structure elements but its working without using pointer in the print statement but shouldn't we use pointers to gather the element from the variable address why is it different in the structure case and its different in string also . Can anyone tell me why is that ? ``` #include <stdio.h> int main(){ struct books{ char name[10]; int page; }; struct books b1={"book1",1}; struct books *ptr; ptr=&b1; printf("%s %d",ptr->name,ptr->page); } ```
``` printf("%s %d",*ptr->name,*ptr->page); ``` is wrong.A->Bmeans(*A).B. You should do either ``` printf("%s %d",ptr->name,ptr->page); ``` or ``` printf("%s %d",(*ptr).name,(*ptr).page); ```
I have a problem in which I write a VERY simple program for the ESP32 using the Arduino IDE. I am trying to write something to the Serial output, but in the console I only get gibberish. I do get the data, but it's not formatted in the way it needs to be. Here is a screenshot: As you can see, the code is very simple. The console is on the right rate, but the input looks like crap. I have tried using different forms, like Serial.write and Serial.print, but they all seem to not work. I just expect to get "Testline" on different lines, which does happen sometimes, but it's not consistent. I am using the NodeMCU-ESP32 ESP32 DEVKITV1
Using a delay of 40 did the trick. Have you tried using longer delays? What happens then? And all in all this looks more like some kind of buffering issues, where multiple transmissions are mixed up somehow (either on the sending or on the receiving side).– Some programmer dude
I would like to make a lookup table withuint8_tassociated to astring. How do you think I can do this? Here is my code: ``` static const uint16_t ReadAccess[][2] = { /* Value in b3b2 in byte 1, read access description */ {0x0, "ALWAYS"}, {0x1, "RFU"}, {0x2, "PROPRIETARY"}, {0x3, "RFU"} }; ```
You can usestructuresto group members with multiple types to create one new type. ``` struct table_element { uint8_t intValue; const char* strValue; }; static const struct table_element ReadAccess[] = { {0x0, "ALWAYS"}, {0x1, "RFU"}, {0x2, "PROPRIETARY"}, {0x3, "RFU"} }; ```
I used pointer while printing structure elements but its working without using pointer in the print statement but shouldn't we use pointers to gather the element from the variable address why is it different in the structure case and its different in string also . Can anyone tell me why is that ? ``` #include <stdio.h> int main(){ struct books{ char name[10]; int page; }; struct books b1={"book1",1}; struct books *ptr; ptr=&b1; printf("%s %d",ptr->name,ptr->page); } ```
``` printf("%s %d",*ptr->name,*ptr->page); ``` is wrong.A->Bmeans(*A).B. You should do either ``` printf("%s %d",ptr->name,ptr->page); ``` or ``` printf("%s %d",(*ptr).name,(*ptr).page); ```
I have a problem in which I write a VERY simple program for the ESP32 using the Arduino IDE. I am trying to write something to the Serial output, but in the console I only get gibberish. I do get the data, but it's not formatted in the way it needs to be. Here is a screenshot: As you can see, the code is very simple. The console is on the right rate, but the input looks like crap. I have tried using different forms, like Serial.write and Serial.print, but they all seem to not work. I just expect to get "Testline" on different lines, which does happen sometimes, but it's not consistent. I am using the NodeMCU-ESP32 ESP32 DEVKITV1
Using a delay of 40 did the trick. Have you tried using longer delays? What happens then? And all in all this looks more like some kind of buffering issues, where multiple transmissions are mixed up somehow (either on the sending or on the receiving side).– Some programmer dude
I would like to make a lookup table withuint8_tassociated to astring. How do you think I can do this? Here is my code: ``` static const uint16_t ReadAccess[][2] = { /* Value in b3b2 in byte 1, read access description */ {0x0, "ALWAYS"}, {0x1, "RFU"}, {0x2, "PROPRIETARY"}, {0x3, "RFU"} }; ```
You can usestructuresto group members with multiple types to create one new type. ``` struct table_element { uint8_t intValue; const char* strValue; }; static const struct table_element ReadAccess[] = { {0x0, "ALWAYS"}, {0x1, "RFU"}, {0x2, "PROPRIETARY"}, {0x3, "RFU"} }; ```
Is the following valid/acceptable C code to return a string-literal? ``` char* level_str(level) { switch (level) { case DEBUG: return "DEBUG"; case INFO: return "INFO"; case WARN: return "WARN"; case ERROR: return "ERROR"; default: return "UNKNOWN"; } } ``` Or, does the pointer to the string-literal become invalid/overridden on the stack once the function is returned? If so, are the only two valid ways to do this either (1) malloc the string; or (2) write to a callee-supplied buffer?
Can a string-literal be returned without malloc/buffer Yes. The address of the string literal can be retuned. OP's code is fine, but better asconst char* level_str(level)as the dataconst char *points to andstring literalsare best left alone without attempting to change. To attempt to change a string literal isundefined behavior(UB). Might work might not, might crash, etc.
EDIT: It was a cache issue I had to restart Visual Studio code It says its not included but I use this code#include <d3dx9.h>;and here are myDirectories(Include Directores:$(DXSDK_DIR)Include;$(IncludePath)) (Library Directories:$(DXSDK_DIR)Include;$(IncludePath)) I see a lot of people ask this question but no one of the answers seem to work. If it matters I am using visual studio code 2019. Also I checked the the Include folder of where I installed DirectX and it has the d3dx9.h.
It was a cache issue with VSC 2019
I am trying to get the Least significant 4 bits of one word and the most significant 12 bits of another word and concatenate them into a single word. I am working in C, which I haven't worked with much in the past. ``` int a; int b; int c; int a_masked; int b_masked; a = 0x1234; b = 0xABCD; a_masked = a & 0X000F; b_masked = b & 0xFFF0; c = ((a_masked << 12) || b_masked >> 4); printf("%d", c); ``` C should be 4ABC, but my result is 1.
||operator, which you used, is alogicalOR operator and it returns 0 or 1. You should use abitwiseOR operator|(one vertical line, not two).
I want to use the braced-group within expression, which is a GNU extension to C. The compiler will evaluate the whole block and use the value of the last statement contained in the block. The following code will print 5, but when I compile it withgccit returns a warning warning: statement with no effect [-Wunused-value] ``` typeof(5) x = ({1; 2;}) + 3; // The warning points to "1" printf("%d\n", x); ``` Why would the GCC compiler return a warning if this expression was made by GNU?
Why would the GCC compiler return a warning if this expression was made by GNU? gccdoesn't complain about the GNU extension itself. Rather the statement1;is useless since thestatement expression's result would be the same without it since the final result of({1; 2;})is 2. i.e. it's equivalent to: ``` typeof(5) x = ({2;}) + 3; ``` sogccwarns that the statement1;has no effect.
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.Closed2 years ago.Improve this question #include errors detected. Please update your includePath. Squiggles are disabled for this translation unit (C:\Users\manth\.vscode\Untitled-1.c) cannot open source file stdio.h in vs code
Make sure your includePath doesn't contain any system headers and your compilerPath is set correct and then run C/C++: Log Diagnostics and see if the output appears correct or not.
let's say I have following plain C struct ``` typedef struct { uint16_t id; uint32_t address; uint8_t type; } Config; typedef struct { Config cfg; uint32_t ready; } Instance; ``` My question is whether it is possible to define a C++ class which has an attribute ofInstancetype i.e. ``` class A { public: A(); private: Instance instance; }; ``` If so how the compiler notice that theInstanceis plain C struct? Is it necessary to use the initialization part of the A class constructor to initialize theinstance?
No, you don't need to use the constructor to initialize. Compiler knows it's a "struct" data type because you defined it that way. Plain C structures also valid c++ structures so there's nothing called as plain c structure. Learn more about compilers here:https://www.freecodecamp.org/news/c-compiler-explained-what-is-the-compiler-and-how-do-you-use-it/
printf("%s", ...)assumes null-terminated string. If I have a string deliminated by a length, what is the best way to do? Supposebufis the start address of the string,nis the length of the string. I have the following code. Is it the best way to do so? ``` for(int i=0;i<n;++i) { fputc(buf[i], stdout); } ```
You can use%.*sformat specifier to specify the length to print. ``` #include <stdio.h> int main(void) { int length = 3; const char* str = "123456"; printf("%.*s\n", length, str); return 0; } ``` This example will print123. Better way to print fixed-length data should be usingfwrite().printf()can do many thing, so it may be unnecessarily slow. ``` #include <stdio.h> int main(void) { int length = 3; const char* str = "123456"; fwrite(str, sizeof(*str), length, stdout); return 0; } ```
There is auint8x8_tmask, obtained from intrinsics likevcgt_u8(), with values like: ``` 0, 0, 0, 0,255, 0, 255, 255 ``` I would like to convert this mask to twouint32x4_ttype masks. It seemsvmovl_u8()andvmovl_u16()will still keep 255 instead of 65535 and 4294967295. How can I do this conversion?
A signed widen operation likevmovl_swill convert an all-ones pattern like 255 into 65535 and so on, so you need tovreinterpretyour unsigned vector to signed, and back: ``` uint8x8_t v = ...; int16x8_t i = vmovl_s8(vreinterpret_s8_u8(v)); uint32x4_t low = vreinterpretq_u32_s32(vmovl_s16(vget_low_s16(i))); uint32x4_t high = vreinterpretq_u32_s32(vmovl_s16(vget_high_s16(i))); ```
I'm creating a program that calculates the multiples of seven from 1 to 100. However my code prints one multiple above 100, 105. I'm not sure how to fix this. I've tried doing num <= 100, num < 100, num < 99, num = 0, but nothing works. Thank you! Code: ``` int main() { //variables int i = 1, num; printf("Multiples of Seven from 1 to 100: \n"); while(num < 100) { num = i * 7; printf(" %d ", num); i++; } //while end } //main end ```
Make while loop condtion as, ``` while(i * 7 <= 100) ```
Scan a number along with its base value. If a number starts with 0 it is octal nd if it starts with 0x it is hexadecimal. print the corresponding decimal value. ``` #include<stdio.h> int main() { int a,b; scanf("%x %d",&a,&b); printf("%d",a);` } ``` 3 test cases shows error .please help me with this.
Use scanf i flag: Matches an optionally signed integer; the next pointer must be a pointer to int. The integer is read in base 16 if it begins with 0x or 0X, in base 8 if it begins with 0, and in base 10 otherwise. Only characters that correspond to the base are used. ``` #include<stdio.h> int main(void) { int a,b; scanf("%i %i",&a,&b); printf("%d %d\n", a, b);` return 0; } ```
I've made a little program that should read a file and print its content out (Yes, itisexactly 14 Bytes :) ``` # include <stdio.h> # define FILE_SIZE 14 int main () { FILE *fp = fopen("file.txt", "r"); char *buf[FILE_SIZE]; fread(buf, FILE_SIZE, 1, fp); for (int i = 0; i < FILE_SIZE; i++) printf("%c", *buf[i]); } ``` If I run it, aMemory Access Violationoccurs.I guess it's caused by*buf[i], because if I remove the*, everything's right.(Well, I get cryptic characters then, but that's allright, isn't it?) Now, my question: Why doesbuf[i]work, but*buf[i]doesn't?
Oopsbufshouldn't be an array of pointers to character but array of character ``` char buf[FILE_SIZE]; ``` and ``` printf("%c", buf[i]); ``` No crash
``` char c = '2'; char d = '3'; char e = 'c' + 'd'; int digit = e - '0'; // ACSII into int printf("digit = %d \n", digit); //should display 23 printf("char c : %c \n",c); //should display 2 printf("char d : %c \n",d); //should display 3 ``` What I am trying to do is to is a string concatenation without using the strcat() function to display 23 as an int.However I seem to be getting : digit = - 105
Overflow! Acharis just 8 bits long. By default, it's signed, so the range is-128 <= x < 128. You're adding the characters'c'and'd'(not the variablescandd) which means you're really adding the ASCII values, soehas the value199. Because it's signed, it's really199 - 256 == -57. Then you subtract'0', which is48in ASCII, so you get-57 - 48 = -105.
``` double A[N] = { ... }, B[N] = { ... }; for (int i = 1; i < N; i++) { A[i] = B[i] – A[i –1]; } ``` Why can't this loop be parallelized using the#pragma omp parallel forconstruct?
The reason is pretty plain in the code. To calculateA[i]you need to calculateA[i-1]first. There areNsteps where every step depends on the previous step. In general, a loopfor(int i=1; i<N; i++)is suitable for parallelism if the loop would produce the exact same result if you changed the header tofor(int i=N-1; i>0; i--) Maybe that was a bit confusing. It has nothing to do with reverse order. The point is that you should be able to do each step individually.
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)sequence points in c(4 answers)Closed2 years ago. ``` val = n++ + arr[n]; ``` How can I rewrite the line of code above to become more readable? How is this code evaluated by a compiler?
This code is invalid (reason) so you should bin it. It is better to write more lines to keep the code readable and correct than to write "hacky" complex expressions. ``` val = n + arr[n]; n++; ```
i was writing a c code for executing "history 10" command of terminal,i run program using clang compiler on my mac terminal,it show error "Illegal Instruction :4"My Code is- ``` #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include<errno.h> #include<sys/wait.h> #include <unistd.h> #include<string.h> int main() { char cmd[10]; strcpy(cmd,"history 10"); system(cmd); return 0; } ```
You overrun your buffer: thecmdarray has only 10 characters and youstrcpyan 11-character string into it (the string has an implicit 11-th zero byte at the end, which is the string's terminator). Get rid of the buffer and just do ``` system("history 10"); ``` Or declare the buffer long enough to accomodate your current, and possibly some future command. Something like this: ``` char cmd[500]; ```
I am trying to deep copy from one structure to another structure However structure has many pointers,how do I copy it in single statement? Do I have to manually copy each structure pointer member?
You have to manually copy everything if you want a deep copy.
Does GCC, or do compilers in general, remove variables which are operated on, yet do not at all affect the result of the code? For example, say main only contained ``` int a = 0; int b = 0; for (int i = 0; i < 10; i++) { a += 10; b += 10; } printf("%d", a); ``` Is the variable b ever present in memory or even operated on after compilation? Would there by any assembly logic storing and handling b? Just not positive whether this is something that's counted under deadcode elimination. Thanks.
Yes, absolutely. This is a very common optimization. The best way to answer such questions for yourself is to learn a little bit of assembly language and readthe code generated by the compiler. In this case, you can see that not only does GCC optimizebentirely out of existence, but alsoa, and it compiles the whole function into just the equivalent ofprintf("%d", 100);.