question
stringlengths
25
894
answer
stringlengths
4
863
I'm writing net raid FS with FUSE on ubuntu. Here are syscalls I've implemented:createopenreadwritereleaseunlinkmkdiropendirreaddirreleasedirrmdirgetattrandrename. Everything works fine, but here is such case: I wrote "hello world" in c and tried typing this:gcc hello.c -o a.out.a.outis fine, but it's just a file, not executable (When I set manually 0777 permissions it executes fine on./a.out). When permissions must be set, and how? And when compiling, how to know which files should be set exe permissions? Based on what?
I lackedchmodsyscall implementation.chmodmakes it work all right. Thanks @Barmar for help!
How can i typecast address returned by malloc to struct node type?when i try to compile the following code it shows error every time regarding change in type. ``` struct node { int info; struct node *link; }; struct node createnode() { struct node *n; n = (struct node *) malloc( sizeof(struct node) ); // error: incompatible types when returning type 'struct node *' but 'struct node' was expected return n; } ```
Yourcreatenodefunction returnsstruct nodebut you return astruct node* You should change the method signature to make it return astruct node*
I need to create some major improvements in my circut and I am not sure if the LCD display I am using is or is not the bottleneck.Assuming well designed C code, how long would it take to set cursor position to (0,0), write 4 characters (or a single character) and set cursor to next line?Does checking the busy flag increase/decrease the operation time?I know measuring times like those can be problematic but I just need the order of magnitude. (Although if You have some experience with specific times please share your benchmarks).
On page 52the datasheetstates the "Enable cycle time" t[cycE] is 500ns min. => At least 500ns are needed to sendoneword (4 or 8 bits) of data to the display. Add to that the processing time for each operation (37µs for most). The return home command however takes 1500µs and hence dominates the processing time.
Say I have anint16x8_tvector. I want to limit the range of its values to 0-255 and convert it to anuint8x8_tvector. Reading the vector into an array and doing it the traditional non-intrinsic way is waaaay too slow. Is there a faster way?
All you need is the single instructionvqmovun.s16,vqmovun_s16in intrinsics. Vector Saturating(q) Move Unsigned Narrow ``` int16x8_t input; uint8x8_t result; . . . . . . result = vqmovun_s16(input); ``` Any negative element will be replaced with 0 while all the numbers bigger than 255 will be set as 255 then narrowed to unsigned 8bit elements, and all these in a single cycle, EXACTLY what you need. There is alsovqmovn_s16which keeps the values signed (-128~127) PS: Are you working on YUV to RGB conversion? That's the one time I needed this instruction.
Using stdarg.h, I can only pull one type because I have to know the types im retrieving. How then, does printf manage to be a variadic function with any type, in C no less?
printf()uses the format string to determine at run time what sort of argument to pull. I haven't looked at the source toprintf(), but one possible implementation might contain a switch something like this: ``` switch (type_specifier) { case 's': str = va_arg(args, char *); /* output str as a string */ break; case 'd': number = va_arg(args, int); /* output number as a decimal value */ break; etc. etc. etc. } ``` Note that a full implementation will be vastly more complex than this when you factor in all the various types of arguments, all the various sizes the arguments can be, the fact that "%*d" makes an extra va_arg() usage to get the width of the number, and that width specifiers can vary the output as well.
I know that for example this: ``` void foo(int a[])// or a[x] ``` will be considered by the compiler like this: ``` void foo(int *a) ``` But I don't know, and I didn't found anywhere how are multidimensional arrays seen by the compiler For example: ``` void foo(int a[3][4]) ``` Will it be something like this? ``` void foo(int (*a)[4]) ``` Or something like this? ``` void foo(int **a) ```
When an array decays, it converts into a pointer to the first element. In the case ofint a[3][4],ais an array ofint[4], so a pointer to an element ofint [3][4]has typeint (*)[4]. So this: ``` void foo(int a[3][4]) ``` Is the same as: ``` void foo(int (*a)[4]) ```
All I can find on this topic is mentions ofFSMoveObjectToTrashSyncfunction, which is nowdeprecated and no alternative is listed for it. How to do it from C or Objective-C code?
Use NSFileManager: https://developer.apple.com/documentation/foundation/nsfilemanager trashItemAtURL:resultingItemURL:error: Moves an item to the trash.
This question already has answers here:Assigning two values with an union variable(6 answers)Closed5 years ago. ``` union Data { int i; char s[20]; } data; int main(){ printf( "%lu\n", sizeof( data ) ); for( int i = 0; i < 20; ++i ) { data.s[i] = 0; } data.i = 0; strcpy( data.s, "Hello World!"); if( data.i ) { strcpy( data.s, "Farewell!"); } printf( "%s\n", data.s ); ``` Why does it respond with "Farewell"? I would expectif( data.i )to evaluate asFalse, but somehow it is evaluated asTrue.
Unlike astruct, all fields in aunionoverlap each other in memory. So if you change one field, it affects all the others. If you want the fields to be distinct from each other, declare astructinstead: ``` struct Data { int i; char s[20]; } data; ```
Prefer a micropython answer but will accept CPython I'm implementing a Python function in C. How do you apply a decorator to Python function written in C?
Decorators can be invoked with a function as their argument. So if you would have written this (in Python): ``` @mydeco def myfunc(x, y): return x * y ``` You can instead write this: ``` def myimpl(x, y): return x * y myfunc = mydeco(myimpl) ``` You can then movemyimplto C. If your decorator takes arguments: ``` myfunc = mydeco(a, b)(myimpl) ```
I have the function below : ``` addToTxBuffer((uint8_t []){0x01,0x11}, 2, zeroPad); ``` The second argument2is thesizeof first argument. I would like to usesizeofinstead of2. Is there any syntax that makes it possible? i.e. : ``` addToTxBuffer((uint8_t header[]){0x01,0x11}, sizeof(header), zeroPad); ``` this does not work though.
Compound literals are unnamed, so you can't reference them in that way. You would need to define the array separately, then you can get its size: ``` uint8_t header[] = {0x01,0x11}; addToTxBuffer(header, sizeof(header), zeroPad); ```
I want to write a script with C. Only run on the Ubuntu system. I Get the name of the operating system. But. I failed to define the if clause. Thanks for the help Like this algorithm:
I think the most reliable way of checking the OS name is to use theunameutility. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int match_OS(const char* name) { FILE *p; int result; char *s = malloc(1024); p = popen("uname -v", "r"); s = fgets(s, 1024, p); result = (strstr(s, name) != NULL); pclose(p); free(s); return result; } int main() { if (match_OS("Ubuntu")) { puts("This is Ubuntu"); } else { puts("This isn't Ubuntu"); } return 0; } ```
Programming in C I found out it was convenient in a switch-case to make little groups of cases by giving them the same name and add a number to it like: ``` case initiating: break; case (initiating+1): break; ``` etc etc. Currently I am still using brackets around around (initializing+1). But I wonder, do I have to do that? would ``` case (initiating+2): ``` work? I could not really find an anwser.
As you can seeherea switch requires a constant expression. Every label should be knownat compile time. Brackets are not required but can improve readability. Be sure that you really need (initiating + 2). 2 is a magic number and does not provide any additional information to the reader of your program. Using an enum will give you the same result but better readability. The best way to verify if this works is by simply writing an example down and compiling it.
The Problem I usually usefgets()orgetchar(), but now I need to usegetch(), because I don't want to pressenterto send a char to the input buffer. What I tried When I usedfgets()andgetchar()I also used: ``` int c; while ((r = getchar()) != '\n' && r != EOF){} ``` But now if I use it beforegetch()it requires me to pressenter, which I don't want. Is there any portable solution to empty the input buffer?
You can't usegetch()in a portable contextbecause it's aconio.h, not astdio.hfunction. There arelengthy threads on this topicand the overall assumption is that it can't be done, only worked around in a dodgy manner. I suggest you revise your code and application to check weather or not youneedto input with agetch()like function, or if there are other ways to do achieve the same goal. Depending on the use case it's often only cosmetic not to pressEnter.
I want to print big arrays which can contain any value, when 0x00 came then printf stop printing remaining characters. ``` int main(void) { // your code goes here char string[10]={0x31, 'a', 0x33,0x34, 0x35, 0x00,0x39, 0x40, 0x42,'\0'}; printf("%.*s\n", 5, string); printf("%.*s\n", 10, string); return 0; } ``` Output :1a3451a345 Note : I can print char by char and it works but it is too slow when dealing in MBs
You can always try to usefwriteto simply write a block of data to either a file or stdout. But note, when writing to stdout the zero will not be shown, because cmd/terminal don't have a character assigned to it (as far as I know). ``` fwrite (string , sizeof(char), sizeof(string), stdout); ``` If you write to a file, the data (even the zeros) should be printed to your file and stored, so that should not be an issue if you wish to reuse it later.
I want to print big arrays which can contain any value, when 0x00 came then printf stop printing remaining characters. ``` int main(void) { // your code goes here char string[10]={0x31, 'a', 0x33,0x34, 0x35, 0x00,0x39, 0x40, 0x42,'\0'}; printf("%.*s\n", 5, string); printf("%.*s\n", 10, string); return 0; } ``` Output :1a3451a345 Note : I can print char by char and it works but it is too slow when dealing in MBs
You can always try to usefwriteto simply write a block of data to either a file or stdout. But note, when writing to stdout the zero will not be shown, because cmd/terminal don't have a character assigned to it (as far as I know). ``` fwrite (string , sizeof(char), sizeof(string), stdout); ``` If you write to a file, the data (even the zeros) should be printed to your file and stored, so that should not be an issue if you wish to reuse it later.
Please help me, why is identifier "size3" is undefined? ``` if (size1 > size2) { int size3 = size1; } else { int size3 = size2; } int *array3 = malloc(sizeof(int) * size3); ```
You must declare the variable (size3) in a scope where it can be accessed. In your case just declare this (int size3;) in outside and before calling if condition. then just assign values. It will solve the problem. ``` int size3 ; if (size1 > size2) { size3 = size1; } else { size3 = size2; } int *array3 = malloc(sizeof(int) * size3); ```
I'm writing FS with FUSE, here are the functions I've implemented: createopenreadwritereleaseunlinkmkdiropendirreaddirreleasedirrmdirgetattrrename Everything works fine, except this case: when I first trycat>a(when a file still does not exist) it works fine: creates "a" and lets me write something in it. But when I type againcat>aIt tells me-bash: a: Function not implemented. (Similar message appears when I try to modify file withnano ait opens let's me write in, but after trying to save modifications the same message appears innano) What can be the cause? Which function may I me missing? Or which function may be implemented not properly?
Unless the mount was done with theatomic_o_truncoption, you need to implementtruncate()foropen()withO_TRUNC(as is used when opening a file with>rather than>>) to succeed.
``` int main(void) { printf("Hello, world! \n"); fork(); return 0; } ``` why it is print only 2 hello worlds? if evert time when the system excute the function fork() new procces is created, it need to print "Hello, world! \n" forever?
This Program should be printingHello worldonce. still if it prints it twice it is because theline bufferis not cleared.The line buffer should be cleared because there is\nin your printf.still its not cleared means this is about the platform you are using to execute the code.You can verify this by addingfflush(stdout)after theprintf(). ``` int main(void) { printf("Hello, world! \n"); fflush(stdout); fork(); return 0; } ```
How can I xor two data segments pointed by pointers? I've tried this, one based on a similar solution on stackoverflow, but the output is not what I expected. Here is the code: ``` void printXor(){ int j; char* c = strdup("hey"); for(j = 0; j < strlen(c); j++){ c[j] ^= c[j]; } printf("%d\n", *(int*)(c)); } ``` But the output is:7955712. Shouldn't the output be 0? I'm xoring "hey" over "hey" and its value in int is 0 right?
Take a look at this loop: ``` for(j = 0; j < strlen(c); j++) { c[j] ^= c[j]; } ``` You are modifyingcand calculating its length usingstrlen. After the first iteratorstrlenreturns 0 and loop stops. If you translate7955712to hex it is0x796500. 0x79 is a code for'y'and0x65is a code for'e'and the least significant byte is0x00. Since you are running this on a little endian machine, you get an empty string.
This question already has answers here:How to check the value of errno?(3 answers)Closed5 years ago. I'm using syscallstat, it returns 0/-1. When -1 is returned it means, error occurred and errno is set as it should be (source:man 2 stat). But I want to access errno and print it, how to do that?
You can get it fromerrno. Also you can print the error usingstrerror
i have conditional operator's statement and i have no idea how its works. there are two questions: Question 1 :what will the following statement do : ``` quotient=(b==0)?0:(a/b) \\ here a,b,quotient is integer ``` Question 2 :Can preceding statement be written as follow ? ``` quotient=(b)?(a/b):0; ``` NOW MY QUESTION IS : Question:1 ::we do not know b's value then how can we check this condition(b==0) Question 2::what (b) indicate ?
The conditional check in the C ternary conditional operator is an implicit comparison to not-zero. In other words ``` quotient = b ? a / b: 0; ``` is the same as ``` quotient = b != 0 ? a / b : 0; ``` or the absurd ``` quotient = (b != 0) != 0 ? a / b : 0; ``` This is consistent throughout C, e.g. in anif, aforstopping condition, awhile,&&,||, &c.
This question already has answers here:How dangerous is it to access an array out of bounds?(12 answers)Closed5 years ago. ``` #include<stdio.h> #include <stdlib.h> int *ip_range ; int main() { ip_range = (int *) malloc(1); ip_range[0]=2; ip_range[10]=2; ip_range[20]=2; ip_range[33787]=12444; printf("%d\n", ip_range[33787]); } ``` I have malloc just 1 block then why it is accessible till 33787 and generating core on 33788.
You are writing to memory which you do now own i.e. was not handed back bymalloc,callocorrealloc. This results inundefined behaviour. Your program can do anything at all, including not producing any error message or core dump.
i'm recording with VUG and receive this error when click a button to acces to another page. here is my configuration: If someone know how to solve it, thanks in advance.
go under recording options and set a new connection. Any server, all Ports (value 0) and go further with the settings (direct/proxy etc.). If you are not sure which settings you should use just try and edit them as long as the record is empy
``` if((nbytes=mq_receive (qid_recv, (pchar_t)in_buffer, msg_buffer_size, NULL)) != -1) { printf("nbytes is %ld\n", nbytes); }else{ perror("recv_data"); printf("nbytes is %ld\n", nbytes); ``` How to exit from the mq_receive if there is no message is received.Is there any possiblity for give a timeout.Thanks for your time.
In addition tomq_timedreceive(), you can also set theO_NONBLOCKwhen you open the queue withmq_open(). Perthemq_open()documentation: O_NONBLOCKDetermines whether anmq_send()ormq_receive()waits for resources or messages that are not currently available, or fails with errno set toEAGAIN; seemq_sendandmq_receivefor details. Perthemq_receive()documentation: If the specified message queue is empty andO_NONBLOCKis set in the message queue description associated withmqdes, no message shall be removed from the queue, andmq_receive()shall return an error.
i'm recording with VUG and receive this error when click a button to acces to another page. here is my configuration: If someone know how to solve it, thanks in advance.
go under recording options and set a new connection. Any server, all Ports (value 0) and go further with the settings (direct/proxy etc.). If you are not sure which settings you should use just try and edit them as long as the record is empy
``` if((nbytes=mq_receive (qid_recv, (pchar_t)in_buffer, msg_buffer_size, NULL)) != -1) { printf("nbytes is %ld\n", nbytes); }else{ perror("recv_data"); printf("nbytes is %ld\n", nbytes); ``` How to exit from the mq_receive if there is no message is received.Is there any possiblity for give a timeout.Thanks for your time.
In addition tomq_timedreceive(), you can also set theO_NONBLOCKwhen you open the queue withmq_open(). Perthemq_open()documentation: O_NONBLOCKDetermines whether anmq_send()ormq_receive()waits for resources or messages that are not currently available, or fails with errno set toEAGAIN; seemq_sendandmq_receivefor details. Perthemq_receive()documentation: If the specified message queue is empty andO_NONBLOCKis set in the message queue description associated withmqdes, no message shall be removed from the queue, andmq_receive()shall return an error.
This question already has answers here:Array increment operator in C(7 answers)Closed5 years ago. The code gives me the error: lvalue required as increment operand But if I incrementstrby 1 it must point to the next character in the string. ``` #include <stdio.h> #include <stdlib.h> int main() { char str[50]; scanf("%s", str); while(*str != 0) { printf("%c", *str); str++; } return 0; } ```
stris not a pointer but an array. In many cases, the array decays to a pointer to its first element, but that doesn't make it a pointer itself.
here are includes and my function: I'm trying to copystbuf->st_modein buffer withmemcpyand when reading it back, value is not what I was trying to copy. ``` #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/stat.h> #include <string.h> void r1_getattr(char* pth, int cfd){ struct stat* stbuf = malloc(sizeof(stat)); int res = stat(pth, stbuf); printf("(%3o)\n", (stbuf->st_mode)&0777); char* wbuf = malloc(256); memcpy(wbuf, &(stbuf->st_mode), sizeof(mode_t)); printf("(%3o)\n", (*(mode_t*)((char*)wbuf))&0777); } ``` outputs: "(775)" and "( 21)" shouldn't they be the same?
Simple typing error: Replace ``` struct stat *stbuf = malloc(sizeof(stat)); ``` with ``` struct stat *stbuf = malloc(sizeof(struct stat)); ``` Always funny to see the weird results we get when we use un-initialized memory :-)
In C11 it is legal to write, for instance: ``` int b = (some_function_returning_void(), 1020); ``` And you'll get back 1020. But it won't let you write: ``` int b = (_Static_assert(2 > 1, "all is lost"), 304); ``` gcc returning ``` error: expected expression before '_Static_assert' ``` And it would be inconvenient to use_Static_assertoutside of an expression sometimes since you're out of luck with preprocessor macros-based pseudo-functions that verify their arguments then.
This is doable in ISO C11. The trick is to put_Static_assertin a struct declaration, in a sizeof expression: ``` sizeof(struct { _Static_assert(0, "yay it failed"); int dummy; }) ``` The dummy field is necessary becauseempty struct is a GNU extension, according toclang -std=c11 -Weverything.
How can I define a directive as an other directive in C ? ex : I want to define ``` #define #warning #warn ``` I get an error ``` error #41: expected an identifier ``` for compilers and targets for example, some compilers recognize#warningand other recognize#warn. I already have a way to do this but I want to make it generic ``` #if PLATFORMS_TOOLCHAIN == PLATFORMS_ticgt #warn "RAM is not initialized at startup, test will possibly fail" #else #warning "RAM is not initialized at startup, test will possibly fail" #endif ```
There's no way to create your own preprocessor directives. The#definedirective allows you to define new source symbols only. What you're currently doing is the proper way to handle differing directives on different compilers.
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.Closed5 years ago.Improve this question I had the following question for my C exam: What should you write in place of 'condition' to print the statement 'I love food' in just one execution? You cannot add any more code. ``` if(condition) printf("food"); else printf("I love"); ```
You can changeconditiontoprintf("I love ").printfreturns the number of printed characters, which will be 7, so the condition is true. ``` if (printf("I love ")) printf("food"); else printf("I love"); ```
``` #define LODWORD(x) (*((unsigned int*)&(x))) ``` I'm translating C code to python and can't quite get this. If anyone can explain how to read this or what it means it'd be greatly appreciated.
It's a macro for getting the lowerDWORD( 32bits ) of a 64 bit variable, there's most likely an associatedHIDWORDmacro as well to get the higher 32 bits. Other comments have pointed out some flaws with the macro, but it's a fairly common idiom for accomplishing this. Some equivalent Python code might be: ``` def LODWORD(x): return x & 0xFFFFFFFF ```
According tothe manual, GNU complexity scores look like this: ``` Score | ln-ct | nc-lns| file-name(line): proc-name 3 13 12 tokenize.c(507): skip_params 3 15 13 score.c(121): handle_stmt_block 3 22 17 tokenize.c(64): check_quote ``` Can anyone confirm ifln-ctmeans line count and explain whatnc-lnsmeans?
Why I didn't just test this, I don't know. Anyway, from messing around with a source file I can confirm: ln-ct= line countnc-lns= non-comment lines Leaving this here in case it's helpful - the manual doesn't describe these terms.
How can I make two threads to wait for each other till they complete one loop each using pthreads? ``` void* th1Fn() { while(1) { //do something printf("I'm done"); //signal that i'm done //wait for thread2 so that I can repeat the cycle } } void* th2Fn() { while(1) { //do something printf("I'm done"); //signal that i'm done //wait for thread1 so that I can repeat the cycle } } ```
You are looking forpthread_barrier_wait:http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_barrier_wait.html And here is a documented example for this function:http://man7.org/tlpi/code/online/dist/threads/pthread_barrier_demo.c.html
I have the following code: ``` int i = 0; char ar[500]; while(i < 20) { printf("Type a line: "); fgets(ar, 500, stdin); fprintf(fp,"%s", ar); i++; } ``` Basically, i am trying to open a file, then take 20 lines of input from the user and store it in an array, then print it to the file. It works fine but i don't understand how fgets works in the while loop. As i understand, when i = 0, fgets stores the 1st line to ar[500] and fprintf prints it out to the file, when i = 1, fgets stores the 2nd line to ar[500], but now ar[500] has 2 lines, but why fprintf only prints the 2nd line to the file but not all the 2 lines and so on when i increment by 1.
fgets always start populating the array at arr[0]. At every iteration, the previous line is overwritten. fgets will add the null terminating character for you in arr, so only the currently read line will be outputed to FILE pointed to by fp.
``` typedef struct flag { int8_t (*valid)(Flag flag); const uint8_t requiresValue; const char* name; uint8_t active; char* value; } Flag; ``` How do i have the parameter for *valid be Flag inside the struct?
The typedef you are looking for is as follows: ``` typedef struct flag { int8_t (*valid)(struct flag flag); const uint8_t requiresValue; const char* name; uint8_t active; char* value; } Flag; ``` I changedFlagtostruct flag. Note the lowercaseflagdue to the first linetypedef struct flag.
I need to make a linked list out of a txt file like this: ``` 1 Some 1.5 G 2 Thing 2.3 F 3 Another 6.7 B ``` and the list is: ``` typedef struct list{ int code; char name[255]; float price; char letter; struct list *next; }List1; ``` But how can I select the specific parts in the file and put in the right spot of the list ignoring the space? Sorry for the stupid question, I'm a newbie in programming.
First of all you have to open the file with fopen(), assign the return value to a pointer. Then select your function to read your file(as @Karthick ) mentioned fe. fgets or sscanf. Store the values in temporary variables and assign them to the struct elements. Like: ``` list.price = tempVar; strcpy(list.name,tempString); ```
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.Closed5 years ago.Improve this question What does the following code segment do? ``` #include <stdio.h> #include <stdlib.h> int main(){ int num=0; while(malloc(1<<10)) ++num; } ```
First of all,1<<10is an expression that can be calculated at compile time, and it equals 1024. So your code is equivalent to ``` #include <stdlib.h> int main() { int num=0; while(malloc(1024)) ++num; } ``` So what it does is to allocate chunks of 1024 bytes of memory until it fails to do so. Each time, the value ofnumis increased by one. Overflowing the variablenumwill causeundefined behaviorbecause it is signed. However, since you are not using the variable, it is likely to be optimized away.
``` #include<stdio.h> #include <stdlib.h> int main () { int i; printf ("%d", scanf ("%d", &i)); } ``` while using the scanf function in printf statement,when i give any integer as input it prints only 1. Input:5 output:1 i am beginner in c ,so kindly help. can any one explain this program ?
scanf()returns number of receiving arguments successfully assigned or EOF in case of failure. Read more about scanf()here. In context of your program, when you give input5thescanf()successfully assign it to receiving argumentiand since the receiving argument is1,scanf()is returning1which is getting printed. Hence you are getting output1.Try to give a character as input and check the output.
What is the difference betweenint variable;andint variable = 0;? I've seen them both used, and, if I recall correctly, by the same author in the same file. As far as I can tell, they're the same: ``` $ cat integers.c #include <stdio.h> int main(void) { int patty; int tim = 0; printf("Patty: %d\nTim: %d\n", patty, tim); } $ gcc integers.c -o integers $ ./integers Patty: 0 Tim: 0 ``` This goes for other variable types, too: what is the difference betweenchar *variable;andchar *variable = NULL;?
As far as I can tell, they're the same No they are not. Accessingpattyis undefined beavior because it is not initialized.You just happen to get same result. Ifpattywere global, then it would have been default initialized(0).
I am dealing with application that requires certain signal to be blocked in every thread. Said app also dynamically links a library (libcpprest.so) which creates a thread pool during initialization. Naturally, because main executable had no chance to execute any code these threads have that signal unblocked -- which leads to mysterious crashes. Is it possible to block a signal before dynamically linked library has a chance to create a thread? Unacceptable solutions (that I am aware of): link library statically and useinit_priorityto ensure signal is blocked asapuse "starter" utility that blocks signal and starts executable (which will inherit signals mask)
Doesn't seem to be possible -- shared library should block all signals in created threads if it really needs to create a thread so early.
What I'm trying to do would look like this in Python (wherenis float/double): ``` def check_int(n): if not isinstance(n, numbers.Integral): raise TypeError() ``` Since C/C++ are typestrong, what kind of cast-and-compare magic would be the best for this purpose? I'd preferably want to know how it's done in C.
Usefloor ``` #include <cmath> if (floor(n) == n) // n is an integer (mathematically speaking) ```
Even after typecasting to integer type in malloc declaration, the ptr cannot be used without typecasting it explicitly every time whenever I dereference the pointer. Can anyone explain why the pointer is not converted to int* forever after I typecasted it. ``` void *ptr; ptr = (int*)malloc(sizeof(int)); *ptr = 1; // This line does not work even after typecasting in the above line *(int*)ptr = 1; //This line works ```
The issue is the declaration ofptrin your first line. You seem to want it to be ``` int *ptr; /* NOT void* */ ``` Otherwise you will have to cast it every time. C/C++ use compile time declarations and the cast on themallochas no effect after the line on which it appears. In particular ``` ptr = (int*)malloc(sizeof(int)); /* the (int*) HAS NO EFFECT when ptr is declared void* */ ```
How can I declare a multibyte character array in which each is character is represented for 3 or 4 bytes? I know I can do:char var[] = "AA";which will write to memory6161and I can dowchar var[] = L"AA";which will do00610061. How can I declare a wider character array in C or C++? Is there any other prefix like theLto instruct the compiler to do so?
Both C and C++ offerchar32_t. InCchar32_tis a typedef of/same type asuint_least32_t. InC++char32_thas the same size, signedness, and alignment asstd::uint_least32_t, but is a distinct type. Both of them can be used like ``` char32_t string[] = U"some text"; ```
Is it possible to create a window without it showing up on taskbar in X11 using c?
That depends on GUI toolkit you are using. For example, GTK+ providesgdk_window_set_skip_taskbar_hintfunction. If you don't use any GUI toolkit and directly interface X11, you need to add_NET_WM_STATE_SKIP_TASKBARatom to_NET_WM_STATEproperty.
Is it possible to create a window without it showing up on taskbar in X11 using c?
That depends on GUI toolkit you are using. For example, GTK+ providesgdk_window_set_skip_taskbar_hintfunction. If you don't use any GUI toolkit and directly interface X11, you need to add_NET_WM_STATE_SKIP_TASKBARatom to_NET_WM_STATEproperty.
As statedin pipe's Linux man page, given a pipe/FIFO that was opened properly for reading & writng, if the write end is closed, then "an attempt to read(2) from the pipe will see end-of-file (read(2) will return 0)". My question is, let's say I've written some data to the pipe (which should now be stored in a kernel buffer), and I've then closed the writing end before the reading end managed to read the data, will a following attempt to read from the file still automatically get EOF, or will the reader be able to first read the data in the kernel buffer and only afterwards get EOF?
The data still in the pipe is read first before an EOF is signaled.
I have started to do some research about Lua and I got pretty confused about howembeddedLua works: It says that You'll also need a C or C++ compiler for your program, because the Lua headers and library are written in C. So that means, that I only need a C/C++ compiler for executing Lua, because the library and headers are written in C. That means that all the libraries I write and/or use are C-Code? I probably misunderstood that, but for me that would mean: I write some code in Lua and it gets translated into C-code before it is compiled? Or is there a difference between what I import as library and write as "Lua-Code"?
Those instructions are for embedding Lua into your C or C++ program. In that case, you need to interact with the C API for Lua to run Lua scripts inside your program. If you want to program in pure Lua, you just need the Lua interpreterlua. Lua scripts are not converted to C before execution.
For example, can I do this: ``` int i, number_of_values, variable[i]; printf("Enter the number of values you would like to insert: \n"); scanf("%d", &number_of_arrays); for (i=0; i<number_of_values; i++) ``` Instead of using a method like this: ``` printf("Enter the number of values you would like to insert: \n"); scanf("%d", &number_of_values); int variable[no_of_values]; ``` Is it possible? Thanks!
An array is just a chunk of contiguous memory of specified size. To allocate an array youmustspecify its size. However, there are instances where you may not know the size required in advance. For those situations, we have dynamic memory malloc. You may allocate the required memory at run-time usingmalloc. ``` int* a; a=(int *)malloc(sizeof(int)*required_size); ``` And then access this memory as easily as you did for array e.g.a[i]or by dereferencing e.g.*(a + i)
Thecallocfunction in C is used to allocate zeroed memory capable of holding at least the requested amount of elements of a specified size. In practice, most memory allocators may allocate a bigger block in order to increase efficiency and minimize fragmentation. The actual usable block size of an allocation in such systems is usually discoverable by means of special functions, i.e._msizeormalloc_usable_size. Willcallocmake sure the entire usable block is zeroed, or will it only zero the requested count*size part of the allocation?
It's only guaranteed to zero out the requested allocation. You shouldneverrely on over-allocation.
This question already has answers here:Why does scanf ask twice for input when there's a newline at the end of the format string?(7 answers)Closed5 years ago. I just started learning c. I have a code here for taking input from users and printing it. ``` #include <stdio.h> #include <stdlib.h> int main() { int a[5]; int i ; for(i=0;i<5;i++) { printf("enter the %d position no: ",i+1); scanf("%d \n",&a[i]); } for(i = 0;i<5;i++) printf("position %d : %d \n",i+1,a[i]); } ``` Here is my output console. But the output is giving misleading result. at line 2 when scanf is reding it is not showing the string "enter the %d position" it is directly asking for value.
Yourscanfdoesn't need the space and the newline character, just"%d". ``` for(i=0; i<5; i++) { printf("enter the %d position no: ",i+1); scanf("%d",&a[i]); } ```
I often see tutorials about ellipsis with examples like this: ``` void foo(int i, ...){ int *p = &i; ++p; //... } ``` And I'm just wondering, is this approach correct in terms of standard? Can I use variadic args without va_* macros? Maybe some implementations store args in reversed order, or something like this. UPD:"Use" = pass args portably and reliably
The mechanism for how parameters are passed to a function is very implementation specific. They could be passed on the stack, via registers, or some other method, and the method can differ based on the datatype. The stdarg family of functions / macros (va_start,va_arg,va_end, etc.) specified in section 7.16 of theC standardabstracts away all this and is theonlystandard compliant way of handling variable arguments lists.
This question already has answers here:Flexible array member not getting copied when I make a shallow copy of a struct(2 answers)Closed5 years ago. I'm currently learning c structure, especially structure with flexible array member. Given a structure flexible array ``` struct flex { size_t count; double average; double scores[]; // flexible array member }; ``` I have been told not to use assignment for copying I'm not sure why this operation only copy the non-flexible member of the structure. Could someone please explain to me the underlying reasons why this is the case?
The size of the structure doesn’t count the FAM. The compiler has no way to know how big the FAM is. Consequently, any copy ignores the FAM. Since that’s very seldom the desired behaviour, don’t use structure copying on structures with a FAM.
Consider: ``` int a; a = -3--3; printf("%d", a); ``` The 2nd line(a = -3--3)produces a compile time error.On adding an extra pair of brackets as follows: ``` int a; a = -3 - (-3); printf("%d", a); ``` the error disappears. Since the brackets remove the error I believe that some ambiguity must have caused it. But I don't see why the compiler is confused. I try to subtract-3from-3. All help is appreciated.
C has a unary decrement operator that's spelled--, and a "maximal munch rule" that makes it recognize that operator rather than a minus sign and a negative sign even where the latter would make more sense. For about half a dozen accompanying reasons,3 -- 3doesn't make sense, and you get an error. If you'd saida = -3 - -3;, instead of cramming everything together like your space bar's broken, you'd have been fine. :P A space between the two operators keeps C from seeing a--.
The question comes when I tried to make a macro like this: ``` #define OP1(a,b,op) (a) op (b) ``` then I was wondering why not also put op into parentheses, as it is also a macro parameter. I then find I cannot even have this: ``` 1 (+) 1; ``` otherwise there will be error: ``` error: expected primary-expression before ')' token ``` Can anyone tell me where is the rule saying operator cannot be in parentheses? I really cannot find it. Thank you.
§ 7.6.6(expr.add) defines "additive expressions" as: ``` additive-expression: multiplicative-expression additive-expression + multiplicative-expression additive-expression - multiplicative-expression ``` No parens around the operator allowed.
I have a 3 dimensional array and want to create a pointer to the 2nd dimension. ``` uint32_t m0[4096][256][8]; uint32_t (*m1)[256][8] = &m0[0]; uint32_t *m2 = m1[2]; //<- warning: initialization from incompatible pointer type // do something with m2[0], m2[1].... m2[7] ``` Obviously there is something with the above code. What is it?
m1[2]is*(m1+2).Type of*(m1+2)is the same as the type of*m1, which isunit32_t [256][8]. For that reason, the following line is wrong. ``` uint32_t* m2 = m1[2]; ``` What you need to use is: ``` uint32_t* m2 = (*m1)[2]; ```
Code: ``` #include <stdio.h> void main() { FILE *ptr; char buff[255]; ptr = fopen("Test.txt", "w+"); if (ptr != NULL) { printf("Success\n"); } fputs("Hello", ptr); fgets(buff, 255, (FILE *)ptr); printf("%s", buff); fclose(ptr); } ``` The file "Text.txt" has the content "Hello" when I opened it, but I just can't print it out withfgets. What did I do wrong here?
You didn't rewind the file before reading.fseek(ptr, 0, SEEK_SET);orrewind(ptr);
``` int main() { int f; printf("Type your age"); scanf("%d", &f); if(!isdigit(f)) { printf("Digit"); } else { printf("Is not a digit"); } return 0; } ``` No matter if a typed6oraalways shows me the "Digit" message
isdigit()should be passed acharnot anint. And your if-else logic is reversed: ``` int main() { char f; printf("Type your age"); scanf("%c", &f); if (isdigit(f)) { printf("Digit"); } else { printf("Is not a digit"); } return 0; } ``` As mentioned in the comments, this will only work for a single digit age. Validating input is a major topic under the 'C' tag, a search will reveal many approaches to more robust validation.
The question comes when I tried to make a macro like this: ``` #define OP1(a,b,op) (a) op (b) ``` then I was wondering why not also put op into parentheses, as it is also a macro parameter. I then find I cannot even have this: ``` 1 (+) 1; ``` otherwise there will be error: ``` error: expected primary-expression before ')' token ``` Can anyone tell me where is the rule saying operator cannot be in parentheses? I really cannot find it. Thank you.
§ 7.6.6(expr.add) defines "additive expressions" as: ``` additive-expression: multiplicative-expression additive-expression + multiplicative-expression additive-expression - multiplicative-expression ``` No parens around the operator allowed.
I have a 3 dimensional array and want to create a pointer to the 2nd dimension. ``` uint32_t m0[4096][256][8]; uint32_t (*m1)[256][8] = &m0[0]; uint32_t *m2 = m1[2]; //<- warning: initialization from incompatible pointer type // do something with m2[0], m2[1].... m2[7] ``` Obviously there is something with the above code. What is it?
m1[2]is*(m1+2).Type of*(m1+2)is the same as the type of*m1, which isunit32_t [256][8]. For that reason, the following line is wrong. ``` uint32_t* m2 = m1[2]; ``` What you need to use is: ``` uint32_t* m2 = (*m1)[2]; ```
Code: ``` #include <stdio.h> void main() { FILE *ptr; char buff[255]; ptr = fopen("Test.txt", "w+"); if (ptr != NULL) { printf("Success\n"); } fputs("Hello", ptr); fgets(buff, 255, (FILE *)ptr); printf("%s", buff); fclose(ptr); } ``` The file "Text.txt" has the content "Hello" when I opened it, but I just can't print it out withfgets. What did I do wrong here?
You didn't rewind the file before reading.fseek(ptr, 0, SEEK_SET);orrewind(ptr);
``` int main() { int f; printf("Type your age"); scanf("%d", &f); if(!isdigit(f)) { printf("Digit"); } else { printf("Is not a digit"); } return 0; } ``` No matter if a typed6oraalways shows me the "Digit" message
isdigit()should be passed acharnot anint. And your if-else logic is reversed: ``` int main() { char f; printf("Type your age"); scanf("%c", &f); if (isdigit(f)) { printf("Digit"); } else { printf("Is not a digit"); } return 0; } ``` As mentioned in the comments, this will only work for a single digit age. Validating input is a major topic under the 'C' tag, a search will reveal many approaches to more robust validation.
I'm trying to use the following code but i'm not sure where the issue is, I'm trying to make a function that sums 2 variables and call it later on in the program ``` #include <stdio.h> #include <stdlib.h> void func(int sum) { int a; int b; int sum = a+b; printf("sum is %d", sum); } int main() { printf("Enter a:\n"); scanf("%d", &a); printf("enter b\n"); scanf("%d", &b); return func(sum); } ```
You need to pass in a and b to your sum function, and not declare them as local variables. ``` #include <stdio.h> #include <stdlib.h> void sum(int a, int b) { int sum = a+b; printf("sum is %d", sum); } int main() { int a, b; printf("Enter a:\n"); scanf("%d", &a); printf("enter b\n"); scanf("%d", &b); sum(a,b); } ```
I've got the unix time since January 1st 1970 (E.G 1531074816) from my GPS module, how do I convert this into a readable format? I only need to get the current hour, minutes and seconds. I'm not worried about the day or date. I'm also using C. Thanks.
use gmtime ``` #include <stdio.h> #include <time.h> int main() { static const time_t unixtimestamp = 1230728833; struct tm *tmp = gmtime(&unixtimestamp); printf("%02d:%02d:%02d\n", tmp->tm_hour, tmp->tm_min, tmp->tm_sec); return 0; } ```
I need to do so because I am supposed to stub this function for unit testing. I am using gcc version 5.4.0. for a lot of other functions that exist in glibc like memcpy I simply wrote the implementation in my .c file and then this implementation was the one used instead of the original, but in case of strdup and some other function I get a compilation error like this one: ``` error: expected identifier or ‘(’ before ‘__extension__’ char* strdup (const char *__s) ``` I know this is because I am trying to use a function name that already exist in string.h although it works with some other functions in their as well. I wish to know if it is possible to bypass this somehow.
Looks like in your case the originalstrdupis a preprocessor macro, not an actual function. You can try to get rid of it: ``` #undef strdup char *strdup(const char *s) { // your code goes here } ```
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed5 years ago.Improve this question I tried reading a string with leading white spaces in C. I used"%[^\n]%*c"too but couldn't get leading white spaces. input:" Language"output:" Language" Can anyone tell me how to read a string with leading white spaces in C?I am getting like this. But I want output same as input
If you need to read lines with significant spaces, definitely usefgets()instead ofscanf. Note in particular thatscanf("%[^\n]%*c", buf)fails on empty lines and may cause undefined behavior on invalid input, just likegets().
I need to do so because I am supposed to stub this function for unit testing. I am using gcc version 5.4.0. for a lot of other functions that exist in glibc like memcpy I simply wrote the implementation in my .c file and then this implementation was the one used instead of the original, but in case of strdup and some other function I get a compilation error like this one: ``` error: expected identifier or ‘(’ before ‘__extension__’ char* strdup (const char *__s) ``` I know this is because I am trying to use a function name that already exist in string.h although it works with some other functions in their as well. I wish to know if it is possible to bypass this somehow.
Looks like in your case the originalstrdupis a preprocessor macro, not an actual function. You can try to get rid of it: ``` #undef strdup char *strdup(const char *s) { // your code goes here } ```
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed5 years ago.Improve this question I tried reading a string with leading white spaces in C. I used"%[^\n]%*c"too but couldn't get leading white spaces. input:" Language"output:" Language" Can anyone tell me how to read a string with leading white spaces in C?I am getting like this. But I want output same as input
If you need to read lines with significant spaces, definitely usefgets()instead ofscanf. Note in particular thatscanf("%[^\n]%*c", buf)fails on empty lines and may cause undefined behavior on invalid input, just likegets().
This question already has answers here:How to read asterisk( * ) as an argument from the command line in C [duplicate](3 answers)argv: Sanitizing wildcards(2 answers)Closed5 years ago. I am trying to write a C code that will take three arguments from the command line in the form of{num1} {operator} {num2}. It is working fine in case of all operator symbols other than*. This is the code to verify this: ``` #include <stdio.h> int main(int argc, char const *argv[]) { printf("%d\n", argc); } ``` I am compiling this asgcc test.c -o test. Then when I run it using./test 5 + 9, it gives the expected output4. But then when I run./test 5 * 9, it gives25as output. What am I doing wrong here?
The*is expanded by the shell into a list of all files in the current directory. If you don't want shell-expansion you need to (single) quote the argument: ``` ./test 5 '*' 9 ```
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.Closed5 years ago.Improve this question Anyone know of a C IDE that lists the declared functions in the code on a sidebar? It would be nice to click to go directly to the function instead of scrolling a lot. The code I work with is unfortunately a bit monolithic.
Of course, Eclipse is capable to show your code outline in the outline view. See here:https://help.eclipse.org/oxygen/index.jsp?topic=%2Forg.eclipse.platform.doc.user%2Fconcepts%2Fcoutline.htm
As I've understood from the answers tothis related question, an uninitialized pointer can contain pretty much anything and could therefore also happen to equal toNULL. Is there a way to distinguish uninitialized pointers from null pointers, for example by giving them a specific value? For example, consider: ``` // could potentially print FILE *f1; if (f1 == NULL) fprintf(stderr, "f1 is NULL"); // will never print, but is this a good/safe way? FILE *f2 = -1; if (f2 == NULL) fprintf(stderr, "f2 is NULL"); ```
You can't. An uninitialised value could be anything. An uninitialised pointer could point anywhere. It could even point to valid data by sheer coincidence. Initialise your pointers toNULLor a real value; if you ever find yourself seeing uninitialised values then a programmer somewhere has done something wrong.
This question already has answers here:Precedence of && over || [duplicate](4 answers)Closed5 years ago. ``` #include <stdio.h> int main(void) { int a = 0, b = 0, c = 0; ++a || ++b && ++c; printf("%d %d %d", a, b, c); return 0; } ``` The outputs are1,0,0by gcc 8.1.0. The&&‘s precedence should higher than||. Why are thebandcare still0?
The expression++a || ++b && ++cisgroupedas++a || (++b && ++c).But, the right hand side of||is only evaluated if++ais0, which it isn't.
In the functionstruct page *rmqueue(..)I am extracting the physical address usingpage_to_phys(page)and the linear address (also called asvirtual address) usingpage_address(page). My question is how do I extract the logical address generated by the OS so that I can complete my mapping overview from Logical ---> linear ---> Physical address space. Is it just an offset for the x86 that I need to subtract from the segmantation unit or is it something else?
So on surfing through the code, I found a function calledstruct page * alloc_pages_vma(gfp_t gfp, int order, struct vm_area_struct *vma, unsigned long addr, int node, bool hugepage)inmm/mempolicy.con my linux kernel 4.14.4+The parameter unsigned long addr is the logical address. The page can be accessed from the function from which the physical address and the linear address(virtual) can be extracted too with the functions already mentioned in the question.
Given the variable enc_out as the output of an AES256 encryption algorithm, and the function: ``` static void hex_print(const void* pv, size_t len) { const unsigned char * p = (const unsigned char*)pv; if (NULL == pv) printf("NULL"); else { size_t i = 0; for (; i<len;++i) printf("%02X ", *p++); } printf("\n"); } ``` Which is used to print the output AES256 encryption in hex, How can I change the above function to output the hex to a file?
Usefprintf()instead ofprintf(), and pass an additionalFILE *parameter: ``` static void hex_print(FILE *out, const void* pv, size_t len) { // ... fprintf(out, "%02X ", *p++); // ... ``` When calling this, pass an openedFILE *forout. You can also passstdoutorstderr, so this will be more flexible anyways.
I implement DTLS protocol for CoAP on C, C++. As I see I can use OpenSSL or WolfSSL. For example WolfSSL: https://github.com/wolfSSL/wolfssl-examples/blob/master/dtls/client-dtls-nonblocking.c But how I can detect that some message has been sent to me?
In nonblocking operation, you typically have a point in the program where it waits for any of the nonblocking file descriptors to report availability of data. In the example you linked, that's theselect(...)line. In practice, you either have such a central select yourself, or have the main loop run by another library to which you pass the descriptors of whose readiness you want to be notified (eg. in GTK that might beg_source_add_unix_fd).
I have got the following union: ``` typedef union { struct { uint8_t LSB; uint8_t MSB; }; int16_t complete; }uint16ByteT; ``` Know I want to use my type and initialize the variable. After scanning SO ( I thought) I found the solution: ``` uint16ByteT myVariable = {0}; ``` But my compiler gives me an Error message: simple type required for "@" Normally the xc8 compiler uses the "@" to bring a variable at a specific address.
To initialize an anonymstruct/unionyou can use: ``` uint16ByteT myVariable = {{0}, .complete = 0}; ``` or simply ``` uint16ByteT myVariable = {{0}}; ``` Noticeuint16ByteTinstead ofuint16Byte Also notice that you need to compile in C11 mode since anonymstructs/unions was introduced in this version.
I have a process that works in a loop good except when any key is accidentally pressed in the keyboard, in which case, the program crashes. I still need to debug this but it is basically caused by the function poll(). I am not sure yet why this happens, but I would like to unbind all the key strokes happened in the terminal so they are not sent to the process and this crash will not occur. How can I do that? Thank you.
It's possible that there is a STDIN_FILENO descriptor in your pollfd set.
I'm a bit confused about a thing : If I have an array of structs:tablewhith a length ofXand I want to access the last element of it:table[X]ortable[X-1]. If it'stable[X-1], whattable[X]contains ?
The indexing of array in C starts with zero, i.e. the first element will be intable[0], the second intable[1], the third intable[2]... and the last on intable[X-1]. table[X]is outside of the arrays bounds. C does not have bounds checking, so compiler allows accessing it, but this is an undefined behaviour, i.e. you will never know what happens. Reading it can give back memory garbage or can lead to an OS exception like segmentation fault.
I'm developing Linux kernel character driver and in read function I sleep in a loop until I get a data from the hardware. If I kill an user application while it is blocked in read syscall, the application is still working before I return from read syscall. Is there a possibility to determinate in the driver that the application is terminated, so I can return from the loop?
When you are waiting for the data you should add your process to waiting queue (add_wait_queue()) then use set_current_state(TASK_INTERRUPTIBLE) and invoke schedule(). When the data comes in - it should be somehow recognized - for example using some interrupt and then wake up the sleeping task (wake_up()). There are plenty examples in kernel sources. In other words - in read function you need to go to sleep when there is no data and in some other path (interrupt) you need to wake up this read function. Better don't do the busy waiting in read function.
I just didn't get it, why the time complexity is O(n^2) instead of O(n*logn)? The second loop is incrementing 2 each time so isn't it O(logn)? ``` void f3(int n){ int i,j,s=100; int* ar = (int*)malloc(s*sizeof(int)); for(i=0; i<n; i++){ s=0; for(j=0; j<n; j+=2){ s+=j; printf("%d\n", s); } free(ar); } ```
By incrementing by two, rather than one, you're doing the followingN*N*(1/2). With big(O) notation, you don't care about the constant, so it's still N*N. This is because big(O) notation reference the complexity of the growth of an algorithm.
This question already has answers here:Why is “while( !feof(file) )” always wrong?(5 answers)Closed5 years ago. I know this is an easy problem but i can't figure out how to solve this. I was learning about file and when i tried to read a file, it went on in an infinite loop. Here is my code: ``` int main() { FILE *p; p = fopen("123.txt", "r"); char ar[150]; while(!feof(p)) { fgets(ar, 150, p); puts(ar); } fclose(p); return 0; } ```
You need this: ``` #include <stdio.h> int main() { FILE *p = fopen("data.txt11", "r"); if (p == NULL) { printf("File could not be opened.\n"); return 1; } char ar[150]; while (fgets(ar, 150, p) != NULL) { puts(ar); } fclose(p); return 0; } ```
I want to make the for loop execute the code in the beginning. However, my beginning state is same as my ending state. Is there any way I can execute the code without writing it before the loop? ``` for(int i = queue1->front; i%queue1->size != queue1->front; i++) { //some code } ``` In the code, I am using a circular array and I want to print that using a loop.
Aside from using a do-while-loop you could use a flag to enter the loop in any case like this: ``` int first = 1; for (int i = queue1->front; i%queue1->size != queue1->front || first; i++){ first = 0; //some code } ``` You can even integrate it directly into the for loop header, if you like: ``` for (int i = queue1->front, f=1; i%queue1->size != queue1->front || f; i++, f=0) { ```
This question already has answers here:What does strcmp() exactly return in C?(6 answers)Closed5 years ago. I was just trying to execute this program in code blocks and i got an output of 0,1,-1 , in some other compiler i got result 0,4,-1 but according to the working of strcmp() , i should get 0,4,-32 , i am not able to understand why i am getting diferent outputs on different compilers. ``` #include<stdio.h> #include<string.h> int main() { char string1[]="Jerry"; char string2[]="Ferry"; int i,j,k; i=strcmp(string1,"Jerry"); j=strcmp(string1,string2); k=strcmp(string1,"Jerry boy"); printf("%d %d %d \n",i,j,k); return 0; } ```
strcmp()returns value greater than or less than or equal to0. That means it will return0for sure if two strings are equal otherwise it can returnany integer valuegreater or less than0.
This question already has answers here:Undefined behavior and sequence points(5 answers)How to understand function recursion precisely?(4 answers)Closed5 years ago. For example, I have a recursive function which calculate n!. ``` int fact(int n){ if(n==1) return 1; return n*fact(n-1); } ``` My question is why I can't replace n-1 with n--? Or can I replace it with --n?
There are two reasons. One,n--is post-decrement. The value used as the arugment would be the original (non-decremented) value ofn. Two,nis used twice in the expression (once as the left-hand side argument of*, and once within the argument to the recursive call). Neither C nor C++ specify evaluation order in this case, so it would be unclear whether thenis evaluated before or aftern--(or even--n).
How can I resolve the warnings below? ``` FGlobal FctVoid gtmnts PARMLIST((TESPAP, p_var, mantissa, sign), hspacbTp TESPAP .... ) #ifdef ASNFAM1 { (void)TESPAP; ... } ``` unused parameter 'TESPAP'
this is direct way. use --Wunused-value with gcc this will suppress all warnings for unused value in source code.As Sourav mentioned in comment try adding -DASNFAM1 while compiling if you want to conditionally compile it.add#ifdef ASNFAM1at all occurrences. I will recommend third option as it is fail proof. but sometimes we need quick hack so give other 2 a try. Quick suggestion:- try not to ignore/suppress compiler warnings as they are there for a reason.
This question already has answers here:What does strcmp() exactly return in C?(6 answers)Closed5 years ago. I was just trying to execute this program in code blocks and i got an output of 0,1,-1 , in some other compiler i got result 0,4,-1 but according to the working of strcmp() , i should get 0,4,-32 , i am not able to understand why i am getting diferent outputs on different compilers. ``` #include<stdio.h> #include<string.h> int main() { char string1[]="Jerry"; char string2[]="Ferry"; int i,j,k; i=strcmp(string1,"Jerry"); j=strcmp(string1,string2); k=strcmp(string1,"Jerry boy"); printf("%d %d %d \n",i,j,k); return 0; } ```
strcmp()returns value greater than or less than or equal to0. That means it will return0for sure if two strings are equal otherwise it can returnany integer valuegreater or less than0.
This question already has answers here:Undefined behavior and sequence points(5 answers)How to understand function recursion precisely?(4 answers)Closed5 years ago. For example, I have a recursive function which calculate n!. ``` int fact(int n){ if(n==1) return 1; return n*fact(n-1); } ``` My question is why I can't replace n-1 with n--? Or can I replace it with --n?
There are two reasons. One,n--is post-decrement. The value used as the arugment would be the original (non-decremented) value ofn. Two,nis used twice in the expression (once as the left-hand side argument of*, and once within the argument to the recursive call). Neither C nor C++ specify evaluation order in this case, so it would be unclear whether thenis evaluated before or aftern--(or even--n).
How can I resolve the warnings below? ``` FGlobal FctVoid gtmnts PARMLIST((TESPAP, p_var, mantissa, sign), hspacbTp TESPAP .... ) #ifdef ASNFAM1 { (void)TESPAP; ... } ``` unused parameter 'TESPAP'
this is direct way. use --Wunused-value with gcc this will suppress all warnings for unused value in source code.As Sourav mentioned in comment try adding -DASNFAM1 while compiling if you want to conditionally compile it.add#ifdef ASNFAM1at all occurrences. I will recommend third option as it is fail proof. but sometimes we need quick hack so give other 2 a try. Quick suggestion:- try not to ignore/suppress compiler warnings as they are there for a reason.
I am trying to find an algorithm to search for binary strings of fixed size (64 bit) in a large binary buffer (100 MB). The buffer is always the same and i have got lots and lots of strings to search for (2^500 maybe). I have to find all the occurrences of any given string, not only the first one. What algorithm can i choose from? Maybe one that benefits from the constant buffer in which i search. Links to C source code for such algorithm is appreciated.
Assuming your string are 8-bit aligned, from 100MB buffer you'll get 100 millions different strings, which can be put into the hash table approximately 800MB in size with constant (O(1)) access time. This will allow you to make the search as fast as possible, because once you have your 8 byte string, you immediately know where this string was seen in your buffer.
How can I concatenate two integers and save the data inlong long int, Example: ``` int x=0x1234abcd; int y=0x5678cdef; ``` the result is, long long z=0x1234abcd5678cdef;
Here is the sample code ``` int main(void) { int x = 0x1234abcd; int y = 0x5678cdef; long long z = ((long long)x<<32) | y;/* x needs to be type casted as long long */ printf("%llx\n",z); return 0; } ``` Also take consideration ofxorybeing negative number i.e ifsignbit isset(1). It's better to declare type asunsignedas pointed by @harold.
What is difference between ++*var++ and ++var++ ? why ++*var++ is working while ++var++ results with lvalue required error in C?
++var++is grouped as++(var++)and that results in a compilation failure sincevar++is not anlvalue. (Informally speaking this means you can't put it on the left hand side of an assignment). ++*var++is grouped as++(*(var++))which means increment the pointervarby 1 using pointer arithmetic, then increase the dereferenced value of the initial value ofvarby 1.
I got a bunch of 2d points. What I'm trying to find is the smallest polygon around (created from minimal set of points that fully enclose) one specific point. I tried to use convex hull and Voronoi but none of them produce the results I'm looking for and I'm running out of ideas... What I want is to find are the lines (in red) that represent the smallest convex polygon around a point (in green) as demonstrated on the image below: Another example: Any code, suggestions, or known algorithm would be greatly appreciated...
Start from any black point in your diagram, let's call it A. Draw the line from point A to the green point G. Now draw the line from point A to any other point A1, A2,... . If in a clockwise sense, this line is after line AG, ignore it. From all other lines choose the one that forms the smallest angle with line AG. Now move point A to the next point. Repeat until you are visiting a point for the second time.
1- string =a'b"c\d 2- escaped_string =a\'b\"c\\d 3- make an insert query that inserts escaped_string in some table field. 4- make a select query that returns the inserted value. The returned value is:a'b"c\d Is there a way to get the select query to returna\'b\"c\\d? (I understand that i can escape it again).
You can use theQUOTE()function of mysql: ``` mysql> select data from x; +---------+ | data | +---------+ | a'b"c\d | +---------+ 1 row in set (0.00 sec) mysql> select quote(data) from x; +-------------+ | quote(data) | +-------------+ | 'a\'b"c\\d' | +-------------+ 1 row in set (0.00 sec) ``` This should exactly do what you are looking for. Note that the"doesn't need to be escaped here, soQUOTE()doesn't escape it, too.
I have a text file, and it is a paragraph with quotation marks, commas, periods, and spaces. I want my C program to scan only the letters into an array, while also making all of them lower case in the process. So if a text file said "Hello.", then the array would have: hello
There are multiple solutions. Two of the more "common" would be Readeverythinginto memory, then copy only the wanted characters to the main array while converting to lower-case.Read character by character, saving only the characters you want to save while converting to lower-case. Both of these solutions are basically the same, they only differ in the actual file-reading part.
``` for(i = 1; i < len; i++){ for(j = i - 1; j >= 0; --j){ if(data[j] > data[1 + j]){ swap(j, j + 1); } else { break; } } } ``` swap method does swapping elements. Why it should be --j instead of j-- ? what is the difference ? what is the advantage of putting j-- ?
In this context both work. In C++ there are good reasons to use ++i. Since you're coding in C choose one and stick with it.
``` for(i = 1; i < len; i++){ for(j = i - 1; j >= 0; --j){ if(data[j] > data[1 + j]){ swap(j, j + 1); } else { break; } } } ``` swap method does swapping elements. Why it should be --j instead of j-- ? what is the difference ? what is the advantage of putting j-- ?
In this context both work. In C++ there are good reasons to use ++i. Since you're coding in C choose one and stick with it.
Inspired by thisquestion. Code: ``` #include <stdio.h> int main() { char arr[] = "Hello"; char *ptr = arr + 5; printf("%s\n",ptr); } ``` In the above code, I have accessed null-terminated character. So, What actually happens when accessing null terminated character in literal string? Is it Undefined behaviour?
Essentially, you're passing an emptystringas the argument, so it should be treated as such. For%sconversion specifier, withprintf()family [...]Characters from the array are written up to (but not including) the terminating null character.[...] In your case, the null terminator happens to appear at the first element in thearray, that's it. Just for clarification, accessing a null-terminator is OK, accessing aNULLpointer is not OK, and they both are different things!!
I want to print a string with multiple lines, I have tried: ``` printf("1. englsih 2. finish 3. japanese); ``` How should I do it?
To have newline characters in string, use\n: ``` printf("1. englsih\n2. finish\n3. japanese\n"); ``` If you want to split a string literal to several lines for readability, you can use\as the last character on line (not even spaces after it): ``` printf("1. englsih\n\ 2. finish\n\ 3. japanese\n"); ``` Above has the aesthetic problem, that any indentation at start of line will actually become part of the string. Alternatively, you can just split the string into several"quoted"parts, with only whitespace in between, so compiler will combine them into a single string literal: ``` printf("1. englsih\n" "2. finish\n" "3. japanese\n"); ```
I am using Valgrind to debug my code, and I am getting a warning when I test whether astructis initialized by comparing it withNULL. ``` void main() { int *unassignedPointer; if(unassignedPointer == NULL) printf("This Pointer is NULL\n"); } ``` This code compiles and runs, but when ran through Valgrind it gives a warning: Conditional jump or move depends on uninitialised value(s). The whole point of comparing it withNULLis to determine if it is initialized or not. Is this a dangerous practice, or should I just ignore these warnings?
You should of course not ignore the warning, you should fix it by initializing the pointer: ``` int *pointer = NULL; ``` in general you cannot detect if a variable has been assigned to, there's no magic "no value" value, all bits of the variable are used to contain the actual value.
I have developed a small python c-extension, with a flex scanner, that works perfectly fine in CPython. All my tests pass. But in IPython the output differs or IPython dies with a malloc error, whenever I try to interact with my c-extension. When I run my c-extension with valgrind lots of potential memory issues are detacted in Py_Initialize(), but none of them seem to be related to my code. I also double checked the reference count on my objects. I'm using anaconda on OS X with Python 3.6.5 Anybody got an idea what may cause this problem or how to debug this issue? The memory error I get is: ``` python(92795,0x7fff9ba8f380) malloc: *** error for object 0x7f9222845a40: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug Abort trap: 6 ```
Ok it was my own stupid fault. I Python didn't used the c extension from the conda env, but an older not properly working version of my c extension.