question
stringlengths
25
894
answer
stringlengths
4
863
My understanding is that the functionchar *tparm(char *str, ...);just converts the given stringstrto an expanded parameterized version which will be fine to use with stdout outputting functions likeprintforcout. But theman pagementions - Parameterized strings should be passed through tparm to instantiate them. All terminfo strings [including the output of tparm] should be printed with tputs or putp. So can I parse terminfo entries and usetparm()on them passing appropriate parameters and output them using stdout output functions? Also I'm doing the checks of non-tty output and ignoring these methods so I got that base covered.
Sure, youcan. But some capability strings includepaddingandtime delays, whichtparmassumes will be interpreted bytputs. For instance, theflashcapability would use time-delays, which are passed along totputs(using the syntax described in theterminfo(5)manual page).
What's the fastest way to delete a binary tree in C and why? Is there a way to do better than this: ``` void deleteTreeUtil(struct node* node) { if (node == NULL) return; deleteTreeUtil(node->left); deleteTreeUtil(node->right); printf("\n Deleting node: %d", node->data); free(node); } void deleteTree(struct node** node_ref) { deleteTreeUtil(*node_ref); *node_ref = NULL; } ```
Small optimization to improve performance for large trees: ``` void _deleteTree(struct node* node) { if (node->left) { _deleteTree(node->left); free(node->left); } if (node->right) { _deleteTree(node->right); free(node->right); } } void deleteTree(struct node** node_ref) { if (*node_ref) { _deleteTree(*node_ref); free(*node_ref); } } ```
I don't know if that is possible, I want to pass a block of instructions in macro like an argument.I will show you an example: ``` #define ADD_MACRO(size, BLOCK){ for(int i=0; i<size; i++){\ BLOCK} } ``` what do you think about it? thanks for help
The only problem with the given macro is that it doesn't handle commas in theBLOCK. Commas are tolerated by a variadic macro parameter: ``` #define ADD_MACRO(size, ...) do { for(int i=0; i<size; i++){\ __VA_ARGS__} } while(0) ``` (Also, common practice is to enclose statement macros indo … while(0)to force the user to include a semicolon.) (Of course, the original problem may have a better solution. The preprocessor is a blunt instrument. This is the preprocessor solution to the stated question.)
In the socket programming, SO_SNDBUF and SO_RCVBUF will have the default value as the 8192 bytes when the size of RAM is greater than 19MB. Now, I want to change the socket buffer sizes for my sockets.I know that one way is by setsockopt. But, I want to apply changes to the system default, and be able to use the modified value of the socket buffers for all the sockets I create in the system. Please let me know where do I make the configuration changes in windows platform?
Here there is a description of how it works:http://smallvoid.com/article/winnt-winsock-buffer.html And the solution should be: ``` [HKEY_LOCAL_MACHINE \SYSTEM \CurrentControlSet \Services \Afd \Parameters] DefaultReceiveWindow = 16384 DefaultSendWindow = 16384 ```
This question already has answers here:How printf works in case of type mismatch with type specifier?(3 answers)Closed6 years ago. In an Interview, I was asked the output of the following code snippet: ``` printf("%d", "computer"); ``` I am a c# developer and earlier I had learned C too, but when this question was asked, I had no clue. When I run the same question in windows 10 computer (64-bit), it is giving putput as 3571712 Please give reasons why this is happening.
It doesn't"work", what you observe is an outcome ofundefined behavior. QuotingC11, chapter §7.21.6.1/p9 [...] If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined. In your case, the conversion specifier is%dwhich expects an argument of typeintbut you're supplying achar*, and they are not the compatible type, hence the UB.
How would I show the default menus for pwndbg (https://github.com/pwndbg/pwndbg) (e.g. disassemble, code, stack trace, ..etc) that are shown by default when a step is made, and the program is paused at a certain breakpoint, but without having to make another step to show those menus? I would like to ask the same question as well for GEF (https://github.com/hugsy/gef)?
I have found the answer I was looking for. It is the command "context" that produces the menus once again!!
In the socket programming, SO_SNDBUF and SO_RCVBUF will have the default value as the 8192 bytes when the size of RAM is greater than 19MB. Now, I want to change the socket buffer sizes for my sockets.I know that one way is by setsockopt. But, I want to apply changes to the system default, and be able to use the modified value of the socket buffers for all the sockets I create in the system. Please let me know where do I make the configuration changes in windows platform?
Here there is a description of how it works:http://smallvoid.com/article/winnt-winsock-buffer.html And the solution should be: ``` [HKEY_LOCAL_MACHINE \SYSTEM \CurrentControlSet \Services \Afd \Parameters] DefaultReceiveWindow = 16384 DefaultSendWindow = 16384 ```
This question already has answers here:How printf works in case of type mismatch with type specifier?(3 answers)Closed6 years ago. In an Interview, I was asked the output of the following code snippet: ``` printf("%d", "computer"); ``` I am a c# developer and earlier I had learned C too, but when this question was asked, I had no clue. When I run the same question in windows 10 computer (64-bit), it is giving putput as 3571712 Please give reasons why this is happening.
It doesn't"work", what you observe is an outcome ofundefined behavior. QuotingC11, chapter §7.21.6.1/p9 [...] If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined. In your case, the conversion specifier is%dwhich expects an argument of typeintbut you're supplying achar*, and they are not the compatible type, hence the UB.
How would I show the default menus for pwndbg (https://github.com/pwndbg/pwndbg) (e.g. disassemble, code, stack trace, ..etc) that are shown by default when a step is made, and the program is paused at a certain breakpoint, but without having to make another step to show those menus? I would like to ask the same question as well for GEF (https://github.com/hugsy/gef)?
I have found the answer I was looking for. It is the command "context" that produces the menus once again!!
Thank you all I want to the program code" Enter the natural number n and print the even number smaller than n and the odd number is smaller than n ". When I am trying to use the for () loop it does not run properly. And I do not understand why so. This is my code ``` puts("even number"); for(i=0;i<=n;i=i+2) {printf("%3d",i);} printf("\n"); puts("odd number "); for(j=1;j<=n;j=j+2); {printf("%3d",i);} ``` And this is the result when I give n = 10enter image description hereThanks all
Your second loop should be ``` for(j=1;j<=n;j=j+2) // remove the final ; { printf("%3d",j); } // change i to j ``` The supposed body of thejloop was not in the loop at all, so was executed once, printing the final value ofi.
How to know the name and/or path of the debug symbol file which is linked to a binary executable? Suppose you did like this: ``` objcopy --only-keep-debug foo foo.dbg objcopy --strip-debug foo objcopy --add-gnu-debuglink=foo.dbg foo ``` Now foo.dbg has debug symbols, foo only has the link to foo.dbg that gdb can use. Since gdb can know the symbol file from foo, how can we know same without actually running gdb? I have observed that even if I rename the executable from foo to xyz still gdb loads symbols from foo.dbg so it is not like binaryname.extension, and extension is optional anyway.
how can we know same without actually running gdb? Either of these commands will tell you: ``` readelf -x.gnu_debuglink foo objdump -sj.gnu_debuglink foo ``` Theobjcopy --add-gnu-debuglinksimply adds.gnu_debuglinksection containing the given path, and a checksum of the debug file. More infohere.
I would like to write a function in C that truncates an input string to 32 chars, but the code below gives me a segmentation fault. Could anyone explain why it is so? ``` void foo (char *value){ if (strlen(value)>32) { printf("%c\n", value[31]); // This works value[31] = '\0'; // This seg faults } } ```
If you call your function like this: ``` char str[] = "1234567890123456789012345678901234567890"; foo(str); ``` It will work fine. But if you call it like this: ``` char *str = "1234567890123456789012345678901234567890"; foo(str); ``` That can cause a segfault. The difference here is that in the former casestris achararray, while in the latter casestris a pointer to a string constant. A string constant typically lives in a read only section of memory, so attempting to modify it causes the core dump.
Thank you all I want to the program code" Enter the natural number n and print the even number smaller than n and the odd number is smaller than n ". When I am trying to use the for () loop it does not run properly. And I do not understand why so. This is my code ``` puts("even number"); for(i=0;i<=n;i=i+2) {printf("%3d",i);} printf("\n"); puts("odd number "); for(j=1;j<=n;j=j+2); {printf("%3d",i);} ``` And this is the result when I give n = 10enter image description hereThanks all
Your second loop should be ``` for(j=1;j<=n;j=j+2) // remove the final ; { printf("%3d",j); } // change i to j ``` The supposed body of thejloop was not in the loop at all, so was executed once, printing the final value ofi.
How to know the name and/or path of the debug symbol file which is linked to a binary executable? Suppose you did like this: ``` objcopy --only-keep-debug foo foo.dbg objcopy --strip-debug foo objcopy --add-gnu-debuglink=foo.dbg foo ``` Now foo.dbg has debug symbols, foo only has the link to foo.dbg that gdb can use. Since gdb can know the symbol file from foo, how can we know same without actually running gdb? I have observed that even if I rename the executable from foo to xyz still gdb loads symbols from foo.dbg so it is not like binaryname.extension, and extension is optional anyway.
how can we know same without actually running gdb? Either of these commands will tell you: ``` readelf -x.gnu_debuglink foo objdump -sj.gnu_debuglink foo ``` Theobjcopy --add-gnu-debuglinksimply adds.gnu_debuglinksection containing the given path, and a checksum of the debug file. More infohere.
I would like to write a function in C that truncates an input string to 32 chars, but the code below gives me a segmentation fault. Could anyone explain why it is so? ``` void foo (char *value){ if (strlen(value)>32) { printf("%c\n", value[31]); // This works value[31] = '\0'; // This seg faults } } ```
If you call your function like this: ``` char str[] = "1234567890123456789012345678901234567890"; foo(str); ``` It will work fine. But if you call it like this: ``` char *str = "1234567890123456789012345678901234567890"; foo(str); ``` That can cause a segfault. The difference here is that in the former casestris achararray, while in the latter casestris a pointer to a string constant. A string constant typically lives in a read only section of memory, so attempting to modify it causes the core dump.
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed6 years ago.Improve this question int isValid(const long long phonenumber) { int check = 0; ``` int a; int p; a = phonenumber / 10000000; p = (phonenumber / 10000) % 1000; if (a = 416 || a = 647 || a = 905) { if (p >= 100 || p <= 999) { check++ } } return check; ``` } the 416 and 647 says expression must be a modifiable lvalue
to compare, use '==', not '='.
I am trying to program with C and implementing a function which calculates the days of the current year by entering the date. However, it keeps giving me a segmentation error. Can anyone help out? ``` #include <stdio.h> int datum2int(int day, int month){ int result=0; int array[]={31,28,31,30,31,30,31,30,31,30,31,30}; while((month-1)!=0){ result += array[month-2]; month--; } result +=day; return result; } int main(){ int day,month; scanf("%d, %d",&day, &month); printf("%d", datum2int(day, month)); return 0; } ```
You get seg fault because of the,between the%d. Remove it scanf("%d %d",&day, &month);
I'm trying to read 4 user inputs that can either be one digit, two digits, or a letter. I've tried using %c, but that can't contain any two digit numbers. I've also tried %d, but that reads all letters as 0. Is there anything that can cover all the bases?
In C there %c is usually for character inputs and %d is for integer. Usually you use these when scanning. Try %s this scans a string.
I have set#define DEBUG 1insicslowmac.cbut the debug messages are not being printed in packet capture display of cooja simulator. I have tried usingprintfin every function ofsicslowmac.c. Also tried#define DEBUG DEBUG_PRINTbut no success. I have used sky motes for udp-server.c and udp-client.c inrpl-udp. I am using latest build of contiki. What might I be doing wrong? I am able to print debug messages fromcc2420.candsicslowpan.cbut not fromsicslowmac.c. P.S: I have not made even a single change to any of the other files. So let not the question be treated astoo broadorprimarily opinion-based.
I got help from contiki mailing list. We need to tell contiki which RDC driver to use. By default it isnullrdc_driver. I changed it tosicslowmac_driver. But then I gotundefined reference to sicslowmac_driverincontiki-sky-main.cof sky platform. I could solve it by addingcore/net/mac/sicslowmacin Modules ofMakefile.sky.
When declaring an array in C I can writeint array[100]={0}and it assigns 0 to all index. Is there any way to do the same thing with string? Because when I writechar string[100]={'A'}it only assigns 'A' to the first index.And when I print the string it displays "A" instead of what I want "AAAAA.....A(99 times)". I dont want to use a loop to assign all the indexes with 'A'. So what can I do?
Its not in the standard but some compilers (includinggccand clang that I tested it with on my system) allow this: ``` #include <stdio.h> int main(){ char str[100] = {[0 ... 98] = 'A'}; str[99]='\0'; // this line is really not necessary, since default is 0 and I just wrote it for clarity printf("%s\n", str); return 0; } ```
Sometimes when I enter no numbers at all in thefgets()my isdigit condition is still met. Does not happen all the time but rarely. Why does it do this? here's the code. ``` void calculate(){ char item_name[20]; int i; printf("\nEnter Your Product:"); fgets(item_name, 20, stdin); for(i=0; i<20; i++){ if(isdigit(item_name[i])){ Errorlevel("Input Has a Number"); } } internet(item_name); return; } ```
You are not initializing youritem_namearray and possibly just encountering junk that might be stored there, especially as you are not checking the length of the stored string and yourforloop is iterating over the entire array length.
I'm working on an assignment and I have to open a file from command line upon executing the program. Example: ``` program.exe file.txt ``` However that is not working at all for me. Can someone please tell me what I'm doing wrong? This is the first time I'm working with taking a file as a parameter. ``` int main(int argc, char **argv) { int value; value = fileRead(argv[1]); } int fileRead(char argv[]) { int value; FILE *fp; fp = fopen(argv[1], "r"); if (fp) { fscanf(fp, "%d", &value); } else { fprintf(stderr, "Failed to open file!\n"); } return value; } ```
You're mixing up a character and a string. You passargv[1]tofileReadasargv. Then infileRead, you doargv[1]again. This effectively doesargv[1][1], which just gives the second character of the string. You need to either remove the[1]from inmainand then change the argument type, or remove the[1]fromfileRead.
We need to find new bits turned ON in interlock status received from the device compared to the last status read. This is for firing error codes for bits that are newly set. I am using the following statement. ``` bits_on =~last_status & new_status; ``` Is there any better ways to do this?
It's only 2 operations and an assignment, so the only way to improve it would be to do it in 1 operation and an assignment. It doesn't correspond to any of the simple C bit manipulation operators, so doing it in 1 operation is not possible. However, depending on your architecture your compiler might actually already be compiling it to a single instruction. ANDN(Logical AND NOT) is part of theBMI1instruction set, and is equivalent to~x & y.
What I need is a user to input 10 integers separated by spaces and then prints that out reverse. This is what I have, but it's not working. ``` #include <stdio.h> int main(int argc, char *argv[]) { int a[ 9 ], i, j, t ; printf("Enter ten integers seperated by spaces:\n"); for(i = 0; i < 10; i++) { scanf("%d", &a[i]); } j = i - 1; i = 0; while (i < j) { t = a[i]; a[i] = a[j]; a[j] = t; i++; j--; } printf("\nReverse array is:\n"); for(i = 0; i < 10; i++); { printf("%d ", a[i]); } return 0; } ```
I noticed two problems. Your array,a, only has 9 elements. You should make it large enough to to contain all ten elements.The secondforloop has a trailing semicolon:for(i = 0; i < 10; i++); { This semicolon will cause the loop to behave like this: ``` for(i = 0; i < 10; i++) { } { ``` Which isn't what you want.
I am trying to use a function that has no arguments and all it does is spit out a printf statement, but I don't know how to do so, or if I am even calling this function correctly. Here is an example of what I have. ``` void list(); char L; int main() { L = list(); printf("%c, L); void list() { printf("f - find a quote\ny - find a year\nq - quit"); } } ``` any suggestions?Note: I can't use a break statement or flag
You do not need to attempt to store the return value of yourlistfunction, as it returns void. Simply calling the function will cause it to be executed, and run your printf. Here's what you want: ``` #include <stdio.h> void list(); int main() { list(); return 0; } void list() { printf("f - find a quote\ny - find a year\nq - quit"); } ```
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.Closed6 years ago.Improve this question For example, what happens if I say: ``` for(i = 2; i < 2; i++) ``` Obviously, this is a useless for loop, but maybe i = a, and a is set by something else. So what happens in this case?
Neither iteration of the loop will be executed. In fact this loop (provided that the condition has no side effects) ``` for(i = 2; i < 2; i++) { /* ... */ } ``` is equivalent to this statement ``` i = 2; ```
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed6 years ago.Improve this question I'm running "gcc foo.c" foo.c: ``` #include "foo.h" FILE* foo(char* fileName) { ... } ``` foo.h: ``` #ifndef FOO_H #def FOO_H #include <stdio.h> #include <stdlib.h> FILE* foo(char* fileName); #endif ``` The error is: ``` foo.c:5:1: error: expected '=', ',', ';', 'asm', or '__attribute__' before '{' token { ``` Baffled here. Is there something wrong in the way I'm using headers? I've pored over this code for a while and can't find anything. Could it be a bad gcc statement in the command line?
Because ٰ#def FOO_Hshould be#define FOO_H.
What I need is a user to input 10 integers separated by spaces and then prints that out reverse. This is what I have, but it's not working. ``` #include <stdio.h> int main(int argc, char *argv[]) { int a[ 9 ], i, j, t ; printf("Enter ten integers seperated by spaces:\n"); for(i = 0; i < 10; i++) { scanf("%d", &a[i]); } j = i - 1; i = 0; while (i < j) { t = a[i]; a[i] = a[j]; a[j] = t; i++; j--; } printf("\nReverse array is:\n"); for(i = 0; i < 10; i++); { printf("%d ", a[i]); } return 0; } ```
I noticed two problems. Your array,a, only has 9 elements. You should make it large enough to to contain all ten elements.The secondforloop has a trailing semicolon:for(i = 0; i < 10; i++); { This semicolon will cause the loop to behave like this: ``` for(i = 0; i < 10; i++) { } { ``` Which isn't what you want.
I am trying to use a function that has no arguments and all it does is spit out a printf statement, but I don't know how to do so, or if I am even calling this function correctly. Here is an example of what I have. ``` void list(); char L; int main() { L = list(); printf("%c, L); void list() { printf("f - find a quote\ny - find a year\nq - quit"); } } ``` any suggestions?Note: I can't use a break statement or flag
You do not need to attempt to store the return value of yourlistfunction, as it returns void. Simply calling the function will cause it to be executed, and run your printf. Here's what you want: ``` #include <stdio.h> void list(); int main() { list(); return 0; } void list() { printf("f - find a quote\ny - find a year\nq - quit"); } ```
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.Closed6 years ago.Improve this question For example, what happens if I say: ``` for(i = 2; i < 2; i++) ``` Obviously, this is a useless for loop, but maybe i = a, and a is set by something else. So what happens in this case?
Neither iteration of the loop will be executed. In fact this loop (provided that the condition has no side effects) ``` for(i = 2; i < 2; i++) { /* ... */ } ``` is equivalent to this statement ``` i = 2; ```
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed6 years ago.Improve this question I'm running "gcc foo.c" foo.c: ``` #include "foo.h" FILE* foo(char* fileName) { ... } ``` foo.h: ``` #ifndef FOO_H #def FOO_H #include <stdio.h> #include <stdlib.h> FILE* foo(char* fileName); #endif ``` The error is: ``` foo.c:5:1: error: expected '=', ',', ';', 'asm', or '__attribute__' before '{' token { ``` Baffled here. Is there something wrong in the way I'm using headers? I've pored over this code for a while and can't find anything. Could it be a bad gcc statement in the command line?
Because ٰ#def FOO_Hshould be#define FOO_H.
This question already has answers here:Element count of an array in C++(14 answers)Closed6 years ago. I want to get the amount of how much elements in an int array; for example, Here's a simple array of integer type: int myArray[] = {2, 4, 2, 13}. And I need to get the amount of elements ( here is4). Please help me.
If it has notdecayedinto a pointer type, then you can use sizeof(myArray) / sizeof(myArray[0]) to yield the number of elements. If you've passedmyArrayinto afunctionthough, you can't use this method. In that case the normal thing to do is to pass the size as an additional parameter. Alternatively, in C++, usestd::vector<int>.
I have already seen other questions related with this, but nothing helped me. I have a problem integrating ImageMagick sdk into swift. ViewController.swift ``` class ViewController: UIViewController { var wand: MagickWand! // [...] } ``` The error: ``` Error: Use of undeclared type 'MagickWand' ``` I correctly imported MagicWand.h in Briding Header. ``` #ifndef Header_h #define Header_h #import "MagickWand.h" #endif ``` In MagickWand.h, the struct is defined correctly. ``` typedef struct _MagickWand MagickWand; ``` Any help would be appreciated.
Incomplete struct definitions like that are imported asOpaquePointer(that's basically whatOpaquePointerwas made for). If Swift actually has access to the contents of theMagickWandstruct, then it can import it as a named type.
I am trying to solve the numerical equation: sin^2(x)tan(x) = 0.499999 Using a while loop in C. However I was only able to get program to print an answer if I rounded to 0.5. This led me to thinking, is there a way of writing: ``` For(x=0;x<=360;x=x+0.001) { y=f(x) If(y **is near x**(e.g. Within 1 percent) ) Do something etc. } ``` Is there a way of telling the computer to execute a task if the value is sufficiently near. Such as in this if statement? Thank you.
Use a relative difference, such as: ``` #include <math.h> static inline double reldiff(double x, double y) { return fabs(x - y) / fmax(fabs(x), fabs(y)); } ``` Now your test becomes: ``` if (reldiff(x, y) < 0.01) // 1% as requested ```
I have written a program in C to solve the maximum sub-array problem. This solution is of O(N^3) complexity. Is there any way to approximate the run time for N = 1,000,000? I know there are much faster algorithms than that of third order but I need to compare those to my current program. ``` int MaxSubSlow(){ int max_so_far = 0,i,j,k,temp_sum; for(j=1;j<N;j++){ for(k=j;k<N;k++){ temp_sum = 0; for(i=j;i<k;i++){ temp_sum += A[i]; } if(temp_sum > max_so_far){ max_so_far = temp_sum; } } } return max_so_far; } ```
If it is O(N^3) you can approximate N=1,000,000 by running it with N=1,000 and then multiply by 1,000,000,000. (But, since the O notation can hide other significant terms except the N^3 one, you can't be sure that it is a very good approximation.)
I have a translation question but I am asking it here because I think it needs technical understanding. In order to translate a program to German, I have this line in the.pofile: ``` #, c-format msgid "Unable to stat %s\n" msgstr "" ``` What does this mean and how would I say it in German?
Herestatis a reference to the POSIX standard call of that name,stat(2). Perhaps you can take some clue from the manual page's description, the brief one is "get file status". My German is waaaay too rusty to suggest a translation, but inserting it into the English would give "Unable to get file status (stat) %s\n" (I kept the original "stat" phrase since it's highly-detailed technical information and might be useful). You could of course not try to work around the function name, and instead just say "The stat() function failed for %s", it's the use of the funtion name as a verb which makes it harder to translate, I think.
How to correctly cast SEPARATOR in the following code while calling the send_data function? foo.h ``` #define SEPARATOR 0xFF void send_data(unsigned char * data, int dataSize); ``` foo.c ``` void welcome(){ // I want to call it in a one line send_data(SEPARATOR ,1); } ``` Btw, of course I can define the SEPARATOR as a const char. But I just wonder about if there is any way to use it like that.
The old-school way would be to work around it, if you don't want to change it: ``` void welcome(void) { unsigned char data = SEPARATOR; send_data(&data, 1); } ``` But you should also be able to use a C99 compound literal: ``` send_data((unsigned char[1]) { SEPARATOR }, 1); ```
I have written a program in C to solve the maximum sub-array problem. This solution is of O(N^3) complexity. Is there any way to approximate the run time for N = 1,000,000? I know there are much faster algorithms than that of third order but I need to compare those to my current program. ``` int MaxSubSlow(){ int max_so_far = 0,i,j,k,temp_sum; for(j=1;j<N;j++){ for(k=j;k<N;k++){ temp_sum = 0; for(i=j;i<k;i++){ temp_sum += A[i]; } if(temp_sum > max_so_far){ max_so_far = temp_sum; } } } return max_so_far; } ```
If it is O(N^3) you can approximate N=1,000,000 by running it with N=1,000 and then multiply by 1,000,000,000. (But, since the O notation can hide other significant terms except the N^3 one, you can't be sure that it is a very good approximation.)
I have a translation question but I am asking it here because I think it needs technical understanding. In order to translate a program to German, I have this line in the.pofile: ``` #, c-format msgid "Unable to stat %s\n" msgstr "" ``` What does this mean and how would I say it in German?
Herestatis a reference to the POSIX standard call of that name,stat(2). Perhaps you can take some clue from the manual page's description, the brief one is "get file status". My German is waaaay too rusty to suggest a translation, but inserting it into the English would give "Unable to get file status (stat) %s\n" (I kept the original "stat" phrase since it's highly-detailed technical information and might be useful). You could of course not try to work around the function name, and instead just say "The stat() function failed for %s", it's the use of the funtion name as a verb which makes it harder to translate, I think.
How to correctly cast SEPARATOR in the following code while calling the send_data function? foo.h ``` #define SEPARATOR 0xFF void send_data(unsigned char * data, int dataSize); ``` foo.c ``` void welcome(){ // I want to call it in a one line send_data(SEPARATOR ,1); } ``` Btw, of course I can define the SEPARATOR as a const char. But I just wonder about if there is any way to use it like that.
The old-school way would be to work around it, if you don't want to change it: ``` void welcome(void) { unsigned char data = SEPARATOR; send_data(&data, 1); } ``` But you should also be able to use a C99 compound literal: ``` send_data((unsigned char[1]) { SEPARATOR }, 1); ```
My C codes are listed below: ``` char s="MIDSH"[3]; printf("%d\n",strlen(&s)); ``` The result of running is 2, which is wrong because char s is just an 'S'. Does anybody know why and how to solve this problem?
That's actually quite an interesting question. Let's break it up: ``` "MIDSH"[3] ``` String literals have array types. So the above applies the subscript operator to the array and evaluates to the 4th character 'S'. It then assigns it to thesingle character variables. ``` printf("%d\n",strlen(&s)); ``` Sincesis a single character, and not part of an actual string, the behavior is undefined for the above code.
I have tested this,kis 16, but why? ``` int main(int argc, char **argv) { int k = (int)((int *)0 + 4); printf("%d", k); return 0; } ```
Important note:Pointer arithmetic on a pointer that does not point to an array is undefined behavior. You can get 16, but you can also get a crash, for example, if the implementation chooses to produce a trap representation for the result. This is pointer arithmetic: when you add a numberxto a pointer toT, numeric value that corresponds to the pointer is increased byx * sizeof(T). In your case, the numeric value of the pointer is zero,xis 4, andsizeof(int)is also 4.4*4yields 16.
My system is Ubuntu16.04 LTS. when I use the OpenSSLEVP_MD_CTX, this error appeared. Can anyone help me? CODE: ``` #include <stdio.h> #include <openssl/evp.h> #include <openssl/rsa.h> int main() { int ret,inlen,outlen=0; unsigned long e=RSA_3; char data[100],out[500]; EVP_MD_CTX md_ctx, md_ctx2; ... } ``` ERROR: ``` root@ubuntu:/work/test# gcc evp_openssl_test.c -I/usr/local/include -L/usr/local/lib -lssl -lcrypto -o evptestevp_openssl_test.c: In function ‘main’: evp_openssl_test.c:13:19: error: storage size of ‘md_ctx’ isn’t known EVP_MD_CTX md_ctx,md_ctx2; ```
You are using OpenSSL 1.1.0 which made this structure (and many others) opaque - which means you cannot stack allocate it. Instead do this: ``` EVP_MD_CTX *md_ctx; md_ctx = EVP_MD_CTX_new(); if (md_ctx == NULL) ... ... EVP_MD_CTX_free(md_ctx); ```
This question already has answers here:Why doesn't getchar() recognise return as EOF on the console?(8 answers)Testing getchar() == EOF doesn't work as expected(2 answers)Closed6 years ago. Having trouble getting an actual count, but I'm not seeing what I'm doing wrong. I type in a word, hit enter, then nothing happens and it keeps running. ``` int main(void) { double nc; for (nc = 0; getchar() != EOF; ++nc) ; printf ("%.0f\n", nc); } ```
When reading from an interactive console input,getchar()will not returnEOFjust because the user stops typing or presses return, it will if necessary wait for the user to enter something new on the keyboard. So, the for-loop is not terminated. You have to use a special key combination (dependent on the operating system used) to signal end-of-file or check for some other input to terminate the loop (like end-of-line, for example)
I'm writing a program written in C that needs to run many tasks in parallel. After doing research it seams the OpenMP API is a great fit. Further research shows there are cons to using OpenMP; specifically that it is restricted to shared-memory multiprocessor platforms. How can I determine if my OS + hardware is a shared-memory multiprocessor platform? I'd assume that most modern machines support multiprocessing.
How can I determine if my OS + hardware is a shared-memory multiprocessor platform? If it wasn't, you'd probably know so already. Modern computers (including desktops, laptops, mobile devices, and most servers) are almost always shared-memory platforms, and as such can support OpenMP. Hardware that doesn't fall into this category is rare, and typically falls into one of two cases: Extremely large servers, cluster computers, and supercomputers.Esoteric and experimental architectures.
This question already has answers here:Why doesn't getchar() recognise return as EOF on the console?(8 answers)Testing getchar() == EOF doesn't work as expected(2 answers)Closed6 years ago. Having trouble getting an actual count, but I'm not seeing what I'm doing wrong. I type in a word, hit enter, then nothing happens and it keeps running. ``` int main(void) { double nc; for (nc = 0; getchar() != EOF; ++nc) ; printf ("%.0f\n", nc); } ```
When reading from an interactive console input,getchar()will not returnEOFjust because the user stops typing or presses return, it will if necessary wait for the user to enter something new on the keyboard. So, the for-loop is not terminated. You have to use a special key combination (dependent on the operating system used) to signal end-of-file or check for some other input to terminate the loop (like end-of-line, for example)
I'm writing a program written in C that needs to run many tasks in parallel. After doing research it seams the OpenMP API is a great fit. Further research shows there are cons to using OpenMP; specifically that it is restricted to shared-memory multiprocessor platforms. How can I determine if my OS + hardware is a shared-memory multiprocessor platform? I'd assume that most modern machines support multiprocessing.
How can I determine if my OS + hardware is a shared-memory multiprocessor platform? If it wasn't, you'd probably know so already. Modern computers (including desktops, laptops, mobile devices, and most servers) are almost always shared-memory platforms, and as such can support OpenMP. Hardware that doesn't fall into this category is rare, and typically falls into one of two cases: Extremely large servers, cluster computers, and supercomputers.Esoteric and experimental architectures.
Hello I am using this code for reading floating numbers in txt. If end of txt file has extra blank empty line program reads it 0.00000 and this affect my calculationLast empty line (# means end of the calculation I added comment line if it exist update comment line) I try "getline" and other function I can't fix it ``` fptr = fopen(fileName,"r+"); if(fptr == NULL){ printf("Error!! Cannot open file: %s \n", fileName ); return 1; } else { printf("File opened successfully\n"); while((c = getc(fptr)) != '#' && c != EOF) { fscanf(fptr,"%f" ,&arr[i]); ++i; } } ```
Check the return value offscanf-- it should return 1 when it successfully reads a number and 0 on that blank line.
I am trying to run my code on an ARM device. So far it's running and I also have a tool to measure complexity. Now I have lots of standard functions I am using to perform mathematical operations, like dividing, multiplying, adding and so an. Is it easier (i.e. less complex) if I write those functions as e.g. ``` result = a + b; ``` or as ``` "qadd %0, %1, %4;" ``` which would be arm code for this operation if the values are in the respective registers. I am just wondering if writing everything in ARM code would really reduce the complexity. Also, how does that behave for conditionals (like If and Else). Thank you.
Let the compiler take care of it, until you discover a bottleneck. Note thatQADDis saturating arithmetic and has different behavior to the C code you show.
How to build SCTP client.c and server.c sample code with Eclipse in Linux ubuntu? In terminal I can build with ``` gcc -Wall sctpclient.c -lsctp -o sctpclient ``` but in Eclipse I received "undefined reference to `sctp_recvmsg'". I don't know to add the "-lsctp" switch in Eclipse IDE.
I found the right path in Eclipse IDE, You must add -lsctp parameter to below path: ``` Project properties->C/C++ Build->Setting->GCC C Linker->Miscellaneous->Other objects ``` And in NetBeans IDE add parameter to: ``` Project properties->Build->Linker->Additional Options ```
Hello I am using this code for reading floating numbers in txt. If end of txt file has extra blank empty line program reads it 0.00000 and this affect my calculationLast empty line (# means end of the calculation I added comment line if it exist update comment line) I try "getline" and other function I can't fix it ``` fptr = fopen(fileName,"r+"); if(fptr == NULL){ printf("Error!! Cannot open file: %s \n", fileName ); return 1; } else { printf("File opened successfully\n"); while((c = getc(fptr)) != '#' && c != EOF) { fscanf(fptr,"%f" ,&arr[i]); ++i; } } ```
Check the return value offscanf-- it should return 1 when it successfully reads a number and 0 on that blank line.
I am trying to run my code on an ARM device. So far it's running and I also have a tool to measure complexity. Now I have lots of standard functions I am using to perform mathematical operations, like dividing, multiplying, adding and so an. Is it easier (i.e. less complex) if I write those functions as e.g. ``` result = a + b; ``` or as ``` "qadd %0, %1, %4;" ``` which would be arm code for this operation if the values are in the respective registers. I am just wondering if writing everything in ARM code would really reduce the complexity. Also, how does that behave for conditionals (like If and Else). Thank you.
Let the compiler take care of it, until you discover a bottleneck. Note thatQADDis saturating arithmetic and has different behavior to the C code you show.
How to build SCTP client.c and server.c sample code with Eclipse in Linux ubuntu? In terminal I can build with ``` gcc -Wall sctpclient.c -lsctp -o sctpclient ``` but in Eclipse I received "undefined reference to `sctp_recvmsg'". I don't know to add the "-lsctp" switch in Eclipse IDE.
I found the right path in Eclipse IDE, You must add -lsctp parameter to below path: ``` Project properties->C/C++ Build->Setting->GCC C Linker->Miscellaneous->Other objects ``` And in NetBeans IDE add parameter to: ``` Project properties->Build->Linker->Additional Options ```
I'm reading through HLSL code to try to figure out how it works, and I came across a bit of code that looks like this: ``` float aFloat = someVar > someConstant; ``` Now I'm wondering what in the world a comparison operator is doing in a float assignment statement. I know HLSL is C-like, but I've never tried C, though I intend to give it a shot in the future, so any insight into this statement will help there too.
Transferring comment to answer. The result of the comparison is an integer — either 0 or 1 — so the value assigned to the float will be 0.0 or 1.0. Without more context, it isn't possible to say why they did it like that, but it is reliable and determinate.
I'm trying to get the value of DF from the EFLAGS register. I tried to use theLAHFinstruction, but according to the Intel X86 documentation, the instruction loads only theSF, ZF, AF, PF, CFflags. However, I'm trying to find an instruction that will give me the value of the DF register. Thanks in advance.
Use the following code: ``` pushf ;Maybe you'll need pushfd pop eax bt eax, 10 ``` If the CF is set then the DF was set! If you don't want to clobber any register, you could use next method (inspired by @fuz): ``` pushf test byte [esp+1],4 lea esp, [esp+4] ;The LEA instruction doesn't change any flags ``` This time if the ZF is set, it means the DF was cleared!
I am new with data structures and c-language. I came across this algorithm ``` big=a if(b>big) big = b end if if(c>big) big = c end if if(d>big) big =d end if return big ``` does this statement mean that "'if' statement will end if big=b in situation of b being greater then big(or a as a=big) and henceforth. also i wanted to know what is big as a variable used for and what it means as came across big-o and big-theta in data structures. thnx in advance
The above algorithm returns you the largest number among a,b,c,d. It has nothing to do with Big O and theta as these are related to complexities of an algorithm.
I'm trying to initial mifare desfire ev1 with my mfrc522 based reader.ISO14443-3 is done successfully and I select PICC successfully and read 7 byte UID and SAK correctly.As I know after completing anti-collision and select processes and receiving valid SAK(0x20) I must perform ISO14443-4 commands.Then I send RATS command to the PICC: ``` PCD->PICC RATS: '0xE0','0x50','CRC_MSB','CRC_LSB' ``` but PICC does not answer with SAK(I receive nothing),actually seems buffer is not big enough.
ISO 14443-3 CRC_A is transmitted least-significant-byte-first (little-endian) -- see Annex B. The correct RATS should be: ``` PCD->PICC RATS: '0xE0','0x50','CRC_LSB','CRC_MSB' ``` Which means: ``` PCD->PICC RATS: '0xE0','0x50','0xBC','0xA5' ``` for your particular FSDI/CID. Good luck!
``` '#include <stdio.h> int main() { short arr[3][2]={3, 6, 9, 12, 15, 18}; printf("%d %d", *(arr + 1)[1], **(arr + 2)); }' ``` The output of the program is 15,15?
As per the operator precedence rule*(a+i)[j]will be parsed as*((a + i)[j])which is ultimately equivalent to*( *(a + i + j) ). So fori = 1andj = 1it will be*( *(a + 1 + 1) ) = *( *( a + 2) + 0) = a[2][0]
``` int die[5] = { 0 }; int roll_die(void) { return rand(1, 6) % 6 + 1; } for (index = 0; index < 5; (++index) && (i++)) { roll_die(die, 5); //tried as &die as well, but same problem printf("die[%d]: %d\n\n", i, die[index]); } ``` prints die[1] - die[5] will 0 values instead of randomly generated integers between 1 and 6
``` #include <stdio.h> int roll_die() { return rand() % 6 + 1; } int main() { int die[5] = { 0 }, index; for (index = 0; index < 5; (++index)) { die[index] = roll_die(); printf("die[%d]: %d\n\n",index, die[index]); } return 0; } ``` you usedrandwrong, didnt used the returned value, and the way you called the function was wrong. hope that helps. p.s. its better also to callsrand(time(NULL));once in the start
I'm trying to get the value of DF from the EFLAGS register. I tried to use theLAHFinstruction, but according to the Intel X86 documentation, the instruction loads only theSF, ZF, AF, PF, CFflags. However, I'm trying to find an instruction that will give me the value of the DF register. Thanks in advance.
Use the following code: ``` pushf ;Maybe you'll need pushfd pop eax bt eax, 10 ``` If the CF is set then the DF was set! If you don't want to clobber any register, you could use next method (inspired by @fuz): ``` pushf test byte [esp+1],4 lea esp, [esp+4] ;The LEA instruction doesn't change any flags ``` This time if the ZF is set, it means the DF was cleared!
I am new with data structures and c-language. I came across this algorithm ``` big=a if(b>big) big = b end if if(c>big) big = c end if if(d>big) big =d end if return big ``` does this statement mean that "'if' statement will end if big=b in situation of b being greater then big(or a as a=big) and henceforth. also i wanted to know what is big as a variable used for and what it means as came across big-o and big-theta in data structures. thnx in advance
The above algorithm returns you the largest number among a,b,c,d. It has nothing to do with Big O and theta as these are related to complexities of an algorithm.
I'm trying to initial mifare desfire ev1 with my mfrc522 based reader.ISO14443-3 is done successfully and I select PICC successfully and read 7 byte UID and SAK correctly.As I know after completing anti-collision and select processes and receiving valid SAK(0x20) I must perform ISO14443-4 commands.Then I send RATS command to the PICC: ``` PCD->PICC RATS: '0xE0','0x50','CRC_MSB','CRC_LSB' ``` but PICC does not answer with SAK(I receive nothing),actually seems buffer is not big enough.
ISO 14443-3 CRC_A is transmitted least-significant-byte-first (little-endian) -- see Annex B. The correct RATS should be: ``` PCD->PICC RATS: '0xE0','0x50','CRC_LSB','CRC_MSB' ``` Which means: ``` PCD->PICC RATS: '0xE0','0x50','0xBC','0xA5' ``` for your particular FSDI/CID. Good luck!
``` '#include <stdio.h> int main() { short arr[3][2]={3, 6, 9, 12, 15, 18}; printf("%d %d", *(arr + 1)[1], **(arr + 2)); }' ``` The output of the program is 15,15?
As per the operator precedence rule*(a+i)[j]will be parsed as*((a + i)[j])which is ultimately equivalent to*( *(a + i + j) ). So fori = 1andj = 1it will be*( *(a + 1 + 1) ) = *( *( a + 2) + 0) = a[2][0]
``` int die[5] = { 0 }; int roll_die(void) { return rand(1, 6) % 6 + 1; } for (index = 0; index < 5; (++index) && (i++)) { roll_die(die, 5); //tried as &die as well, but same problem printf("die[%d]: %d\n\n", i, die[index]); } ``` prints die[1] - die[5] will 0 values instead of randomly generated integers between 1 and 6
``` #include <stdio.h> int roll_die() { return rand() % 6 + 1; } int main() { int die[5] = { 0 }, index; for (index = 0; index < 5; (++index)) { die[index] = roll_die(); printf("die[%d]: %d\n\n",index, die[index]); } return 0; } ``` you usedrandwrong, didnt used the returned value, and the way you called the function was wrong. hope that helps. p.s. its better also to callsrand(time(NULL));once in the start
I am a beginner to c programming. I tried to write a code to invert the elements of an array. Here is what I have written ``` #include <stdio.h> int main(void) { int a[5], i, j, b[5], k=5; printf("enter 5 numbers"); for (i=0;i<5;i++) { scanf("%d",&a[i]); } for(i=1;i<5;i++) { for(j=k; j>=1; j--) { b[j] = a[i]; k--; break; } } for(j=1; j<5; j++) { printf("%d\n",b[j]); } return 0; } ``` In output I am getting only 3 numbers inverted and not all 5. Can anyone please help me out?
You do not really need a loop inside a loop. It can be done easily with one: ``` for(i=0; i<5; i++) { b[i] = a[4-i]; } ```
The C standard librarystring.hcontains several functions to manipulate strings, all of which start withstrand end with an abbreviation. Some of these abbreviations are obvious: strlenstring lengthstrcpystring copystrcmpstring compare Some are a bit less straightforward: strpbrkstring pointer break?strspnstring ...spn?strrchrstring ... R char??strxfrmstring... um... nevermind. What do each of thestr-function abbreviations/acronyms mean?
strlen- find LENgth of stringstrcpy- CoPY stringsstrcmp- CoMPare stringsstrrchr- Reversely find CHaRacterstrspn- calculate the length of SPaN of charactersstrxfrm- TRANS (written as X)-FoRM a stringstrpbrk- find the Point where string is BRoKen by any of the characters
I'm trying to use OpenThread in a CC2650 Launchpad, following their example commands atthis link. However, the state of the node stays detached forever. And if I try to manually set the state to leader, the node outputs error 29, which according to thereference page about status codes in OpenThread, it corresponds to a reserved code. How can I can turn on the leader mode in this case?
As mentioned by Nick on the comments of the question, error 29 means that the device doesn't support being a leader. Taking a look at the description of theCC2650 OpenThread repo, we can see that this chip doesn't have memory to have all capabilities of OpenThread, so the developers should have excluded the leader mode.
I'm trying to recursive function in C that calculates the sum of the numbers from x to max (inclusive). For example, sum (4, 7) would compute 4 + 5 + 6 + 7 and return the value 22. The function code a must be recursive so you are not allowed to use any conventional loop constructs. I have this and i think it should work but i'm not entirely sure why its not ``` #include <stdio.h> int main() { int sum (x, max); int total, y, x, max; if (x<max){ y=x+1; total = x+sum(y,max); return total; return x; } return 0; } ``` Thanks for any help with this in advance!
Here is one possible solution: ``` #include <stdio.h> int sum_in_range(int a, int b){ if(a != b){ return sum_in_range(a+1,b)+a; } else{ return b; } } int main(void) { // your code goes here printf("%d",sum_in_range(2,4)); return 0; } ```
I am a beginner to c programming. I tried to write a code to invert the elements of an array. Here is what I have written ``` #include <stdio.h> int main(void) { int a[5], i, j, b[5], k=5; printf("enter 5 numbers"); for (i=0;i<5;i++) { scanf("%d",&a[i]); } for(i=1;i<5;i++) { for(j=k; j>=1; j--) { b[j] = a[i]; k--; break; } } for(j=1; j<5; j++) { printf("%d\n",b[j]); } return 0; } ``` In output I am getting only 3 numbers inverted and not all 5. Can anyone please help me out?
You do not really need a loop inside a loop. It can be done easily with one: ``` for(i=0; i<5; i++) { b[i] = a[4-i]; } ```
The C standard librarystring.hcontains several functions to manipulate strings, all of which start withstrand end with an abbreviation. Some of these abbreviations are obvious: strlenstring lengthstrcpystring copystrcmpstring compare Some are a bit less straightforward: strpbrkstring pointer break?strspnstring ...spn?strrchrstring ... R char??strxfrmstring... um... nevermind. What do each of thestr-function abbreviations/acronyms mean?
strlen- find LENgth of stringstrcpy- CoPY stringsstrcmp- CoMPare stringsstrrchr- Reversely find CHaRacterstrspn- calculate the length of SPaN of charactersstrxfrm- TRANS (written as X)-FoRM a stringstrpbrk- find the Point where string is BRoKen by any of the characters
I'm launching a process with the instruction ``` execl("./softCopia","softCopia",NULL); ``` softCopia is just a dummy that writes integers in a file. I would like to know how can i get the pid of this process?
Since all of the Unix exec functionsreplacethe running process with the new one, the PID of the exec'd process is the same PID it was before. So you get the PID by using thegetpid()call,beforecallingexecl. Or, if you actually want to continue running your main program and launch a new program, you usefork()first. Thefork()function returns a negative value for errors, 0 for the new, child process, and the PID of the child in the parent. So the parent can then use one of thewaitfunctions or just continue on its business until later.
This question already has answers here:How to define and work with an array of bits in C?(5 answers)Closed6 years ago. I want to make an array of int bit fields where each int has one bit, meaning that all of the numbers will be 1 or 0, how can I code that? I tried ``` struct bitarr { int arr : 1[14]; }; ``` but that doesn't compile and I don't think that this is the way
You can not do array of these bits. Instead, create single 16-bit variable for your bits, then instead of accessing it asi[myindex]you can access it asbitsVariable & (1 << myindex). To set bit, you can use: ``` bitsVariable |= 1 << myindex; ``` To clear bit, you can use: ``` bitsVariable &= ~(1 << myIndex); ``` To check bit, you can use: ``` if (bitsVariable & (1 << myIndex)) { //Bit is set } else { //Bit is not set } ```
I'm launching a process with the instruction ``` execl("./softCopia","softCopia",NULL); ``` softCopia is just a dummy that writes integers in a file. I would like to know how can i get the pid of this process?
Since all of the Unix exec functionsreplacethe running process with the new one, the PID of the exec'd process is the same PID it was before. So you get the PID by using thegetpid()call,beforecallingexecl. Or, if you actually want to continue running your main program and launch a new program, you usefork()first. Thefork()function returns a negative value for errors, 0 for the new, child process, and the PID of the child in the parent. So the parent can then use one of thewaitfunctions or just continue on its business until later.
I have the following code: ``` z=x-~y-1; printf("%d",z); z=(x^y)+2(x&y); printf("%d",z); z=(x|y)+(x&y); printf("%d",z); z=2(x|y)-(x^y); printf("%d",z); ``` I get this error message: ``` 10:11: error: called object is not a function or function pointer z=(x^y)+2(x&y); ^ ``` The language is C. Why did this happen?
As for what the error means:2(x&y)tells the compiler to call the function2, passingx&yas an argument (just likeprintf("hi")means "callprintfand pass"hi"as an argument"). But2isn't a function, so you get a type error. Syntactically speaking, whenever you have a value followed by(, that's a function call.
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.Closed6 years ago.Improve this question My new work will use language Elixir. I'm a fresh at this point also Erlang environment. With some research, I'm find the platform has some problem with performance for CPU intensive computing. Does it possiable use C replace Erlang in above situation withnifeven if C code maybe at high proportion? Or there are some limits that we can't do this.
The easiest and safest way to run computationally intensive C code from Erlang is to write the C code as a standalone executable and connect it to Erlang through a port. Seehttp://erlang.org/doc/tutorial/c_port.htmlfor details.
Why does the sizeof (array [0]) return size as 8 when it has 17 characters/bytes within it? ``` #include <stdlib.h> #include <stdio.h> int main () { char* array [2] = {"12345678912345678","12345678"}; int a = sizeof (array [0]); fprintf (stdout, "%s , %d \n", array [0], a); return 0; } ``` Returns: ``` 12345678912345678 , 12345678 ```
To get the length of the actual character string being stored, use printf("%lu", strlen(array[0])); This gives17. Make sure to include the<string.h>header.
Using the Lua 5.3.4 C API, this works: ``` luaL_dostring(lua, "dofile('mnemonics.lua')"); ``` But this fails to execute the file: ``` luaL_dofile(lua, "mnemonics.lua"); ``` Instead, it reports "attempt to call a string value". When I replace it with ``` luaL_loadfile(lua, "mnemonics.lua"); ``` it returnsLUA_OK, but it doesn't push a function on the stack like it's supposed to. In fact, the stack is empty (gettopreports 0) afterwards. I can use the dostring workaround, but either I'm missing something, or there's a bug.
Popping from an empty stack will cause unexpected behavior. The Lua interpreter cleans up the stack between executing C code and executing Lua code, so the messed up stack didn't affect thedofilein Lua.
I wrote this function from a pseudocode I found, which should convert decimal input into hexadecimal number. Well it does that, but in incorrect order, like for example, for decimal number 195 I get 3C, insted of C3. ``` int temp=0; int i=0; while(decimal!=0) { temp = decimal % 16; if( temp < 10) temp =temp + 48; else temp = temp + 55; array[i++]= temp; decimal = decimal / 16; } ```
save yourself some time like this ``` #include <stdio.h> // ... sprintf(hexStr,"%X",decimal); // or, "%#X" if you want prefix ``` unless, this is homework for a programming class. in which case you should really just work it out on whiteboard or paper, i'm sure you'll see your mistake.
While for simple types(simple types: int, char..)we directly use pointers(their address)as an argument to a function to permanently change their value in the main program, can someone explain to me why for structures we need a pointer to aStructure pointer, and not just a pointer? ``` struct someStruct { int field1; int field2; } void initializeFields(struct someStruct** foo) { //changing fields } //while void initializeFields(struct someStruct* foo) //does not work ? ```
struct someStruct* foois fine, you don't needstruct someStruct** foo. Not sure where you got that idea from, but it's not correct.
How to do stop scrolling uitableview if new rows are not there in tableview in objective c?
For disabling bounces for the tableView you can use: ``` self.tableView.bounces = NO; ``` this will disable it when it gets to the last row
how can I print the actual final sqlite3 query that is executed in a portion of code like this? ``` int rc; sqlite3_stmt *res; char *query = ""; query = "SELECT count(*) FROM `db_report` WHERE `r_sn` = ?;"; rc = sqlite3_prepare_v2(db, query, -1, &res, 0); if (rc == SQLITE_OK) { sqlite3_bind_text(res, 1, sn, strlen(sn), SQLITE_STATIC); } int step = sqlite3_step(res); PRINT REAL QUERY sqlite3_finalize(res); return 0; ``` Thanks a lot :)
You can usesqlite3_expanded_sqlto retrieve a pointer to a string that contains the final query with bound parameters expanded.
This is my sample program for simulating a Loading progress. The only problem I'm facing right now is clearing my previous output of "Loading: %i" ``` /* loading program */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #define TIMELIMIT 5 int main() { for(int i = 0, j; i < 5; ++i) { j = i; printf("Loading: %i%%", ++j); sleep(1); //system("bash -c clear"); not working //printf("\033[2J\033[1;1H"); clears whole screen with no output at all } return(0); } ```
if you print\rinstead of\nusingprintf, then it will return to the beginning of the same line instead of the next line. Then you can re-print the new status on top of the old line.
I have a piece of code that accepts the PID of a process to perform an operation upon. Aside from performing any syscalls to validate the process (something that occurs later on) is there something I can do to assert a process ID is sane? e.g. I will never accept0since that doesn't make sense for the application. Are there any concrete assertions/properties that can be utilized to do some naive sanity checking on PID values?
If you're on Linux, you can try doing aaccess("/proc/$PID/"). Or more generally, you can do akill(pid, 0)as explainedin this answerto see if the process exists. Of course, whatever you do, a syscall will be involved
I am trying to compare a c function code to the equivalent of the assembly and kind of confused on the conditional jumps I looked upjlinstruction and it says jump if < but the answer to the question was>=Can someone explain why is that?
To my understanding, the condition is inverted, but the logic is the same; the C source defines if the condition is satisfied, execute the following block whereas the assembly source defines if the condition is violated, skip the following block which means that the flow of execution will be the same in both implementations.
I have the next code in C: ``` for (i = 0; i < Nk; ++i) { // some actions using i as an index } for (; (i < (Nb * (Nr + 1))); ++i) { // another actions. Here i starts from value in previous loop } ``` Now I try to convert it to Visual Basic (in VB 6.0 really...) First part is easy: ``` For i = 0 To Nk - 1 ' my actions Next ``` But second loop confuse me a bit. Is there some way to make this loop or I just need to put some constant value here?
I got the solution: ``` For i = i To (Nb * (Nr + 1)) - 1 ' my actions Next ``` Thanks to@WhozCraig- he give the same solution to me.
This question already has answers here:What is the maximum and minimum values can be represented with 5-digit number? in 2's complement representation(2 answers)Closed6 years ago. I understand to get two's complement of an integer, we first flip the bits and add one to it but I'm having hard time figuring out Tmax and Tmin? In a 8-bit machine using two's compliment for signed integers how would I find the maximum and minimum integer values it can hold? would tmax be =01111111? and tmin =11111111?
You are close. The minimum value of a signed integer with n bits is found by making the most significant bit 1 and all the others 0. The value of this is -2^(n-1). The maximum value of a signed integer with n bits is found by making the most significant bit 0 and all the others 1. The value of this is 2^(n-1)-1. For 8 bits the range is -128...127, i.e.,10000000...01111111. Read aboutwhy this worksat Wikipedia.
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.Closed6 years ago.Improve this question I am trying buffer overflow and I encountered this error. Is there any way to stop bash from ignoring null bytes? (Was injecting shellcode). Google search did not help me much. Code ` ``` if(argc==1) { printf("Usage: %s input\n",argv[0]); exit(0); } strcpy(buf,argv[1]); printf("%s\n",buf); return 0; ``` `
Bash variables are stored as C strings. C strings are NUL-terminated. They thus cannot store NULsby definition. Consider storing each NUL-delimited component as a separate element of an array. For example: ``` pieces=( a '' bc d ); tail='efg' printf '%s\0' "${pieces[@]}"; printf '%s' "$tail" ``` ...will emita\0\0bc\0d\0efg, with a literal NUL in place of each\0.
When we declare any variable, particularly in C/C++, it is allocated in computer’s memory according to its data-type (and machine also). The question I have is, when we run the program in online IDEs, does memory of my PC/machine get used? This question is meant more for the matter of dynamically allocating memory in C, because, for whatever reason, if we misuse the pointer in arguments of function likemalloc(),calloc(), especiallyfree(), it is possible that computer memory gets damaged to some extent (Memory Leakage). Therefore, if online compilation do not use the computer memory, then I can probably use these functions on an online IDE, but I don't know what the case is. Is it safe?
Since everything runs on the remote machine, your local PC will not be affected by anything happening over there.
I need to write the value of the address of a struct in file with C language. ``` void func_1 ( struct_1 *st) ``` And the type struct_1 located at a file.h ``` struct struct_1 { target_ulong a; target_ulong b; uint32_t c; uint16_t size; } ``` I write in the file file.txt with this code ``` FILE *fp; fp=fopen("/path/to//doc.txt", "wb"); int x=sizeof((void *)st); fwrite (st, x, 100, fp); fclose(fp); ``` And the result is like that when I open the doc.txt It seems that the format of the file can't be open with gedit. can you propose another tools to open it.
the problem was with the editor who by default search the ASCII code and display character in this case i open the file in order to write in binary mode so that's why the problem occurs i used A HEXADECIMAL editor that can open and display binary file
This question already has answers here:Is this a pointer to a pointer of the start of an array?(2 answers)Closed6 years ago. I saw in internet that pointer to array and pointer to first element of array are the same things. But in CooCox next call an error: ``` //Get Arr uint8_t TestDataArr[10]; //Func get pointer to arr void InitData (TestPacks *Data) { //Some code } //This call error InitData(&TestDataArr) //But this is norm InitData(&TestDataArr[0]) ``` Why did it happen?
``` InitData(&TestDataArr) ``` is not equal to ``` InitData(&TestDataArr[0]) ``` causeTestDataArr[0]is equal to*TestDataArrand thenInitData(&TestDataArr[0])equal toInitData(&*TestDataArr)orInitData(TestDataArr). You can see, that ``` InitData(&TestDataArr) ``` is the address ofTestDataArrand ``` InitData(TestDataArr) ``` just the array. That are also different types!
I saw this code on Exam: the question is how many times this string will be printed. I thought first it will be 10 times but this is wrong. Can someone tell me why my answer is wrong. This is part of a code in the C language. ``` for (float x = 100000001.0f; x <= 100000010.0f; x += 1.0f) { printf("lbc"); } ```
Assumingxis a 32 bit floating point: Floating point values have a limited resolution.100000001is1*10^8so you lose your1at the end. If you would add1, it again gets lost because the next float value is1.00000008*10^8. You can add as many1s as you like the result will always be the same. That is the reason why your code is an endless loop.
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.Closed6 years ago.Improve this question I am trying buffer overflow and I encountered this error. Is there any way to stop bash from ignoring null bytes? (Was injecting shellcode). Google search did not help me much. Code ` ``` if(argc==1) { printf("Usage: %s input\n",argv[0]); exit(0); } strcpy(buf,argv[1]); printf("%s\n",buf); return 0; ``` `
Bash variables are stored as C strings. C strings are NUL-terminated. They thus cannot store NULsby definition. Consider storing each NUL-delimited component as a separate element of an array. For example: ``` pieces=( a '' bc d ); tail='efg' printf '%s\0' "${pieces[@]}"; printf '%s' "$tail" ``` ...will emita\0\0bc\0d\0efg, with a literal NUL in place of each\0.
When we declare any variable, particularly in C/C++, it is allocated in computer’s memory according to its data-type (and machine also). The question I have is, when we run the program in online IDEs, does memory of my PC/machine get used? This question is meant more for the matter of dynamically allocating memory in C, because, for whatever reason, if we misuse the pointer in arguments of function likemalloc(),calloc(), especiallyfree(), it is possible that computer memory gets damaged to some extent (Memory Leakage). Therefore, if online compilation do not use the computer memory, then I can probably use these functions on an online IDE, but I don't know what the case is. Is it safe?
Since everything runs on the remote machine, your local PC will not be affected by anything happening over there.
I need to write the value of the address of a struct in file with C language. ``` void func_1 ( struct_1 *st) ``` And the type struct_1 located at a file.h ``` struct struct_1 { target_ulong a; target_ulong b; uint32_t c; uint16_t size; } ``` I write in the file file.txt with this code ``` FILE *fp; fp=fopen("/path/to//doc.txt", "wb"); int x=sizeof((void *)st); fwrite (st, x, 100, fp); fclose(fp); ``` And the result is like that when I open the doc.txt It seems that the format of the file can't be open with gedit. can you propose another tools to open it.
the problem was with the editor who by default search the ASCII code and display character in this case i open the file in order to write in binary mode so that's why the problem occurs i used A HEXADECIMAL editor that can open and display binary file
This question already has answers here:Is this a pointer to a pointer of the start of an array?(2 answers)Closed6 years ago. I saw in internet that pointer to array and pointer to first element of array are the same things. But in CooCox next call an error: ``` //Get Arr uint8_t TestDataArr[10]; //Func get pointer to arr void InitData (TestPacks *Data) { //Some code } //This call error InitData(&TestDataArr) //But this is norm InitData(&TestDataArr[0]) ``` Why did it happen?
``` InitData(&TestDataArr) ``` is not equal to ``` InitData(&TestDataArr[0]) ``` causeTestDataArr[0]is equal to*TestDataArrand thenInitData(&TestDataArr[0])equal toInitData(&*TestDataArr)orInitData(TestDataArr). You can see, that ``` InitData(&TestDataArr) ``` is the address ofTestDataArrand ``` InitData(TestDataArr) ``` just the array. That are also different types!
I saw this code on Exam: the question is how many times this string will be printed. I thought first it will be 10 times but this is wrong. Can someone tell me why my answer is wrong. This is part of a code in the C language. ``` for (float x = 100000001.0f; x <= 100000010.0f; x += 1.0f) { printf("lbc"); } ```
Assumingxis a 32 bit floating point: Floating point values have a limited resolution.100000001is1*10^8so you lose your1at the end. If you would add1, it again gets lost because the next float value is1.00000008*10^8. You can add as many1s as you like the result will always be the same. That is the reason why your code is an endless loop.
My code looks like : ``` void kernel_version(char * kernel_str) { FILE * fp = fopen(log, "a"); FILE * pipe = popen("uname -r", "r"); if(fp && pipe) { // } pclose(pipe); pclose(fp); } ``` Leaks usually occur when memory is being allocated dynamically. However, I am not dynamically allocating the memory anywhere in my code. I am unable to point out the leak.
Shouldn't the last line befclose(fp)? I think that's where things are going wrong. Changepclose(fp)tofclose(fp). ``` fopen() -> fclose() popen() -> pclose() ```
I wrote this code: ``` #include <stdio.h> #define fctrl(N) ( (N==1)? (N) : (N*fctrl(N-1)) ) int main() { int m,n=7; m = fctrl(n); printf("fctrl is %d\n",m); return 0; } ``` While compiling, I got the following error: ``` /tmp/ccRODXnZ.o: In function `main': /home//Desktop/fctrl/fctrl.c:8: undefined reference to `fctrl' collect2: error: ld returned 1 exit status ``` Why was this error displayed and how can I fix it?
You are trying to define a macro that emulates a recursive function, but macros do not support recursiveness, thus the error. I would use a function instead, but you always read more inC preprocessor, recursive macros.
How can I write the address of an pointer to the standard output using only thewrite()function. (similarly to the%pflag in theprintf()function.) I'm not allowed to use anything else than 'write' 'malloc' and 'free'.
If you are trying to recodeprintf, you probably want to implement%p. Use the following steps: retrieve the value of the pointer from the argument va_list.convert that pointer to auintptr_tor whatever unsigned integer type is appropriate for the pointer size on your target architecture.convert this integer to a string in hexadecimal format with a0xprefix, as for the%#xformat.write the resulting string to the output file.
This question already has answers here:Sizeof vs Strlen(3 answers)Closed6 years ago. I try to dynamically allocate memory to a string but when I print out the size it shows 4 instead of the (11+1) bytes that should be allocated. Why does this happen? The string prints out just fine. ``` #include<stdio.h> #include<stdlib.h> #include<string.h> int main(){ char c, *string; int i=0, a=1; printf("\nEnter the string : "); string = (char *) malloc (sizeof(char)); while(c != '\n'){ c = getchar(); string = (char *) realloc (string, sizeof(char) * a); string[i] = c; a++, i++; } string[i] = '\0'; puts(string); printf("\n%d", sizeof(string)); } Input : Sample Text Output : Sample Text 4 ```
sizeof is giving you the size of char pointer which is 4 on your platform.