question
stringlengths
25
894
answer
stringlengths
4
863
I'm currently writing a Blackjack simulator, and I'm generating n decks of cards to play with: ``` int i; int value = 1; for (i = 0; i < deck->n_cards; i++) { deck->cards[i] = value; value++; if (value == 14) value = 1; } ``` (deck->n_cards % 52 == 0) I tried an approach to write the same with modulo operations, but I can't get it away using more than 1 deck. I think that using that if is really ugly. Is there a more elegant solution to this?
I'm not familiar with Blackjack play, however I understand from your code, the values range is 1 to 13. Try this code: ``` int i; for (i = 0; i < deck->n_cards; i++) { deck->cards[i] = (i % 13) + 1; } ``` i%13 range is 0 to 12, adding one to this, makes this range 1 to 13
I was curious and find out the current piece of code does not work however I can not figure out why: ``` #include <stdio.h> void main(){ int a = 42; printf("%d\n", ++a++); } ``` It does not seem like a wrong syntax to me. Could somebody explain the error output? ``` first.c: In function ‘main’: first.c:5:17: error: lvalue required as increment operand printf("%d\n", ++a++); ```
++a++is equal to++(a++)(because ofoperator precedence), and the value returned bya++is anon-lvalue object expression(also known asrvalues). Such values are (in essence) ephemeral and can not be modified by the prefix++operator.
I am using thinger.io for my project. I send request to fetch registered devices in thinger.IO and its details by using following URL http://{myip}/v1/users/username/devices?authorization={mytoken} and i get the following response ``` [ { "device":"nodemcu", "description":"NodeMCU With ESP8266", "connection":{ "active":true, "ts":1486047553711 } } ] ``` I want to convert the ts "1486047553711" to proper date time by using Javascript or with anything possible. As I am beginner inthinger.io. Its getting hard for me to understand their document. Any help.
The number 1486047553711 is the date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. You can convert it to javascript date by passing it in the constructor. For example ``` new Date(1486047553711); ```
I'm currently writing a Blackjack simulator, and I'm generating n decks of cards to play with: ``` int i; int value = 1; for (i = 0; i < deck->n_cards; i++) { deck->cards[i] = value; value++; if (value == 14) value = 1; } ``` (deck->n_cards % 52 == 0) I tried an approach to write the same with modulo operations, but I can't get it away using more than 1 deck. I think that using that if is really ugly. Is there a more elegant solution to this?
I'm not familiar with Blackjack play, however I understand from your code, the values range is 1 to 13. Try this code: ``` int i; for (i = 0; i < deck->n_cards; i++) { deck->cards[i] = (i % 13) + 1; } ``` i%13 range is 0 to 12, adding one to this, makes this range 1 to 13
I was curious and find out the current piece of code does not work however I can not figure out why: ``` #include <stdio.h> void main(){ int a = 42; printf("%d\n", ++a++); } ``` It does not seem like a wrong syntax to me. Could somebody explain the error output? ``` first.c: In function ‘main’: first.c:5:17: error: lvalue required as increment operand printf("%d\n", ++a++); ```
++a++is equal to++(a++)(because ofoperator precedence), and the value returned bya++is anon-lvalue object expression(also known asrvalues). Such values are (in essence) ephemeral and can not be modified by the prefix++operator.
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 My question is about How to make a function to compare strings without case sensitivity, without usingstrcmpi()in C.
Just implement your own: ``` #define TO_LOWER(c) ((c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c) int my_strcmpi(char* str1, char* str2) { while (*str1 && *str2 && TO_LOWER(*str1) == TO_LOWER(*str2)) { str1++; str2++; } return TO_LOWER(*str1) - TO_LOWER(*str2); } ```
When I try to find the time complexity of this function, I come withm!. What I did is ``` T(n,m)=m*T(n-1,m-1)=m(m-1)T(n-2,m-2)=....=m!T(1,1) ``` but the answer of the time complexity isO(n). Why? ``` void f3 (int n, int m) { if (n <= 1) return; if (m > 1) return m*f3(n-1, m-1); f3(n-1, m); } ```
The recursion termination depends onn:if (n <= 1) return;There are 2 possible recursive calls:m*f3(n-1, m-1)orf3(n-1, m). (either one or the other) The argumentnis decremented after each call. As a consequence, there will be at mostncalls to the functionf3. The time complexity of the remain of the functionf3is constant. The total time complexity is thenO(n). I'd recommend you to add aprintfstatement at the begin of the function to print all the calls. That will help you to understand what is happening.
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.Closed5 years ago.Improve this question in the following code the output is30! , it should be 0. am I missing something? ``` #include <stdio.h> #define L 30 #define N2 L * L int main() { unsigned int id = 30; printf("k = %d\n", id/N2); //this prints 30 but 30/900 should be zero! printf("k = %d\n", id/900); //this prints 0 OK! return 0; } ```
Order of operations: 30 / 30 * 30is1 * 30.30 / 900is0. You need to parenthesize in your macro to get the right behaviour: ``` #define N2 (L * L) ```
Found this code in a book: ``` if(a > b) if(c > b) printf("one"); else if(c == a) printf("two"); else printf("three"); else printf("four"); ``` The question was:The program will never printa. one b. two c. three d. four The correct answer isb. twoHere, I cannot understand why it will not printtwo, as in the condition given,ccan equalaandccan be greater thanbat the same time
Ifais greater thanb, andcis not greater thanb,ccan never be equal toa. You can distribute the conditions: onewill print whena > b && c > b. twowill print whena > b && c <= b && c == a. Because ofc == a, these conditions are equivalent toc > b && c <= b, which can never be true.
``` #include <stdio.h> int main() { int a; printf(scanf("%d",&a)); return 0; } ``` I got this message "Segmentation fault (core dumped)"
Format forprintf()function is :- ``` printf(const char *format, ...) ``` You have to provide astring(format string with format specifiers) as argument for functionprintf(). You may Try :- ``` printf("%d",scanf("%d",&a)); // with format string ``` This will print1if scanning is successful . Here%dinformat stringforintegerparameter. To read and print variablea, Try :- ``` scanf("%d",&a); // reading printf("%d",a); // printing ```
I'm working with simple c/c++ console projects in Visual Studio 2017. After a build, if I run/debug it from within the IDE (Ctrl+F5orF5), there's always a strange wait of tens of seconds before it actually runs (e.g. if Iprintfon the first line of mymain(), it won't show until after the long "wait") If there's no build after this first run, and ICtrl+F5orF5again, it runs fast and normal. If then I change some source code and rebuild it, the strange wait appears again. This slows down the dev iterations so much, and definitely feels wrong. Just wonder if any guru here can point me to a solution/workaround? Thanks in advance!
OK, mystery resolved -- it's my Avira antivirus. Somehow after installing VS2017, it starts to scan each new exe I generated. After setting my dev folders as exceptions, things are a lot quicker. Finally.
I'm trying to create a C program that prints a triangular pattern according to height by only using 1, 2 and 3 to generate the patterns: ``` Enter the height: 7 Pattern: 1 22 333 1111 22222 333333 1111111 ``` I am only able to print the numbers but I do not know how to print only using 1, 2 and 3 This is my code so far: ``` printf("Enter the height: \n"); scanf("%d", &height); if(height <0 || height > 10){ printf("Please enter height within 1 to 10!"); } else{ printf("Pattern: \n"); for(row=1; row<=height; row++){ for(int col=1; col<=row; col++){ printf("%d", row ); } printf("\n"); } return 0; } ``` The output: ``` Enter the height: 7 Pattern: 1 22 333 4444 55555 666666 7777777 ``` Thank you
Just change your print statement like, ``` printf("%d", (row % 3) > 0 ? row % 3 : 3); ```
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.Closed5 years ago.Improve this question I'm working on a project and I want my program to read a strictly 5 digits number with a leading zero. How can I print the number with the leading zero included?Plus:how can I provide that my program reads 5 digits including a zero as a leading number?
I assume you want to read inintvariable. If so you can try the below solution. ``` #include<stdio.h> void main() { int a; scanf("%5d", &a); printf("%05d",a); } ```
``` #include <stdio.h> int main() { int a; printf(scanf("%d",&a)); return 0; } ``` I got this message "Segmentation fault (core dumped)"
Format forprintf()function is :- ``` printf(const char *format, ...) ``` You have to provide astring(format string with format specifiers) as argument for functionprintf(). You may Try :- ``` printf("%d",scanf("%d",&a)); // with format string ``` This will print1if scanning is successful . Here%dinformat stringforintegerparameter. To read and print variablea, Try :- ``` scanf("%d",&a); // reading printf("%d",a); // printing ```
I'm working with simple c/c++ console projects in Visual Studio 2017. After a build, if I run/debug it from within the IDE (Ctrl+F5orF5), there's always a strange wait of tens of seconds before it actually runs (e.g. if Iprintfon the first line of mymain(), it won't show until after the long "wait") If there's no build after this first run, and ICtrl+F5orF5again, it runs fast and normal. If then I change some source code and rebuild it, the strange wait appears again. This slows down the dev iterations so much, and definitely feels wrong. Just wonder if any guru here can point me to a solution/workaround? Thanks in advance!
OK, mystery resolved -- it's my Avira antivirus. Somehow after installing VS2017, it starts to scan each new exe I generated. After setting my dev folders as exceptions, things are a lot quicker. Finally.
I'm trying to create a C program that prints a triangular pattern according to height by only using 1, 2 and 3 to generate the patterns: ``` Enter the height: 7 Pattern: 1 22 333 1111 22222 333333 1111111 ``` I am only able to print the numbers but I do not know how to print only using 1, 2 and 3 This is my code so far: ``` printf("Enter the height: \n"); scanf("%d", &height); if(height <0 || height > 10){ printf("Please enter height within 1 to 10!"); } else{ printf("Pattern: \n"); for(row=1; row<=height; row++){ for(int col=1; col<=row; col++){ printf("%d", row ); } printf("\n"); } return 0; } ``` The output: ``` Enter the height: 7 Pattern: 1 22 333 4444 55555 666666 7777777 ``` Thank you
Just change your print statement like, ``` printf("%d", (row % 3) > 0 ? row % 3 : 3); ```
``` int pop(STA* stack) { if (!isEmpty(stack)) return stack->array[stack->top--] ; return '$'; } ``` What is the useage of the (return'$') in this function? What kind of value will it return?
It seems like it's just default return value in case stack is empty (which should not really happen, precondition of callingpop()should be for stack not to be empty. ) It will return 36 ( code of$)
I built a cross-compiler forsh3eb-elftargets. Now I need a libc implementation. However, when I want to buildnewlib,configurefails. Running configure: ../newlib-cygwin/configure --host=sh3eb-elf It fails. A quick look intoconfig.log: ``` configure:4435: sh3eb-elf-gcc conftest.c >&5 [...]/sh3eb-elf/sh3eb-elf/lib/gcc/sh3eb-elf/8.1.0/../../../../sh3eb-elf/bin/ld: cannot find -lc collect2: error: ld returned 1 exit status configure:4439: $? = 1 ``` Obviously the linker does not findlibcwhich is what I am trying to build here in the first place. I am confused... Are the parameters ofconfigurewrong?
I'm not sure why, but as Chrono Kitsune pointed out, using--target=sh3eb-elfdoes the trick.
I noticed thatprintf()has specifiers%Fand%f. What are the differences? The link above says%Fwill give "Decimal floating point, uppercase". I fail to see what an uppercase floating point is. Thanks!
Per the C 2018 standard, clause 7.21.6.1, paragraph 8: The F conversion specifier produces INF, INFINITY, or NAN instead of inf, infinity, or nan, respectively.
I have a portion of the code as: ``` __weak void TimingDelay_Decrement(void) { } ``` and it keeps throwing up the captioned error. I checked the web and couldn't find relevant content for the__weakcase. Any help is appreciated.
Because it is ARM Cortex gcc toolchain so the__weakis a definition of__attribute__((weak)). The easiest way to add is to amend thegcccommand line arguments:-D__weak=__attribute__((weak))
This question already has answers here:Access of static variable from one file to another file(4 answers)Closed5 years ago. Is the following code "correct"? Or would it be undefined behavior? ``` // myfile.c static char x[10][10]; char* my_function() { return x[0]; } ``` my_functionis being used in a shared library, so I would think it's not safe to access its return value outside the file/compilation-unit (due to thestatickeyword).
The variablexis notvisibleby that name outside of myfile.c, however because it resides at file scope, i.e. it has static storage duration, its lifetime is still the lifetime of the whole program. So it is valid to return a pointer to static data between source files.
I have an array: ``` unsigned char data[dataLength]; ``` and a function: ``` unsigned char* get_data(int length) ``` I want to assign the return value of the function to the variable. When I do it straight forward ``` data = get_data(length); ``` the compiler is complaining: incompatible types in assignment of ‘unsigned char*’ to ‘unsigned char [(((sizetype)(((ssizetype)frameLength) + -1)) + 1)]’ It works with memcpy: ``` memcpy(data, get_data(dataLength), dataLength); ``` but I don't want to copy the data again. Can someone help?
The way this is done in C is through parameter passing: ``` void get_data (int length, unsigned char data[length]); ``` call as: ``` get_data(dataLength, data); ``` datainside the function will now be the same object as the one allocated in the caller. No copies taken, no memcpy needed.
To handle asysfsread I need to create ashowfunction which is added to akobj_attributestructure. The prototype ofthe function is defined as: ``` ssize_t (*show)(struct kobject *kobj, struct kobj_attribute *attr, char *buf); ``` Obviously I need to write data to thebufparameter, but what is the upper limit of the number of bytes which can be written? Is it defined anywhere?
According toDocumentation/filesystems/sysfs.txt(search for "Reading/Writing Attribute Data") the buffer size is one page, orPAGE_SIZEbytes. To avoid the warning below, you can effectively only usePAGE_SIZE - 1bytes though: ``` if (ret >= (ssize_t)PAGE_SIZE) { printk("dev_attr_show: %pS returned bad count\n", dev_attr->show); } ```
If I have multiple if-statements nested inside each other which are all in a for-loop, will a break statement on the inner-most if-statement break out of the for-loop or just into the next if statement?
It will break the loop (the inner most loop that the if contains in) no matter how many if statments are nested inside. Abreakbreaks from a loop and not from if statement.
This question already has answers here:Calling C/C++ from Python? [closed](12 answers)Closed5 years ago. I made a GUI in Python and i just wanted to know how can i import a C file into python so every time a button is clicked on my GUI, different methods in the C program will be executed. I tried the 'Python' method of importing: ``` sys.path.insert(0, '/home/pi/Desktop/FTPclass.py') import FTPclass ``` That worked for the python file i imported, but when I do the same for my c file, it complains saying my "testinc" module doesn't exist. Thanks for everyone help in advance. ~Neamus
To use c file according to docs you need to first compile C code and then use the compiled file in your code here is the link. Visithttp://book.pythontips.com/en/latest/python_c_extension.html
Clang+pycparserfail to parsepythread.hheader from CPython 3.7, but this was working in CPython 3.7-dev in Travis CI. ``` opt/python/3.7.0/include/python3.7m/pythread.h:122:5: error: "Require native threads. See https://bugs.python.org/issue31370" # error "Require native threads. See https://bugs.python.org/issue31370" ``` It is not obvious whether I should trygccinstead ofclang, pass specific threading flags to compiler or extend pycparser with additional "faked" libc headers due to code not compliant with C99? More details in this issue: https://github.com/pythonnet/pythonnet/issues/609#issuecomment-412959577
This is now fixed, like Eli B. suggested it was a missing#defineto the compiler: https://github.com/pythonnet/pythonnet/blob/py37/tools/geninterop/geninterop.py#L177 "-D _POSIX_THREADS"
This question already has answers here:Calling C/C++ from Python? [closed](12 answers)Closed5 years ago. I made a GUI in Python and i just wanted to know how can i import a C file into python so every time a button is clicked on my GUI, different methods in the C program will be executed. I tried the 'Python' method of importing: ``` sys.path.insert(0, '/home/pi/Desktop/FTPclass.py') import FTPclass ``` That worked for the python file i imported, but when I do the same for my c file, it complains saying my "testinc" module doesn't exist. Thanks for everyone help in advance. ~Neamus
To use c file according to docs you need to first compile C code and then use the compiled file in your code here is the link. Visithttp://book.pythontips.com/en/latest/python_c_extension.html
Clang+pycparserfail to parsepythread.hheader from CPython 3.7, but this was working in CPython 3.7-dev in Travis CI. ``` opt/python/3.7.0/include/python3.7m/pythread.h:122:5: error: "Require native threads. See https://bugs.python.org/issue31370" # error "Require native threads. See https://bugs.python.org/issue31370" ``` It is not obvious whether I should trygccinstead ofclang, pass specific threading flags to compiler or extend pycparser with additional "faked" libc headers due to code not compliant with C99? More details in this issue: https://github.com/pythonnet/pythonnet/issues/609#issuecomment-412959577
This is now fixed, like Eli B. suggested it was a missing#defineto the compiler: https://github.com/pythonnet/pythonnet/blob/py37/tools/geninterop/geninterop.py#L177 "-D _POSIX_THREADS"
``` printf("12345678\n"); printf("%*c%*c, 2, 'a', 2, 'b'); ``` On the console, I was expecting thatawould be below3andbbelow6since the way I understand it is that I indicated two spaces before each character. However, the output shows thatais below2and,bis below4.
The reason for that, is that the number in front of a format specifier defines the field width not a margin or a padding. In the format%ns, wherenis an integer number andsis your specifier of choice,ndefines that you are reserving n spaces for what ever you will replace the specifier with. That said, if the information which replaces the specifier will need more than n spaces, it will take the spaces it needs. So if you want the lettersaandbto appear below3and6you need to reserve three spaces for each letter not two. ``` printf("%*c%*c, 3, 'a', 3, 'b'); ```
I know question sounds dumb, I can't really figure out what is wrong in this code? ``` void sort(int *arr, int size) { int min = 0; for (int i = 0; i < size - 1; i++) { for (int j = i; i < size; j++) { if (arr[min] > arr[j]) { min = j; } } if (min != i) { Swap(&arr[i], &arr[min]); } } } ``` The following code should sort thearrbut it is giving segmentation fault. I ran this code via debugger and it says the value ofjat line ``` for (int j = i; i < size; j++) ``` something like3234(not initialized) and program ends. Butjshould be0. debuger screenshort
In your secondforloop, it should bej < size, noti < size.
I was making a software where, every time after the User would enter a number, automaticallyENTERkey will be pressed (I mean, The value will be assigned without pressingENTER). Sample code: ``` #include<stdio.h> int main(){ int i, num[10]; for(i=0; i<10; i++){ scanf("%d", &num[i]); /*this is where I need help. Every time after typing a single number, the program should store the value and move on to next position without requiring the user to press ENTER. How do I do that ? */ } ```
You can use thegetch()function, but only reads a number from 0 to 9. Next, you can convert to int by using(int)(ch)-48), example: ``` char ch; ch=getch(); printf("%d", (ch - '0')); /*You can do this too*/ // printf("%d", ((int)(ch)-48)); ``` The number 48 is the '0' in the ascii table.
I have the code as below but it failed at compile error. ``` typedef struct { logic [7:0] mem_data[1024]; } mem_blk; mem_blk m_mem[]; ... ... logic [7:0] data = 'h12; m_mem[3].mem_data[0] = data; ``` the error information is : Error- [SV-RTOOBAW] Reference to out of bound array word
Dynamic arrays need to be allocated usingnew[], or a copy from an array of the same time. So you need to do ``` m_mem = new[4]; ``` Before you can referencem_mem[3]. Or maybe you meant to declare an associative array instead of a dynamic array. ``` mem_blk m_mem[bit [15:0]]; ``` Then a write tom_mem[3]allocates that entry.
``` printf("12345678\n"); printf("%*c%*c, 2, 'a', 2, 'b'); ``` On the console, I was expecting thatawould be below3andbbelow6since the way I understand it is that I indicated two spaces before each character. However, the output shows thatais below2and,bis below4.
The reason for that, is that the number in front of a format specifier defines the field width not a margin or a padding. In the format%ns, wherenis an integer number andsis your specifier of choice,ndefines that you are reserving n spaces for what ever you will replace the specifier with. That said, if the information which replaces the specifier will need more than n spaces, it will take the spaces it needs. So if you want the lettersaandbto appear below3and6you need to reserve three spaces for each letter not two. ``` printf("%*c%*c, 3, 'a', 3, 'b'); ```
I know question sounds dumb, I can't really figure out what is wrong in this code? ``` void sort(int *arr, int size) { int min = 0; for (int i = 0; i < size - 1; i++) { for (int j = i; i < size; j++) { if (arr[min] > arr[j]) { min = j; } } if (min != i) { Swap(&arr[i], &arr[min]); } } } ``` The following code should sort thearrbut it is giving segmentation fault. I ran this code via debugger and it says the value ofjat line ``` for (int j = i; i < size; j++) ``` something like3234(not initialized) and program ends. Butjshould be0. debuger screenshort
In your secondforloop, it should bej < size, noti < size.
I was making a software where, every time after the User would enter a number, automaticallyENTERkey will be pressed (I mean, The value will be assigned without pressingENTER). Sample code: ``` #include<stdio.h> int main(){ int i, num[10]; for(i=0; i<10; i++){ scanf("%d", &num[i]); /*this is where I need help. Every time after typing a single number, the program should store the value and move on to next position without requiring the user to press ENTER. How do I do that ? */ } ```
You can use thegetch()function, but only reads a number from 0 to 9. Next, you can convert to int by using(int)(ch)-48), example: ``` char ch; ch=getch(); printf("%d", (ch - '0')); /*You can do this too*/ // printf("%d", ((int)(ch)-48)); ``` The number 48 is the '0' in the ascii table.
I have the code as below but it failed at compile error. ``` typedef struct { logic [7:0] mem_data[1024]; } mem_blk; mem_blk m_mem[]; ... ... logic [7:0] data = 'h12; m_mem[3].mem_data[0] = data; ``` the error information is : Error- [SV-RTOOBAW] Reference to out of bound array word
Dynamic arrays need to be allocated usingnew[], or a copy from an array of the same time. So you need to do ``` m_mem = new[4]; ``` Before you can referencem_mem[3]. Or maybe you meant to declare an associative array instead of a dynamic array. ``` mem_blk m_mem[bit [15:0]]; ``` Then a write tom_mem[3]allocates that entry.
I was trying to compile a very simple program, which stores the base address of a string literal in apointer to charpand then printing the string using pointerpas the following: ``` #include<stdio.h> int main() { char *p = "hello"; printf("%s", p); return 0; } ``` By mistake, I saved the file with.Cextension instead of.cextension and I saw that when I compile using.Cextension there was an additional warning: ``` deprecated conversion from string constant to ‘char*’ ``` which was not there when I compiled the program with.cextension, I am usingCode::Blocks 16.01. What is actually happening here?
Apparently, your compiler conventionally treats .C files as C++ sources, where this conversion is truly deprecated. If you rename it to .cpp then the compiler output should probably stay the same.
This question already has answers here:C macro for OS X version (Lion or not) detection?(2 answers)Closed5 years ago. I want my C code to be compiled successfully on different versions of Mac OS X. One problem I have is before OS X Yosemite I need to#include <vecLib/clapack.h>to make lapack work. However, vecLib can't be founded on later versions. How can I detect the version of Mac OS X and then include the header I have depending on the system?
``` include <Availability.h> #ifdef __MAC_OS_X_VERSION_MAX_ALLOWED #if __MAC_OS_X_VERSION_MAX_ALLOWED < 101000 #include <vecLib/clapack.h> #endif #endif ```
``` #include <stdio.h> void ref(int *a,int *b) { int *t; *t = *a; *a = *b; *b = *t; } int main() { int a = 2, b = 3; ref(&a, &b); printf("a=%d,b=%d", a, b); return 0; } ```
int *t;declaring pointer like this will not create any memory meanstis pointing to nothing, accessing*t = *a;will give undefined behavior. In your case you don't need pointer to swap two variables you just need normal variable. ``` void ref(int *a,int *b){ int t; t=*a; *a=*b; *b=t; } ```
According to my limited knowledge logical operators have left-right order of evaluation. By that rule it should evaluatex && ywhich is1and then it should evaluate== 1in the if statement. But that is what not happening. Could anyone help me with this. ``` int main() { int x = 1, y = 2; if (x && y == 1) printf("true\n"); else printf("false\n"); } ```
Theorder of operationsis different than what you think. Your expression is equivalent to ``` x && (y==1) ``` which isfalsein your case.
I have the following code: ``` uint16_t BufferSize = BUFFER_SIZE; uint8_t Buffer[BUFFER_SIZE]; ``` Buffer size is 64 bytes and is filled as: ``` Buffer[0] = 'P'; Buffer[1] = 'I'; Buffer[2] = 'N'; Buffer[3] = 'G'; Buffer[4] = 0; Buffer[5] = 1; Buffer[6] = 2; Buffer[7] = 3; Buffer[8] = 4; . . . Buffer[63] = 59; ``` I am trying to print the content of the Buffer using: ``` for( i = 0; i < BufferSize; i++ ) { PRINTF(Buffer[i]); } ``` Also tried: ``` for( i = 0; i < BufferSize; i++ ) { PRINTF((const char*) Buffer[i]); } ``` But it is not working.
You should refer to the syntax ofprintf. C treats small and capital letters differently so you should write something like this: ``` printf("%c", Buffer[i]) ```
I'm writing my first Linux LKM. It's a simple chardev that has some basicread,write,open,releasefunctions with amutexlock. It compiles successfully, but when I try to open the chardev bycat /dev/kbschar, I get the following error ``` cat: /dev/kbschar: Invalid argument ``` The source code ison gitlab. I've linked to themain.cfile. You can find theMakefilein the repository The output ofdmesgis here. I also usedftrace'sfunction_graphtracer and filtered by:mod:main.Hereis the output of that. Finally, I also ranstrace cat /dev/kbscharto see where I was getting theEINVALerror.Hereis the output to that. We have theEINVALerror at line 32. Thanks for the help in advance
The last line of yourdev_openfunction: ``` return true; ``` is not good. You're supposed to return an error code (negative errno) or zero for success. Whatevertrueis (probably defined as 1 somewhere?) it's not valid.
I have the following code: ``` uint16_t BufferSize = BUFFER_SIZE; uint8_t Buffer[BUFFER_SIZE]; ``` Buffer size is 64 bytes and is filled as: ``` Buffer[0] = 'P'; Buffer[1] = 'I'; Buffer[2] = 'N'; Buffer[3] = 'G'; Buffer[4] = 0; Buffer[5] = 1; Buffer[6] = 2; Buffer[7] = 3; Buffer[8] = 4; . . . Buffer[63] = 59; ``` I am trying to print the content of the Buffer using: ``` for( i = 0; i < BufferSize; i++ ) { PRINTF(Buffer[i]); } ``` Also tried: ``` for( i = 0; i < BufferSize; i++ ) { PRINTF((const char*) Buffer[i]); } ``` But it is not working.
You should refer to the syntax ofprintf. C treats small and capital letters differently so you should write something like this: ``` printf("%c", Buffer[i]) ```
I'm writing my first Linux LKM. It's a simple chardev that has some basicread,write,open,releasefunctions with amutexlock. It compiles successfully, but when I try to open the chardev bycat /dev/kbschar, I get the following error ``` cat: /dev/kbschar: Invalid argument ``` The source code ison gitlab. I've linked to themain.cfile. You can find theMakefilein the repository The output ofdmesgis here. I also usedftrace'sfunction_graphtracer and filtered by:mod:main.Hereis the output of that. Finally, I also ranstrace cat /dev/kbscharto see where I was getting theEINVALerror.Hereis the output to that. We have theEINVALerror at line 32. Thanks for the help in advance
The last line of yourdev_openfunction: ``` return true; ``` is not good. You're supposed to return an error code (negative errno) or zero for success. Whatevertrueis (probably defined as 1 somewhere?) it's not valid.
This program gives output as 4 3 2 1. Why does it stop at 1 when no condition is given for i? Do main(10) and main(i) differ? ``` #include <stdio.h> int main() { static int i = 5; if (--i){ printf("%d ", i); main(i); } } ```
You actually have a condition: if (--i)is equivalent toif(--i != 0)
I've been trying to compile some C files to use in XCode that uses Openssl as a dependency for encryption. When compiling with clang the code compiles fine. I read a few posts on here likeSetting C++ compile flags in xcodethat says to put the flags under Other Linker Flags but I still couldn't get it to recognize it. Here is the compiling command that works on the command line: Flags in XCode: The error in XCode:
Solution thanks to @WhozCraig Add the include folder in "Header Search Paths" and library folder in "Library Search Paths" Then put -lcrypto to link the files under "Other Link Flags"
As far as I know, Objective-C is a wrapper for pure C. When we compile an Objective-C file the compiler creates pure C file and compiles it. There was an ability to see pure C code generated by the compiler using compiler flags. I used it before but I can't find them now. Could you please remind me the flags for LLVM compiler to obtain pure C code that it creates based on Objective-C file. Thank you!
``` $ clang --help | grep rewrite -rewrite-legacy-objc Rewrite Legacy Objective-C source to C++ -rewrite-objc Rewrite Objective-C source to C++ ```
This question already has answers here:Return value of printf() function in C(13 answers)Closed5 years ago. I am relatively new to C. Was solving a question and was hit with this line of code. So why is x printing the size of the string? How exactly does printf work? ``` #include <stdio.h> int main() { int x; x = printf("stackoverflow"); printf("Value of x:%d\n", x); return 0; } ``` Output: ``` 13 ```
return type of printf isintand it returns the number of characters it printed. So in your case it is returninglength of the string.
I'm studying socket programming and I learnedinet_addrfunction. But I'm confused how can I handlein_addr_ttype. inet_addrfunction returnsin_addr_ttype which isuint32_t, then do I have to useuint32_ttype variable to handle it? In the book, example handles it asunsigned longtype, but I don't understand why this way is used. ``` unsigned long conv_addr = inet_addr(addr1); // unsigned long == uint32_t? ```
You do not have to useuint32_tto handle the value returned frominet_addr. You can use any type that can represent any value that might be returned or that you might use in a calculation. But why not use theuint32_tor thein_addr_ttype?
I'm trying to learn XCB throughthis linkand write a little "library" so I don't forget what to do each time. I'm at the point where I have a window open and I'm almost ready to start drawing things. However something has confused me, in some of the earlier examples they use xcb_window_t but in the new ones the make the "window" variable a xcb_drawable_t. I just went with it before but now I'm at the section "Simple window operations" and the functions seem to use xcb_window_t as inputs. Can these be used interchangeably, or do they need to be their own thing?
There are two kinds of drawables in X11: Windows and pixmaps. Put differently: A window is a drawable and a pixmap is a drawable. Nothing else is a drawable. Every function that accepts axcb_drawable_tcan be called with either a window or a pixmap. Functions that want a window only acceptxcb_window_t.
I have started to write a driver (for the I2C device PCF8574 from NXP) forOpenBSD. Currently I compile the kernel with the official instructionhttps://www.openbsd.org/faq/faq5.htmlfrom the OpenBSD page. But when I change the code of the driver and I typemake, the whole kernel will be compiled. Not only the changed file. How can I prevent this? How can I compile a single file from the kernel and then link it with the rest of the kernel? Thanks in advance!
Some parts are always rebuilt but the full kernel is never rebuilt if you use the correct options. ``` # cd /usr/src/sys/arch/amd64/conf # config GENERIC.MP # cd ../compile/GENERIC.MP # make clean # make -j4 # make install ``` Change any source file in/usr/src/sysand then: ``` # cd /usr/src/sys/arch/amd64/compile/GENERIC.MP # make config # make -j4 # make install ``` The lastmake -j4will only build the changed files + other necessary files.
Is it possible to usestrlen()over a dynamically allocated string? FOR EXAMPLE: ``` #include <stdio.h> #include <string.h> int main () { char *input=NULL; printf ("Enter a sentence: "); scanf("%ms", &input); //Is this legit? printf ("The sentence entered is %u characters long.\n",(unsigned)strlen(input)); return 0; } ```
You can usestrlen()on any sequence ofchars ended by a'\0', the null-character akaNUL*1, which in fact equals0. It does not matter how the memory has been allocated. So yes, this also applies to "dynamically allocated" memory. *1: Not be mixed up withNULL, which is the null-pointer constant.
I am learning flatbuffers and I wish to use them in C. What I'm trying to do is writing a schema file for my structs. this is one of my structs: ``` typedef struct { unsigned short request_number; unsigned short length; unsigned short height; unsigned char *buffer; } CASH_RECEIPT_REQUEST; ``` How can i write the pointerunsigned char *bufferin my schema file?
Don't store pointers, instead store the actual data they point to: ``` table CashReceiptRequest { request_number:ushort; length:ushort; height:ushort; buffer:[ubyte]; } ``` The buffer is a "vector of ubyte", as you can see. Note that iflengthis the size of the buffer, that field can be omitted, since the size is already stored as part of the vector.
I typed this program on code blocks but it is showing error on int main line Here's the program ``` #include <stdio.h> int main() { printf("Hello"); return 0; } ``` The message return is " multiple definition of main"
The sample code is correct. It might be an IDE configuration error. Usegccto compile your code on Linux and on Windows you can installMinGWand execute from a command window.
I have written this little function: ``` int mayor(int n1, int n2, int n3, int n4, int n5) {    int mayor = n1;    for(int *p=&n2; p<=&n5; ++p)            mayor = *p;    return mayor; } ``` Is it guaranteed that the memory block that containsn1ton5is contiguous? Since I get the expected return value I hope so, but I want to know whether this is safe.
No. The variables do not have even to be in the memory - they can be (all or only some) kept in the registers. So your assumptions are wrong. If you want to have them in the contiguous chunks of memory you need to place them there yourself. ``` int mayor(int n1, int n2, int n3, int n4, int n5) { int parameters[5] = {n1,n2,n3,n4,n5}; ```
``` #include <inttypes.h> uint64_t delta = (some huge number); char outstring[80]; sprintf(outstring, "Delta of %"PRIu64 " seconds detected. Adjusting RTC\r\n", delta); ``` This results in outstring = "Delta of lu seconds detected. Adjusting RTC" obviously I'm looking for the number in outstring not "lu". What piece of syntax am I not understanding now? I'm using gcc c11 I think
Your C libraryprintfdoes not seem to supportlong longtypes. This is a common shortcoming of older MSVC libraries on Windows, when used in combinations with a port ofgcc. You should upgrade to a recent version of Microsoft Visual Studio and use that or switch to a platform with better C support such as OS/X or Linux.
I am trying to run the code at the GLFW's official documentation here:http://www.glfw.org/documentation.html I saved the code inglfw-hello-world.cand when I try to compile it, ``` clang `pkg-config --libs --static glfw3` glfw-hello-world.c ``` I get this error, ``` /tmp/glfw-hello-world-c0cd19.o: In function `main': glfw-hello-world.c:(.text+0x9d): undefined reference to `glClear' clang-6.0: error: linker command failed with exit code 1 (use -v to see invocation) ``` GCC also gives me similar errors and I believe that my-ls are correct becausepkg-configis handling that. What is that error and how can I compile it?
glfw-hello-world.c:(.text+0x9d): undefined reference to `glClear' means that the functionglClearwas not defined. glClearis a OpenGL instruction. For the use of OpenGL hou have to linke the OpenGL libraries too. For the use withgccyou have to add the options-lGL -lGLU.
I have to create some functionality that performs operations on byte arrays, that will be provided by other parts of the program. For testing and development, I've been provided the arrays as files, and simply use them as such: ``` unsigned char frame_bytes[FRAME_SIZE]; FILE *fp; fp = fopen("file.xyz", "rb"); fread(frame_bytes, sizeof(unsigned char), FRAME_SIZE, fp); // test the functionality that operates on frame_bytes ``` Now I have to test the code on an embedded environment without a file system. Is there any straightforward way to hardcode this file as a byte array?
HxD (which is very useful in itself) fromhttps://mh-nexus.de/en/hxd/has the option to export as a C array which you would then be able to compile into your application. I have no affiliation with HxD other than being a happy user.
I add an menu Item to "select" context menu, and I wont to add sub menu item to my menu item, is it possible? and if yes please tell me how. ``` ASText t = ASTextNew(); ASTextSetEncoded(t, "menu item text", (ASHostEncoding)PDGetHostEncoding()); AVMenuItem menuItem = AVMenuItemNewWithASText(t, btnAddFromCurrent, NULL, true, NO_SHORTCUT, 0, NULL, gExtensionID); AVMenuAddMenuItem(menu, menuItem, APPEND_MENUITEM); ```
In this line: AVMenuItem menuItem = AVMenuItemNewWithASText(t, btnAddFromCurrent, NULL, true, NO_SHORTCUT, 0, NULL, gExtensionID); pass anAVMenuinstance instead ofNULL
I have written this little function: ``` int mayor(int n1, int n2, int n3, int n4, int n5) {    int mayor = n1;    for(int *p=&n2; p<=&n5; ++p)            mayor = *p;    return mayor; } ``` Is it guaranteed that the memory block that containsn1ton5is contiguous? Since I get the expected return value I hope so, but I want to know whether this is safe.
No. The variables do not have even to be in the memory - they can be (all or only some) kept in the registers. So your assumptions are wrong. If you want to have them in the contiguous chunks of memory you need to place them there yourself. ``` int mayor(int n1, int n2, int n3, int n4, int n5) { int parameters[5] = {n1,n2,n3,n4,n5}; ```
``` #include <inttypes.h> uint64_t delta = (some huge number); char outstring[80]; sprintf(outstring, "Delta of %"PRIu64 " seconds detected. Adjusting RTC\r\n", delta); ``` This results in outstring = "Delta of lu seconds detected. Adjusting RTC" obviously I'm looking for the number in outstring not "lu". What piece of syntax am I not understanding now? I'm using gcc c11 I think
Your C libraryprintfdoes not seem to supportlong longtypes. This is a common shortcoming of older MSVC libraries on Windows, when used in combinations with a port ofgcc. You should upgrade to a recent version of Microsoft Visual Studio and use that or switch to a platform with better C support such as OS/X or Linux.
I am trying to run the code at the GLFW's official documentation here:http://www.glfw.org/documentation.html I saved the code inglfw-hello-world.cand when I try to compile it, ``` clang `pkg-config --libs --static glfw3` glfw-hello-world.c ``` I get this error, ``` /tmp/glfw-hello-world-c0cd19.o: In function `main': glfw-hello-world.c:(.text+0x9d): undefined reference to `glClear' clang-6.0: error: linker command failed with exit code 1 (use -v to see invocation) ``` GCC also gives me similar errors and I believe that my-ls are correct becausepkg-configis handling that. What is that error and how can I compile it?
glfw-hello-world.c:(.text+0x9d): undefined reference to `glClear' means that the functionglClearwas not defined. glClearis a OpenGL instruction. For the use of OpenGL hou have to linke the OpenGL libraries too. For the use withgccyou have to add the options-lGL -lGLU.
I have to create some functionality that performs operations on byte arrays, that will be provided by other parts of the program. For testing and development, I've been provided the arrays as files, and simply use them as such: ``` unsigned char frame_bytes[FRAME_SIZE]; FILE *fp; fp = fopen("file.xyz", "rb"); fread(frame_bytes, sizeof(unsigned char), FRAME_SIZE, fp); // test the functionality that operates on frame_bytes ``` Now I have to test the code on an embedded environment without a file system. Is there any straightforward way to hardcode this file as a byte array?
HxD (which is very useful in itself) fromhttps://mh-nexus.de/en/hxd/has the option to export as a C array which you would then be able to compile into your application. I have no affiliation with HxD other than being a happy user.
I add an menu Item to "select" context menu, and I wont to add sub menu item to my menu item, is it possible? and if yes please tell me how. ``` ASText t = ASTextNew(); ASTextSetEncoded(t, "menu item text", (ASHostEncoding)PDGetHostEncoding()); AVMenuItem menuItem = AVMenuItemNewWithASText(t, btnAddFromCurrent, NULL, true, NO_SHORTCUT, 0, NULL, gExtensionID); AVMenuAddMenuItem(menu, menuItem, APPEND_MENUITEM); ```
In this line: AVMenuItem menuItem = AVMenuItemNewWithASText(t, btnAddFromCurrent, NULL, true, NO_SHORTCUT, 0, NULL, gExtensionID); pass anAVMenuinstance instead ofNULL
I have to create some functionality that performs operations on byte arrays, that will be provided by other parts of the program. For testing and development, I've been provided the arrays as files, and simply use them as such: ``` unsigned char frame_bytes[FRAME_SIZE]; FILE *fp; fp = fopen("file.xyz", "rb"); fread(frame_bytes, sizeof(unsigned char), FRAME_SIZE, fp); // test the functionality that operates on frame_bytes ``` Now I have to test the code on an embedded environment without a file system. Is there any straightforward way to hardcode this file as a byte array?
HxD (which is very useful in itself) fromhttps://mh-nexus.de/en/hxd/has the option to export as a C array which you would then be able to compile into your application. I have no affiliation with HxD other than being a happy user.
I add an menu Item to "select" context menu, and I wont to add sub menu item to my menu item, is it possible? and if yes please tell me how. ``` ASText t = ASTextNew(); ASTextSetEncoded(t, "menu item text", (ASHostEncoding)PDGetHostEncoding()); AVMenuItem menuItem = AVMenuItemNewWithASText(t, btnAddFromCurrent, NULL, true, NO_SHORTCUT, 0, NULL, gExtensionID); AVMenuAddMenuItem(menu, menuItem, APPEND_MENUITEM); ```
In this line: AVMenuItem menuItem = AVMenuItemNewWithASText(t, btnAddFromCurrent, NULL, true, NO_SHORTCUT, 0, NULL, gExtensionID); pass anAVMenuinstance instead ofNULL
I am working on a c code which is to be run on embedded linux. I have to copy the contents of an array to a block of memory. I have defined the base address of the memory as: ``` #define BASE_ADDRESS 0x40000000 ``` Now when I memcpy the contents of an array onto the base address, I get the warning of making a pointer from integer without a cast. How do I remove this warning? This is my code: ``` unsigned int rx1_arr[64] = {0}; //some data is added to this array before memcpy memcpy(BASE_ADDRESS, &rx1_arr, 64*sizeof(int)); ```
You need to cast to the void poiner ``` memcpy((void *)BASE_ADDRESS, rx1_arr, 64*sizeof(int)); ``` there is no need of the address operator&in front of the rx1_arr. rx1_arr,&rx1_arr,&rx1_arr[0]point to the same address but have different types.
I am a beginner to ffmpeg and libavcodec in c programming on a linux machine. I want to know the difference between these API's.
av_register_allregisters absolutely everything - i.e. muxers, demuxers and protocols + it calls toavcodec_register_all.avcodec_register_allonly registers codecs. Bare codecs are seldom useful as such.
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 I've created a socket connection in c between my Raspberry Pi and another device where the Pi is the client. Is there anyway to handle TCP flags in the packets received from the server? In particular, I want certain code to execute if the response has a FIN flag.
You don't need to observe TCP flags to detect FIN.recvwill return 0. If you want to try to observe whether or notrecvwould return 0 without disturbing the buffered data on the socket, you can useMSG_PEEK, and if you need it to be non-blocking, you can combine it withMSG_DONTWAIT.
This question already has answers here:switch case: error: case label does not reduce to an integer constant(6 answers)Closed5 years ago. I want to read characters from the console and check if it is alpha numeric. From my understanding,isalnumhas the following function signature. int isalnum(int x); Why is it illegal to write switch(input) { case isalnum(input): ... ifisalnumreturns an integer value.
Seehttps://en.cppreference.com/w/c/language/switch The syntax requires caseconstant_expression:statement with constant_expression- a constant expression of the same type as the type of condition after conversions and integral promotions I.e. syntax requires constant expression.The result of a function call is not a constant expression.That is why it is illegal.
I'm compiling someone else's code written in C using gcc ARM compiler for STM32F4 ``` #define ESC_CSR_CMD_BUSY BIT(31) #define ESC_CSR_CMD_READ (BIT(31) | BIT(30)) #define ESC_CSR_CMD_WRITE BIT(31) ``` and I get an error as it appears to not know what BIT(n) is. warning: implicit declaration of function 'BIT'; did you mean '__RBIT'? is there a stdint file somewhere that defines what BIT is...? or an alternate way of writing this please.
Although the code should ship with a definition of BIT, I would guess that this is a suitable definition: ``` #define BIT(n) (1UL << (n)) ```
I want to run a basic python script inside a C program using Eclipse. This is the code: ``` #include <Python.h> int main(int argc, char *argv[]) { Py_SetProgramName(argv[0]); /* optional but recommended */ Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n"); Py_Finalize(); return 0; } ``` I am trying to link to several shared libraries like libpython2.7.so in Eclipse linker settings but I always get this error: ``` Invoking: GCC C Linker gcc -L/usr/lib/x86_64-linux-gnu/ -o "Test" ./src/Test.o -llibpython2.7 /usr/bin/x86_64-linux-gnu-ld: cannot find -llibpython2.7 collect2: error: ld returned 1 exit status ``` I can't find any tutorial with the name of the lib that should be linked.
Typically-ldoesn't require thelibprefix or the.sosuffix... Try using-lpython2.7instead of-llibpython2.7.
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 I've created a socket connection in c between my Raspberry Pi and another device where the Pi is the client. Is there anyway to handle TCP flags in the packets received from the server? In particular, I want certain code to execute if the response has a FIN flag.
You don't need to observe TCP flags to detect FIN.recvwill return 0. If you want to try to observe whether or notrecvwould return 0 without disturbing the buffered data on the socket, you can useMSG_PEEK, and if you need it to be non-blocking, you can combine it withMSG_DONTWAIT.
This question already has answers here:switch case: error: case label does not reduce to an integer constant(6 answers)Closed5 years ago. I want to read characters from the console and check if it is alpha numeric. From my understanding,isalnumhas the following function signature. int isalnum(int x); Why is it illegal to write switch(input) { case isalnum(input): ... ifisalnumreturns an integer value.
Seehttps://en.cppreference.com/w/c/language/switch The syntax requires caseconstant_expression:statement with constant_expression- a constant expression of the same type as the type of condition after conversions and integral promotions I.e. syntax requires constant expression.The result of a function call is not a constant expression.That is why it is illegal.
I'm compiling someone else's code written in C using gcc ARM compiler for STM32F4 ``` #define ESC_CSR_CMD_BUSY BIT(31) #define ESC_CSR_CMD_READ (BIT(31) | BIT(30)) #define ESC_CSR_CMD_WRITE BIT(31) ``` and I get an error as it appears to not know what BIT(n) is. warning: implicit declaration of function 'BIT'; did you mean '__RBIT'? is there a stdint file somewhere that defines what BIT is...? or an alternate way of writing this please.
Although the code should ship with a definition of BIT, I would guess that this is a suitable definition: ``` #define BIT(n) (1UL << (n)) ```
I want to run a basic python script inside a C program using Eclipse. This is the code: ``` #include <Python.h> int main(int argc, char *argv[]) { Py_SetProgramName(argv[0]); /* optional but recommended */ Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n"); Py_Finalize(); return 0; } ``` I am trying to link to several shared libraries like libpython2.7.so in Eclipse linker settings but I always get this error: ``` Invoking: GCC C Linker gcc -L/usr/lib/x86_64-linux-gnu/ -o "Test" ./src/Test.o -llibpython2.7 /usr/bin/x86_64-linux-gnu-ld: cannot find -llibpython2.7 collect2: error: ld returned 1 exit status ``` I can't find any tutorial with the name of the lib that should be linked.
Typically-ldoesn't require thelibprefix or the.sosuffix... Try using-lpython2.7instead of-llibpython2.7.
I want to run a basic python script inside a C program using Eclipse. This is the code: ``` #include <Python.h> int main(int argc, char *argv[]) { Py_SetProgramName(argv[0]); /* optional but recommended */ Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n"); Py_Finalize(); return 0; } ``` I am trying to link to several shared libraries like libpython2.7.so in Eclipse linker settings but I always get this error: ``` Invoking: GCC C Linker gcc -L/usr/lib/x86_64-linux-gnu/ -o "Test" ./src/Test.o -llibpython2.7 /usr/bin/x86_64-linux-gnu-ld: cannot find -llibpython2.7 collect2: error: ld returned 1 exit status ``` I can't find any tutorial with the name of the lib that should be linked.
Typically-ldoesn't require thelibprefix or the.sosuffix... Try using-lpython2.7instead of-llibpython2.7.
So, I want to use Mariadb. There is this Connector-C for it.https://downloads.mariadb.org/connector-c/ How do I install it? Quiet frankly, the documentation for it is horrible. Even the src file for 3.0.5 is linked to 3.0.4 page. I did not find a way to install the binary, and the documentation for building from src is quiet vague. I would prefer to know how to install both ways (binary and build from source) I'm using CentOS7 64bit.
The easiest way to install it would be to use the MariaDB package repository. ``` curl -sS https://downloads.mariadb.com/MariaDB/mariadb_repo_setup | sudo bash sudo yum -y install MariaDB-devel ``` As for building from source, these steps should work on CentOS 7. ``` sudo yum -y install git gcc openssl-devel make cmake git clone https://github.com/MariaDB/mariadb-connector-c.git mkdir build && cd build cmake ../mariadb-connector-c/ -DCMAKE_INSTALL_PREFIX=/usr make sudo make install ```
I need to be able to switch between a function in a static library and my overridden version in my main app. To do this, I'm trying to use function pointers. The problem is that I don't know how to load a static library into my program. Is this possible? Or do I have to use a DLL?
I suppose this might be possible if you have an expert level knowledge of linkers, object file formats, calling conventions, and machine language for your target platform; but static libraries are not intended for this purpose. Use a DLL.
``` main() { char a1='='; char a2='='; printf("%d",a1+a2); } ``` Code is as above , it simply perform '='+'=' and printing the value 122.(why??)..
Because ASCII value of'='is61 ASCII Values
This question already has answers here:C typedef of pointer to structure(6 answers)Closed5 years ago. I came across this struct declaration and I do not now what is the last pointer doing here? ``` typedef const struct { //Ommiting the members for stackoverflow!!! } PWMnCurrFdbkParams_t, *pPWMnCurrFdbkParams_t; ``` So the question is what is the effect of,here?what is type of*pPWMnCurrFdbkParams_twhat usecase there is to it?
This is quite common, for example Microsoft use it a lot in their header files. There are two types (comma separated) defined here,PWMnCurrFdbkParams_tis of typeconst structandpPWMnCurrFdbkParams_tis a pointer to thatconst struct. The*is not part of the name, just asint *xis wherexis a pointer to anint. Use case is almost any collection of structures, like a linked list or tree.
This question already has answers here:Signed bit field represetation(2 answers)Closed5 years ago. My tiny snippet when trying to write a bitfield and reading back gives a different value ``` #include <stdio.h> typedef struct { int a:1; int b:1; int c:1; int d:5; }node_t; int main() { node_t var; var.a = 1; var.b = 0; int a = var.a; int b = var.b; printf(" %d", a); printf(" %d", b); return 0; } ``` This gives an output: ``` -1 0 ``` How my bitfield var.a becomes -1 instead of 1?
You should be aware thatintis signed by default. Hence, when you set one bit for the integer value, you will set the sign bit of that variable to1. Hence it would be a negative value. To that end, it would be two's complement techniques.
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 My program includes the following code: ``` printf("%8lx", int); ``` And in kubuntu, when I run the program, it actually prints 16 chars, rather than 8. How is this possible?
That is correct, depending on the value of the integer. The width specifier is the minimum width, not the maximum width: "Width: Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger."
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 want to know whether size of text or binary file can be reduced without creating temporary file. So that we can delete the data present at very end of file. If yes then how. If no then why.
Yes, you can reduce file size usingtruncate()orftruncate()functions that are available on POSIX systems. For Windows, useSetFilePointerto set the current position to desired file size, then callSetEndOfFileto actually truncate it.
This question already has answers here:C typedef of pointer to structure(6 answers)Closed5 years ago. I came across this struct declaration and I do not now what is the last pointer doing here? ``` typedef const struct { //Ommiting the members for stackoverflow!!! } PWMnCurrFdbkParams_t, *pPWMnCurrFdbkParams_t; ``` So the question is what is the effect of,here?what is type of*pPWMnCurrFdbkParams_twhat usecase there is to it?
This is quite common, for example Microsoft use it a lot in their header files. There are two types (comma separated) defined here,PWMnCurrFdbkParams_tis of typeconst structandpPWMnCurrFdbkParams_tis a pointer to thatconst struct. The*is not part of the name, just asint *xis wherexis a pointer to anint. Use case is almost any collection of structures, like a linked list or tree.
The output of the following code is4. Shouldn't it be0? Since a is declared and not been defined and hence memory is not allocated for it. ``` #include <stdio.h> #include <stdlib.h> int main() { extern int a; printf("%ld",sizeof(a)); return 0; } ```
We know what the size ofais even if it is not defined in this module.sizeofdoes not tell you how much memory has been allocated for an object in this module. It tells you how much memory the object requires.
Can I use the same counter variable for aforloop inside of aforloop? Or will the variables affect each other? Should the following code use a different variable for the second loop, such asj, or isifine? ``` for(int i = 0; i < 10; i++) { for(int i = 0; i < 10; i++) { } } ```
You may use the same name (identifier). It will be a different object. They will not affect each other. Inside the inner loop, there is no way to refer to the object used in the outer loop (unless you make special provisions for that, as by providing a pointer to it). This is generally bad style, is prone to confusion, and should be avoided. The objects are different only if the inner one is defined separately, as with theint iyou have shown. If the same name is used without defining a new object, the loops will use the same object and will interfere with each other.
I have a large block of memory in my C program that contains zeros in the middle. I want to save this to disk without converting the values to ASCII. Will writing zeros to a file stream cause a false-negative EOF when I try to read from that file later? Example: ``` int x[1024] = {1, 2, 3, 4, 0, 0, 0, 0, 3}; // write x to disk in myfile.bin ``` Thanks in advance!
Null bytes in a file don't trigger EOF, even on text files. Hitting EOF is something the I/O libraries are able to detect regardless of content. As long as you usewriteorfwriteto write the memory block to disk and later usereadorfreadto read it, you should be fine.
I am wondering whether a simple macrooffset_of_requires a pointer dereference of not. For example, aC++(means that this code will be compiled using a C++ compiler) struct which is declared with packed attribute ``` struct A { int x; int y; } __attribute__(packed); ``` Suppose thatsizeof(int) == 4in this case, to calculate the offset ofyinsideA, I wrote a simple macro: ``` #define offset_of_y (ptrdiff_t)(&(((A*)0)->y)) ``` Can we be sure that the value of this macro is always4? Is there any pointer dereference from0(which may be a UB) when the macro is invoked? Many thanks for any response.
Accessing something through a null pointer is UB, period. (Unless the context is unevaluated, but in this case it IS evaluated.) You probably wantoffsetof(). In practice your code probablycouldwork, buf formally it's undefined.
I'm trying to get a list of files in the directory with libcurl from the SMB server. But I have a error: ``` curl -u "DOMAIN\login:password" smb://fs/january/soft curl: (56) Failure when receiving data from the peer curl -u "DOMAIN\login:password" smb://fs/january/soft/ curl: (56) Failure when receiving data from the peer ``` If I try to get the file then everything will be okay: ``` curl -u "DOMAIN\login:password" smb://fs/january/soft/asn1ve.rar > 1 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 9103k 100 9103k 0 0 4056k 0 0:00:02 0:00:02 --:--:-- 4055k ```
It is not currently supported by libcurl. It is howevermentioned in the TODOas something that we'd like to see added one day.
There can be several mount points under management in linux. I want to umount them all or don't umount any. Since there are cases when linux cannot umount a device (like someone is on the mount point), I want to add a function to check all mount points and see if the devices can be umounted before I actually perform umount action. Is there any functions liketrylockto test if a device is umountable? Or if there are any function to check if any user is using the mount point likelsof?
There isn't a way, AFAIK. And that's ok because your idea is flawed, it's a classic case of aTOCTOU race condition. Between checking whetherumount()would succeed and actually performing it, any other process might change the outcome.
the following short code snippet results in a invalid initializer error, and as a beginner in C, I do not understand why. ``` unsigned char MES[] = { 0x00, .... }; unsigned char *in[] = &MES; ``` Is this not the correct way to do it?
&MESis a pointer to an array ofunsigned char. inis an array of pointers tounsigned char. Try instead : ``` unsigned char (*in)[] = &MES; ``` which makesinalso a pointer to an array ofunsigned char.
I try to create CMake toolchain file for Tasking Aurix compiler (ctc) in which-coption have different meaning: ``` -c --iso=<year> ISO C standard (90, 99) (default: 99) ``` Is it possible to omit-cparameter for object files recipes or maybe it's possible to set custom template for such recipes? Currently I have ugly workaround for it so after CMake I call script which edit generated makefile's and change option-cto-c 99but preferably I would like to be able to generate valid makefile's from CMake directly.
OK I was able to find solution. To achieve it I had to overwrite default behavior by settingCMAKE_<LANG>_COMPILE_OBJECTvariable, so in my case bellow lines ``` set(target_compiler ${CMAKE_C_COMPILER}) set(CMAKE_C_FLAGS "-c 99") set(CMAKE_C_COMPILE_OBJECT "${target_compiler} <INCLUDES> <FLAGS> -o <OBJECT> <SOURCE>") ``` solved my problem
Trying to print out the decimal equivalent\n(newline) with below code. When it is executed I press enter andCtrl+Zbut nothing is printed on screen. I expect 10 to be printed. What am I missing? ``` #include <stdio.h> int main() { char ch; while ((ch = getchar() != EOF)) { if (ch == '\n') { printf("\\n=%d\n", ch); } } } ```
``` while ((ch = getchar() != EOF)) ``` This assigns the valuegetchar() != EOFtoch. You probably meant to write: ``` while ((ch = getchar()) != EOF) ``` P.S.chshould be of typeint, asEOFis a negative value whichcharisn't required to be able to represent (charmight beunsigned) and thus on some systems, you might never see this condition evaluate false ifchis (erroneously)char(thus you'd have an infinite loop on such systems).
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 have a problem in a C program: I would like to free the first element from a dynamic array but I don't know if it is possible nor how I could do it. For instance if I allocate an array A made of 10 integers like this: ``` int *A; A=(int*)malloc(sizeof(int)*10); ``` is it possible to free the first position of the array? In which way? I must optimize the program so I can't do somememcpyignoring the first element or similar stuff because it would be a slowdown.
You cannot "free" a single portion of an allocated memory block. If you want to "ignore" the first element, you could use A+1 which points to the second element.
The configuration of the Google cloud engine is 2 vCPUs, 13 GB memory, ubuntu-1604. It seems that the max memory size "malloc" can allocate is a bit less than 13GB (12GB in the following example works, mallocing 12.5GB would fail..). Is this because that the virtual memory is somehow not turned on? Any other possible reasons? ``` unsigned long input_size = 1024*1024*1024*3; unsigned int *h_data = (unsigned int *)malloc(input_size*sizeof(unsigned int)); ```
Use thefreecommand to see how much free memory you have. It will also show how much swap space you have available. The server might be configured for 13GB memory, but surely other things (like the OS) are using memory for other things, and not all 13GB are available for your application. Are you expecting to be able to malloc more memory than you have physically available, using swap space?
I try to create CMake toolchain file for Tasking Aurix compiler (ctc) in which-coption have different meaning: ``` -c --iso=<year> ISO C standard (90, 99) (default: 99) ``` Is it possible to omit-cparameter for object files recipes or maybe it's possible to set custom template for such recipes? Currently I have ugly workaround for it so after CMake I call script which edit generated makefile's and change option-cto-c 99but preferably I would like to be able to generate valid makefile's from CMake directly.
OK I was able to find solution. To achieve it I had to overwrite default behavior by settingCMAKE_<LANG>_COMPILE_OBJECTvariable, so in my case bellow lines ``` set(target_compiler ${CMAKE_C_COMPILER}) set(CMAKE_C_FLAGS "-c 99") set(CMAKE_C_COMPILE_OBJECT "${target_compiler} <INCLUDES> <FLAGS> -o <OBJECT> <SOURCE>") ``` solved my problem
Trying to print out the decimal equivalent\n(newline) with below code. When it is executed I press enter andCtrl+Zbut nothing is printed on screen. I expect 10 to be printed. What am I missing? ``` #include <stdio.h> int main() { char ch; while ((ch = getchar() != EOF)) { if (ch == '\n') { printf("\\n=%d\n", ch); } } } ```
``` while ((ch = getchar() != EOF)) ``` This assigns the valuegetchar() != EOFtoch. You probably meant to write: ``` while ((ch = getchar()) != EOF) ``` P.S.chshould be of typeint, asEOFis a negative value whichcharisn't required to be able to represent (charmight beunsigned) and thus on some systems, you might never see this condition evaluate false ifchis (erroneously)char(thus you'd have an infinite loop on such systems).