question
stringlengths
25
894
answer
stringlengths
4
863
If for example I usedLoadImage()to load a bitmap from file in Thread A, can I use the returnedHBITMAPin Thread B?
Yes you can, but remember a bitmap can only be selected into one DC at once. If you have two threads both drawing the same bitmap you'll need to coordinate access to it.
I want to convert an unsigned short value from MSB first to LSB first. Did the below code but its not working. Can someone point the error what i did ``` #include <iostream> using namespace std; int main() { unsigned short value = 0x000A; char *m_pCurrent = (char *)&value; short temp; temp = *(m_pCurrent+1); temp = (temp << 8) | *(unsigned char *)m_pCurrent; m_pCurrent += sizeof(short); cout << "temp " << temp << endl; return 0; } ```
Here's a simple but slow implementation: ``` #include <cstdint> const size_t USHORT_BIT = CHAR_BIT * sizeof(unsigned short); unsigned short ConvertMsbFirstToLsbFirst(const unsigned short input) { unsigned short output = 0; for (size_t offset = 0; offset < USHORT_BIT; ++offset) { output |= ((input >> offset) & 1) << (USHORT_BIT - 1 - offset); } return output; } ``` You could easily template this to work with any numeric type.
I need to run my c code from python, usually as advicedhereI do this and works perfectly: ``` from subprocess import call call(["./code", "args", "to", "code"]) ``` I would like to run the code that in order to run needs argv, as a number, so for instance normally from shell I should call simply: ``` ./code #certainNumber ``` I would like to pass a string at the call function, like: ``` D=1 str = "./code %d"(%D) call([str, "args", "to", "code"]) ``` obviously this does not work. I would like to chose from python the parameter that I need to insert in my c code. thanks
As twalberg said this works perfectly: ``` call(["./code", str(variableContainingNumber), "other", "args"]) ```
I want to store binary equivalent of decimal number inchararray by applying below code, but the problem is I am not able to hold the last bit of the decimal number. I am getting garbage values. ``` int k,j; char c[40]; j=32; scanf("%d",&k); while(k) { k=k>>1; c[j]=k|1; j--; } puts("number is"); puts(c); ```
Besides the problems noted by @SouravGhosh, you need to (5) convert from the digits 0/1 to the character values for'0'and'1'by adding in the value of the character'0'[actually Sourav noted that too], and (6) pick off the low-order bitbeforeshiftingkright by 1 bit. Here's a working version: ``` char c[40]; int j=39; c[j--]='\0'; while(k) { c[j]=(k&1)+'0'; j--; k=k>>1; } puts("number is "); puts(&c[j+1]); ```
In script languages, such as Perl and Python, I can change function in run-time. I can do something in C by changing the pointer to a function? Something like: ``` void fun1() { printf("fun1\n"); } void fun2() { printf("fun2\n"); } int main() { fun1 = &fun2; fun1(); // print "fun2" return 0; } ```
No. You can't dothat. You can regard fun1 as a placeholder for the fixed entry point of that function. The semantic you are looking for is that fromfun1=&fun2;point on every call tofun1causesfun2to be called. fun1is a value not a variable. In the same way in the statementint x=1;xis a variable and1is a value. Your code makes no more sense than thinking1=2;will compile and from that point onx=x+1;will result inxbeing incremented by 2. Just becausefun1is an identifier doesn't mean it's a variable let alone assignable.
I have this code: ``` #include <stdio.h> int main(void) { double infre = 11e10; double c = 2.99795e8; double wavelength = c/infre; double delx = 0.600000000e-04; double nperdt = 2*((int)(wavelength/delx)); double dt = 1.0/infre/(double)nperdt; printf("%.11f", dt); return 0; } ``` Nowdtis supposed to be very small. So is there any by which I can get that value upon division as currently I'm getting0.0
Well you can try for example to increase the digits showed after the ".". It seems your value rests somewhere in the range of 10^-13 and you are currently showing only the first 11 digits after the decimal point. For example"%.19f"will display a non-zero result. Additionally you can print them in exponential format using%e, which is actually the preferred solution in this situation.
I need to pass a string to inside the query when connecting to a database using C, but since I have not been using C for a long time I don't know the correct way to do it. I tried the below but that doesn't work. ``` if (mysql_query(conn, "select * from t1 where c1 = %s and c2 = %s", sptr->name, sptr->desc)) { fprintf(stderr, "%s\n", mysql_error(conn)); exit(1); } ``` also what is the easiest method to check whether the query returned an empty result set?
IIRC, you cannot use format specifiers and corresponding arguments directly insidemysql_query()function. What you need to do is Allocate one temporary buffer.usesnprintf()to print the query command in the buffercallmysql_query()with the buffer as second argument.
I was reading more about arrays vs pointers in C and wrote the following program. ``` #include <stdio.h> int arr[10] = { } ; typedef int (*type)[10] ; int main() { type val = &arr ; printf("Size is %lu\n", sizeof(val)) ; printf("Size of int is %lu\n", sizeof(int)) ; } ``` If, I execute this program, thensizeof(val)is given to be 8 andsizeof(int)is given to be 4. Ifvalis a pointer to the array with 10 elements, shouldn't it's size be 40. Why is thesizeof(val)8 ?
If val is a pointer to the array... Yes, it is, andsizeof(val)produces the size for the "pointerto the array", not the array itself. ...shouldn't it's size be 40.? No,sizeof(val)calculates the size of the operand, the "pointer" here. In your platform, the size of a pointer seems to be 64 bits, i.e., 8 bytes. So, it gives8. Also, as I mentioned, use%zuto printsize_t, the type produced bysizeofoperator.
is there a way of manipulating the stack from a timer ISR? So i can just throw away the highest frame of the stack by forcing a long-running function to exit? (I am aware of loosing the heap-allocated memory in this case) The target would probably be an ARM CPU. Best Regards
Looks like you want something likesetjmp/longjmpwith longjmp called after ISR termination. It is possible alter ISR return address such a way, that instead of returning tolong-running functionlongjmp will be called with right parameters andlong-running functionwill be aborted to the place where setjmp was called. Just another solution came in mind. May be it would be easier to restore all the registers (Stack pointer, PC, LR and others) to values they have beforelong-running functionswas called in the ISR stack frame (using assembly). In order to do that you need to save all required values (using assembly) beforelong-running functions.
I have this function: ``` void print_pol(char* pol); //or char[] printf("%s", pol); } ``` Inmain(), I call this function as below ``` print_pol("pol1"); ``` But I didn't allocate memory forchar* polin the program. So how is this possible? I know that a pointer must point to something.
"poll1"is a string literal with type length-6 array of char,char[6]. The data itself is stored in read-only memory. Your function parameterpolmay look like an array, but it is adjusted tochar*, giving you this: ``` void print_pol(char* pol){ ... ``` When you pass it the literal to the function, it decays into a pointer to its first element. No allocation is required on your side.
This question already has answers here:How to add additional libraries to Visual Studio project?(4 answers)Closed4 years ago. I'm working on a C++ project using Visual Studio 2015 I'm trying to link an external library (in this instancelibtins). The library currently resides on my desktop. I've tried editing the project settings, under Linker settings, but it doesn't give me any option to include any custom libraries. How do I do this in VS 2015?
adding to the linker is not enough you need also to add the include library: properties -> C/C++ ->general -> additional include directories
I am searching to know how to pass the enum name directly to switch case. Eg: ``` enum Flower { rose, jasmine }; switch (Flower) { case rose : //Code for rose case jasmine: //Code for jasmine } ``` Someone please help me how to do this way? I found this code portions from C. But I need the same code portions in C++. Is it possible in c++? Please help me. Thanks all
You probably want this: ``` Flower f = rose; ... switch (f) { case rose : //Code for rose case jasmine: //Code for jasmine } ```
is there a way of manipulating the stack from a timer ISR? So i can just throw away the highest frame of the stack by forcing a long-running function to exit? (I am aware of loosing the heap-allocated memory in this case) The target would probably be an ARM CPU. Best Regards
Looks like you want something likesetjmp/longjmpwith longjmp called after ISR termination. It is possible alter ISR return address such a way, that instead of returning tolong-running functionlongjmp will be called with right parameters andlong-running functionwill be aborted to the place where setjmp was called. Just another solution came in mind. May be it would be easier to restore all the registers (Stack pointer, PC, LR and others) to values they have beforelong-running functionswas called in the ISR stack frame (using assembly). In order to do that you need to save all required values (using assembly) beforelong-running functions.
I have this function: ``` void print_pol(char* pol); //or char[] printf("%s", pol); } ``` Inmain(), I call this function as below ``` print_pol("pol1"); ``` But I didn't allocate memory forchar* polin the program. So how is this possible? I know that a pointer must point to something.
"poll1"is a string literal with type length-6 array of char,char[6]. The data itself is stored in read-only memory. Your function parameterpolmay look like an array, but it is adjusted tochar*, giving you this: ``` void print_pol(char* pol){ ... ``` When you pass it the literal to the function, it decays into a pointer to its first element. No allocation is required on your side.
For example: when I round a float into an int, why should I use : int i = (int) round(f); Instead of : int i = int round(f);
What is the difference between int and (int) in C? anintis the built-in type integer and(int)isType Casting.
I came across a code whoes output I'm not able to understand.The code is- ``` int main() { int a[] = {1, 2, 3, 4, 5, 6}; int *ptr = (int*)(&a+1); printf("%d ", *(ptr-1) ); return 0; } ``` The output of above code is coming out 6, but i think that it should be 1. Please explain why it is 6.
In your question "&a" is address of the whole array a[]. If we add 1 to &a, we get “base address of a[] + sizeof(a)”. And this value is typecasted to int *. So ptr points to the memory just after 6 . ptr is typecasted to "int *" and value of *(ptr-1) is printed. Since ptr points memory after 6,so ptr – 1 points to 6.
I have a value stored as an unsigned char *. It holds the SHA1 hash of a string. Since I'm using<openssl/evp.h>to generate the hashes, I end up with anunsigned char*holding the SHA1 value. Now I want to iterate from a value until the end of the SHA1 image space. So if the value was a decimal int I would iterate withi = <original_value>andi++till I reach the max possible value of the image space. How do I do this over anunsigned char *value?
I am assuming your pointer refers to 20 bytes, for the 160 bit value. (An alternative may be text characters representing hex values for the same 160 bit meaning, but occupying more characters) You can declare a class for the data, and implement a method to increment the low order unsigned byte, test it for zero, and if zero, increment the next higher order byte, and so on.
Let's say I have the following code: ``` int i = 0; func(i++, i++); ``` The increment is happening right after returning the value? Is it guaranteed that the first argument will be 0, and the second argument will be 1?
This code is broken for two reasons: Accessing a variable twice between sequence points, for other purposes than to determine which value to store, is undefined behavior. There are no sequence points between the evaluation of function parameters. Meaning anything could happen, your program might crash & burn (or more likely display incorrect or garbage values).The order of evaluation of function parameters is unspecified behavior, meaning you can't know which one that will be evaluated first. Undefined behavior and sequence points Why are these constructs (using ++) undefined behavior?
``` #define VAL1CHK 20 #define NUM 1 #define JOIN(A,B,C) A##B##C int x = JOIN(VAL,NUM,CHK); ``` With above code my expectation was ``` int x = 20; ``` But i get compilation error as macro expands to ``` int x = VALNUMCHK; // Which is undefined ``` How to make it so thatNUMis replaced first and theJOINis used?
You can redirect theJOINoperation to another macro, which then does the actual pasting, in order to enforce expansion of its arguments: ``` #define VAL1CHK 20 #define NUM 1 #define JOIN1(A, B, C) A##B##C #define JOIN(A, B, C) JOIN1(A, B, C) int x = JOIN(VAL,NUM,CHK); ``` This technique is often used with the pasting and stringification operators in macros.
As long as I use thecharand not somewchar_ttype to declare a string willstrlen()correctly report the number ofchars in the string or are there some very specific cases I need to be aware of? Here is an example: ``` char *something = "Report all my chars, please!"; strlen(something); ```
Whatstrlendoes is basically count all bytes until it hits a zero-byte, the so-called null-terminator, character'\0'. So as long as the string contains a terminator within the bounds of the memory allocated for the string,strlenwill correctly return the number ofcharin the string. Note thatstrlencan't count the number of characters (code points) in a multi-byte encoded string (like UTF-8). It will correctly return the number of bytes in the string though.
Using sprintf and the general syntax"%A.B"I can do this: ``` double a = 0.0000005l; char myNumber[50]; sprintf(myNumber,"%.2lf",a); ``` Can I set A and B dynamically in the format string?
Yes, you can do that. You need to use an asterisk*as the field width and.*as the precision. Then, you need to supply the arguments carrying the values. Something like ``` sprintf(myNumber,"%*.*lf",A,B,a); ``` Note:AandBneed to be typeint. From theC11standard, chapter §7.21.6.1,fprintf()function ... a field width, or precision, or both, may be indicated by an asterisk. In this case, anintargument supplies the field width or precision. The arguments specifying field width, or precision, or both, shall appear (in that order) before the argument (if any) to be converted. A negative field width argument is taken as a-flag followed by a positive field width. A negative precision argument is taken as if the precision were omitted.
Suppose I have ``` #define DETUNE1 sqrt(7)-sqrt(5) #define DETUNE2 sqrt(11)-sqrt(7) ``` And I call these multiple times in my program. Are DETUNE1 and DETUNE2 calculatedeverytime it is called?
Are DETUNE1 and DETUNE2 calculated every time it is called? Very unlikely. Because you are callingsqrtwith constants, most compilers would optimize the call to thesqrtfunctions and replace it with a constant value. GCC does that at-O1. So does clang. (See live). In the general case, if you have a macro withnbeing a runtime value: ``` #define DETUNE1(n) (sqrt(n)-sqrt(n)) ``` then after the textual replacement,at leastone of thesqrtfunctions will need to calculated. Notice that your macro isnotsafe. You should have brackets around it to be safe. For example, asDETUNE1 * DETUNE1would not produce what you expect.
``` #define VAL1CHK 20 #define NUM 1 #define JOIN(A,B,C) A##B##C int x = JOIN(VAL,NUM,CHK); ``` With above code my expectation was ``` int x = 20; ``` But i get compilation error as macro expands to ``` int x = VALNUMCHK; // Which is undefined ``` How to make it so thatNUMis replaced first and theJOINis used?
You can redirect theJOINoperation to another macro, which then does the actual pasting, in order to enforce expansion of its arguments: ``` #define VAL1CHK 20 #define NUM 1 #define JOIN1(A, B, C) A##B##C #define JOIN(A, B, C) JOIN1(A, B, C) int x = JOIN(VAL,NUM,CHK); ``` This technique is often used with the pasting and stringification operators in macros.
As long as I use thecharand not somewchar_ttype to declare a string willstrlen()correctly report the number ofchars in the string or are there some very specific cases I need to be aware of? Here is an example: ``` char *something = "Report all my chars, please!"; strlen(something); ```
Whatstrlendoes is basically count all bytes until it hits a zero-byte, the so-called null-terminator, character'\0'. So as long as the string contains a terminator within the bounds of the memory allocated for the string,strlenwill correctly return the number ofcharin the string. Note thatstrlencan't count the number of characters (code points) in a multi-byte encoded string (like UTF-8). It will correctly return the number of bytes in the string though.
Using sprintf and the general syntax"%A.B"I can do this: ``` double a = 0.0000005l; char myNumber[50]; sprintf(myNumber,"%.2lf",a); ``` Can I set A and B dynamically in the format string?
Yes, you can do that. You need to use an asterisk*as the field width and.*as the precision. Then, you need to supply the arguments carrying the values. Something like ``` sprintf(myNumber,"%*.*lf",A,B,a); ``` Note:AandBneed to be typeint. From theC11standard, chapter §7.21.6.1,fprintf()function ... a field width, or precision, or both, may be indicated by an asterisk. In this case, anintargument supplies the field width or precision. The arguments specifying field width, or precision, or both, shall appear (in that order) before the argument (if any) to be converted. A negative field width argument is taken as a-flag followed by a positive field width. A negative precision argument is taken as if the precision were omitted.
Suppose I have ``` #define DETUNE1 sqrt(7)-sqrt(5) #define DETUNE2 sqrt(11)-sqrt(7) ``` And I call these multiple times in my program. Are DETUNE1 and DETUNE2 calculatedeverytime it is called?
Are DETUNE1 and DETUNE2 calculated every time it is called? Very unlikely. Because you are callingsqrtwith constants, most compilers would optimize the call to thesqrtfunctions and replace it with a constant value. GCC does that at-O1. So does clang. (See live). In the general case, if you have a macro withnbeing a runtime value: ``` #define DETUNE1(n) (sqrt(n)-sqrt(n)) ``` then after the textual replacement,at leastone of thesqrtfunctions will need to calculated. Notice that your macro isnotsafe. You should have brackets around it to be safe. For example, asDETUNE1 * DETUNE1would not produce what you expect.
``` #include <stdio.h> int main() { unsigned char y; scanf("%hhu", &y); printf("%hhu", y); return 0; } ``` This code work's fine with g++ (Dev C++), but causes stack corruption in Visual Studio (2010), is this VS bug or there is any other way to inputunsigned charin VS usingscanf();?
Sounds like VS doesn't handle%hhu:https://stackoverflow.com/a/15825386/1715829 The important detail is that you're using Windows, and presumably an outdated or non-conforming C environment (compiler and standard library). MSVCRT only supports C89 (and even then, not entirely correctly); in particular, there was no "hh" modifier in C89, and it's probably interpreting "hh" the same as "h" (i.e. short).
As far as I know the below code should not work. Yet, somehow this is OK on my compiler. Please could someone explain. ``` int main() { char *string; string = "Goo"; } ```
As far as I know the below code should not work I'm afraid, your information is wrong. ``` char *string; string = "Goo"; ``` is perfectly valid. This is basically, Define acharpointerstring.Put the base address of thestring literal"Goo"intostring. However, instead of being acharpointer, ifstringwould have been an array, then this would not have been possible as array's cannot beassigned(except definition time though brace enclosed list).
``` void removeVowels(char* array){ int i,j,v; i=0; char vowel[]={'a','e','i','o','u'}; while(array[i]!='\0') { for(v=0;v<5;v++) { if (array[i]==vowel[v]) { j=i; while(array[j]!='\0') { array[j]=array[j+1]; j++; } i--; break; } } i++; } } ``` in functionremoveVowels()if I don't includei=0; and just sayint i;why does it give segmentation fault? Isn't it automatically0? Full codehere
Isn't it automatically 0? No, it isn't. Itihas automatic storage, so its default initialization leaves it uninitialized, holding an indeterminate value. To read from it before initializing it isundefined behaviour.
I'm in the process of creating a gtk2 application which I would like drawn over all other apps at all times, I would rather use xlib to do that if it is possible here's my code so far: ``` #include <gtk/gtk.h> int main(int argc, char **argv) { gtk_init(&argc, &argv); GtkWidget *mainwin; mainwin = gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_widget_show_all (mainwin); gtk_main (); return 0; } ``` I'd like to do this in the simplest manner possible thanks
Yes it is possible and not complicated ``` #include <gtk/gtk.h> int main(int argc, char **argv) { gtk_init(&argc, &argv); GtkWidget *mainwin; mainwin = gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_window_set_keep_above ( (GtkWindow *) mainwin, TRUE); gtk_widget_show_all (mainwin); gtk_main (); return 0; } ``` gtk_window_set_keep_above does trick if window manager is cooperative.
I'm wondering what this syntax ofstrcpy()does in line 65 and 66: ``` 24 #define SEQX "TTCATA" 25 #define SEQY "TGCTCGTA" 61 M = strlen(SEQX); 62 N = strlen(SEQY); 63 x = malloc(sizeof(char) * (M+2)); /* +2: leading blank, and trailing \0 */ 64 y = malloc(sizeof(char) * (N+2)); 65 strcpy(x+1, SEQX); /* x_1..x_M now defined; x_0 undefined */ 66 strcpy(y+1, SEQY); /* y_1..y_N now defined; y_0 undefined */ ``` I know it's copyingSEQXandSEQYintoxandybut I don't understand what does the+1do? What's the formal name of this type of operation?
strcpy(x+1, SEQX);copies the SEQX into x buffer but it leaves the first byte unchanged. At the comment it says:/* +2: leading blank, and trailing \0 */. it is skipped deliberately. This is the structure of the allocated buffer: ``` +---+---+---+---+---+---+---+ | x |x+1|x+2|x+3|...| | | +---+---+---+---+---+---+---+ ```
I would like to define a template like this: ``` #define DECLARE_MY_STRUCT(name) \ #ifndef MY_STRUCT_DECLARED \ struct my_##name##_struct { \ double var; \ }; \ #define MY_STRUCT_DECLARED \ #endif ``` This would allow me to use DECLARE_MY_STRUCT template wherever I want and not get "my_struct was already defined" error. Unfortunately, gcc treats #ifndef as its preprocessor directives instead of part of template declaration and fails to build such code. Any way to workaround this? ( Except for using ``` #ifndef MY_X_STRUCT_DECLARED DECLARE_MY_STRUCT(X) #endif ``` as there may be a lot of different struct names. )
The C Standard does not allow nested pre-processor directives, so this is impossible. The#in#ifndefwould be treated as a stringizing#.
I want to read a number as an array of int, but something strange happens. ``` #include <stdlib.h> #include <stdio.h> int getNumber( int ** dst ) { int size = 0; int num = 0; scanf( "%c", &num ); while( num != 10 ) { if( (num < 48) || (num > 57) ) { printf( "This is not a number.\r\n" ); return -1; } size++; *dst = ( int * ) realloc( *dst, sizeof( int ) * size ); *dst[ size - 1 ] = ( num - 48 ); scanf( "%c", &num ); } return size; } int main() { int * number = NULL; int size = 0; size = getNumber( &number ); return 0; } ``` First iteration passes normally, but on the second iteration*dst[ size - 1 ] = ( num - 48 );fails. What is wrong?
because [ ] has higher precedence than * operator.so it behaves like*(dst[size-1])instead of(*dst)[size-1].
So I'm confused about how lib files work, I would prefer to use all lib files and no dlls but am concerned about potential conflicts of a specific type. Say you have a program that depends on lib files a1 and a2, and lib file a1 depends on lib file b1 and lib file a2 depends on lib file b2, but b1 and b2 conflict. Is this a problem? In more general terms, is every function in a lib file public, even the included libs, or are its included libs private in some manner?
Yes it is. If the conflict is that b1 and b2 have fiction with the same name and different behavior the linker will pick one of them (the first) and a2 will be served with the wrong one.
My debug CFLAGS were always-g -O0. The latter mainly to disable jumps to unexpected line while debugging. Nowadays more and more programs refuse to compile with -O0, besides,-D_FORTIFY_SOURCErequire optimizer. is it possible to compile with-O, but have predictable behavior in debugger?
If you're using GCC 4.8 or above, try using-g -Og. As explained inthe release notes: A new general optimization level, -Og, has been introduced. It addresses the need for fast compilation and a superior debugging experience while providing a reasonable level of run-time performance. Overall experience for development should be better than the default optimization level -O0.
I wrote a C function which calls a function defined inopenssl/sha.h, let's say the declaration is"helper.h"and implementation is"helper.c". Then I compiled that function using gcc and put it in a library: ``` gcc -std=c99 -lcrypto -lssl -c helper.c -o helper.o ar -rc helper.a helper.o ``` Then I wrote a cpp function that calls the function declared in"helper.h". I added ``` extern "C" { #include "helper.h" } ``` stuff in that cpp file and then I used ``` g++ test.cpp helper.a -o cpp ``` Then the ld error occurs and says I encounter undefined reference for a function defined inopenssl/sha.h. I wonder how to resolve that?
Addsslandcryptolibs to your final command in order to link these libs to your program. You must also respect the order: sincesllis usingcryptoso you must putsslfirst andcryptoafter. ``` g++ test.cpp helper.a -o cpp -lssl -lcrypto ```
I have made one string using strcpy which looks as ``` char optarg ={"30","31"} ``` How to pass the optarg in array so it will pass asdest[3][3]={"30","31"}
Your single string should not be ofchartype. A string is basically equivalent to achar*type, so to make an array of strings, make your variable achar**. Your code should look something like this: ``` int main() { //code to generate the strings here... char** optarg = //array of strings foo(optarg); } void foo(char** dest) { //do stuff with dest } ```
I have the question of the title, but If not, how could I get away with using only 4 bits to represent an integer? EDIT really my question is how. I am aware that there are 1 byte data structures in a language like c, but how could I use something like a char to store two integers?
In C or C++ you can use astructto allocate the required number of bits to a variable as given below: ``` #include <stdio.h> struct packed { unsigned char a:4, b:4; }; int main() { struct packed p; p.a = 10; p.b = 20; printf("p.a %d p.b %d size %ld\n", p.a, p.b, sizeof(struct packed)); return 0; } ``` The output isp.a 10 p.b 4 size 1, showing thatptakes only 1 byte to store, and that numbers with more than 4 bits (larger than 15) get truncated, so 20 (0x14) becomes 4. This is simpler to use than the manual bitshifting and masking used in the other answer, but it is probably not any faster.
I want to read a number as an array of int, but something strange happens. ``` #include <stdlib.h> #include <stdio.h> int getNumber( int ** dst ) { int size = 0; int num = 0; scanf( "%c", &num ); while( num != 10 ) { if( (num < 48) || (num > 57) ) { printf( "This is not a number.\r\n" ); return -1; } size++; *dst = ( int * ) realloc( *dst, sizeof( int ) * size ); *dst[ size - 1 ] = ( num - 48 ); scanf( "%c", &num ); } return size; } int main() { int * number = NULL; int size = 0; size = getNumber( &number ); return 0; } ``` First iteration passes normally, but on the second iteration*dst[ size - 1 ] = ( num - 48 );fails. What is wrong?
because [ ] has higher precedence than * operator.so it behaves like*(dst[size-1])instead of(*dst)[size-1].
``` #include <stdio.h> int main(int argc, char const *argv[]) { FILE *ls = popen("tmp.sh", "r"); char char_array[256]; while (fgets(char_array, sizeof(char_array), ls) != 0) { //NOP } char *ptr_somechar = &char_array[0]; char *pointer = "high"; if (strcmp(pointer, ptr_somechar) == 0) { printf("%s\n", "match"); } else { printf("%s\n", "not matched"); } pclose(ls); return 0; } ``` I want to compare the output with the line.tmp.shreturns a "high". Why does this code always print "not matched"?
It seems that the string"high"in file is followed by a newline character andfgetsreads that\ntoo. You need to remove that character before comparison.
I am doing an assignment in c: Basically I have a struct where it hascharandinttypes. The assignment says that I have to fill the struct fields with some predefined values. The thing is that those values are represented as hexadecimal values. Since I am a bit confused with hexadecimal, I would like to fill the fields with normal values. For example anintfiled, I would like to assign20151instead of0x4EB7. I know it works but still I am a bit worried, is there any difference between these representations?
They are 2 ways of expressing the same thing; you can use whichever makes the most sense.
``` #include <stdio.h> int main(int argc, char const *argv[]) { FILE *ls = popen("tmp.sh", "r"); char char_array[256]; while (fgets(char_array, sizeof(char_array), ls) != 0) { //NOP } char *ptr_somechar = &char_array[0]; char *pointer = "high"; if (strcmp(pointer, ptr_somechar) == 0) { printf("%s\n", "match"); } else { printf("%s\n", "not matched"); } pclose(ls); return 0; } ``` I want to compare the output with the line.tmp.shreturns a "high". Why does this code always print "not matched"?
It seems that the string"high"in file is followed by a newline character andfgetsreads that\ntoo. You need to remove that character before comparison.
I am doing an assignment in c: Basically I have a struct where it hascharandinttypes. The assignment says that I have to fill the struct fields with some predefined values. The thing is that those values are represented as hexadecimal values. Since I am a bit confused with hexadecimal, I would like to fill the fields with normal values. For example anintfiled, I would like to assign20151instead of0x4EB7. I know it works but still I am a bit worried, is there any difference between these representations?
They are 2 ways of expressing the same thing; you can use whichever makes the most sense.
I stumbled across the following cast: ``` (int (*)[10]) ``` In my opinion, this is a "pointer to pointer to int". Let's assume the following array declaration: ``` int array[10]; ``` Then I would assume that&arrayis of type(int (*)[10]) Is this correct?
It is a pointer to an integer array of size 10 and not a'pointer to a pointer of int'. For example when you pass the type ``` char arr[20][10] ``` to a function it decays to type char(*)[10] As the compiler has to know the no of columns to effectively convert a 2d array to linear allocation in memory it is not the same as type int **.
The xv6 mkfs.c file declare the variables: ``` int nblocks = 985; int nlog = LOGSIZE; int ninodes = 200; int size = 1024; ``` That declaration should work properly with inode that have 12 direct blocks and 1 indirect block, what i don't understand is why nblocks is defined as 985? The number of blocks in one inode is 140 (128 for the indirect + 12 direct), so i don't fully understand where is 985 came from and also the size of 1024. If i would understand that part i think i will be able to change the variables to support triple indirection. Thanks!
An inode takes only 32 bytes on disk (sizeof(struct inode)). Only when writing to an inode it starts to take more space (blocks) on disk. Notice this block of code: ``` bitblocks = size/(512*8) + 1; usedblocks = ninodes / IPB + 3 + bitblocks; ... assert(nblocks + usedblocks + nlog == size); ```
Consider a large project, where many types aretypedef'd, e.g. ``` typedef int age; typedef int height; ``` and some functions getting arguments of those types: ``` void printPerson(age a, height h) { printf("Age %d, Height %d\n", a, h); } ``` Is there a way to warn at compile time, if those arguments are of the wrong type, e.g. ``` age a = 30; height h = 180; printPerson(h, a); /* No warning, because a and h are both integers */ ``` Does gcc (or some static code analysis tool) have an option to warn in such cases?
There is no built-in support for this in GCC. There isa feature requestto add this, based on the Sparsenocastattribute. However, this hasn't been implemented. If you can use Sparse, though, you could do this by marking each typedef with__attribute__((nocast)). In C++ you can do this by making wrapper classes rather than typedefs, and then simply not defining implicit conversions for them.
Is there a way in C/ObjectiveC to shorten this? ``` if (a == b || a == c || a == d) { } ``` so that i would have something like this? ``` if (a == (b || c || d)) { } ``` I know the latter is not correct but what I want something that resembles plain english i.e. If "a" equals this or this or this...then do something. I find repeating the == operator a bit redundant.
If you're working with objective-c objects: ``` if([@[b,c,d] containsObject:a]) ``` Otherwise, there's no way to simplify your first implementation.
If I have this string: ``` 2011-10-08T07:07:09Z ``` is it possible to get atime_tfrom it? If so, how can this be done?
Yes, it is. First, convert it to a broken down time withstrptime(3). This gives you astruct tm, which is the structure type for a broken down time. From there, you can convert to atime_twithmktime(3). Here's an example: ``` #define _XOPEN_SOURCE #include <time.h> #include <stdio.h> #include <string.h> int main(void) { const char *date_example = "2011-10-08T07:07:09Z"; struct tm broken_down; memset(&broken_down, 0, sizeof(broken_down)); strptime(date_example, "%Y-%m-%dT%H:%M:%SZ", &broken_down); broken_down.tm_isdst = 0; // Indicates that DST is not in effect time_t epoch_time = mktime(&broken_down); // Note: this is platform dependent printf("Epoch time: %lld\n", (long long) epoch_time); return 0; } ```
I have a line in my code: ``` fprintf(f, "Timestamp, %s, %s, %s, %s, %s, %s, %s ", channels[1].title, channels[2].title, channels[3].title, channels[4].title, channels[5].title, channels[6].title, channels[7].title); ``` I'd like for the line that it ends up printing to be set equal to a variable to use later in my program. I believe this is relatively simple to do but I am very knew to programming.
What you are looking for is thesprintf() function(and its family) that prints into a buffer.
``` Min Profile Cycles [215914] Max Profile Cycles [934625] Max Profile [23] Max Profile Count [4] ``` How to print all these console output into some .txt file in c so that whenever i will call that function it will print in txt file instead of printing in console.
as your tag is C, you can fopen() in append-mode a file and instead of using printf() you use fprintf() (and fwrite() and similar) with this filehandle.
I am trying to find Length of a string w/o using library function. ``` char card[16]; //card number in char array. unsigned int cardno[16]={0}; //card number in int array for calculations. int i,length=0,len; printf("Credit Card Number[without any spaces]: "); gets(card); for(i=0;card[i]!='\0';i++); len=i; length=strlen(card); printf("%d %d",len,length); ``` But if i enter a 16 digit card number the output is 16 17 but otherwise[card number less than 16 digit] both output is same. Is this effect of pre and post increment or some other thing. Please explain.
First, you need a longer char array for a 16 digit number: ``` char card[17]; // 16 digits + `\0` ``` Then try this: ``` for(len=0; card[len] != '\0'; len++); ``` Do not rely on the value ofioutsidethe loop.
This question already has answers here:Understanding typedefs for function pointers in C(8 answers)Closed8 years ago. ``` typedef void (*Hello)(struct test1 *, test2 *, int a, int b, const int c *, int d); ``` In this case, I am confused by how to handle the struct as the argument. I have written: ``` Hello p1; (*p1)(....need some arguments to be added here); ``` Please kindly teach me how to complete this maybe sample code could help. Thanks
Here is some code ``` struct point { int x; int y; }; typedef void (*Hello)(struct point *p); void resetPoint(struct point *p) { p->x = 10; p->y = 0; } int main(void) { struct point dot; Hello p1 = resetPoint; p1(&dot); printf("%d\n",dot.x); return 0; } ```
While studying C I faced something that is completely confusing my mind. The expression is: ``` exp(V*log(i))?i%2?s:s--:s++; ``` If ternary operator is Question?Positive:Negative; I thought it was something like: ``` if(pow(i,V)==1&&(i%2)==0) s--; else s++; ``` However, thesdoes not enter in the question, should I ask what does the first expression mean? The program worked perfectly, but I could not understand why. The original program is: ``` main(){ #define V 1 int a, s=0, i; for(i=1000;i>=0;i--) exp(V*log(i))?i%2?s:s--:s++; exp(V*log(i))?printf("%d\t%d\t",-s,i):printf("%d\t%d\t", s,-i); getch(); } ```
If exp(Vlog(i)) is true then test is it odd i%2==1 if it is return s if even return s-- if exp(Vlog(i)) is false return s++ If you write it like this than is easier to see: ``` exp(V*log(i))?(i%2?s:s--):s++; ```
I have a line in my code: ``` fprintf(f, "Timestamp, %s, %s, %s, %s, %s, %s, %s ", channels[1].title, channels[2].title, channels[3].title, channels[4].title, channels[5].title, channels[6].title, channels[7].title); ``` I'd like for the line that it ends up printing to be set equal to a variable to use later in my program. I believe this is relatively simple to do but I am very knew to programming.
What you are looking for is thesprintf() function(and its family) that prints into a buffer.
``` Min Profile Cycles [215914] Max Profile Cycles [934625] Max Profile [23] Max Profile Count [4] ``` How to print all these console output into some .txt file in c so that whenever i will call that function it will print in txt file instead of printing in console.
as your tag is C, you can fopen() in append-mode a file and instead of using printf() you use fprintf() (and fwrite() and similar) with this filehandle.
I am trying to find Length of a string w/o using library function. ``` char card[16]; //card number in char array. unsigned int cardno[16]={0}; //card number in int array for calculations. int i,length=0,len; printf("Credit Card Number[without any spaces]: "); gets(card); for(i=0;card[i]!='\0';i++); len=i; length=strlen(card); printf("%d %d",len,length); ``` But if i enter a 16 digit card number the output is 16 17 but otherwise[card number less than 16 digit] both output is same. Is this effect of pre and post increment or some other thing. Please explain.
First, you need a longer char array for a 16 digit number: ``` char card[17]; // 16 digits + `\0` ``` Then try this: ``` for(len=0; card[len] != '\0'; len++); ``` Do not rely on the value ofioutsidethe loop.
This question already has answers here:Understanding typedefs for function pointers in C(8 answers)Closed8 years ago. ``` typedef void (*Hello)(struct test1 *, test2 *, int a, int b, const int c *, int d); ``` In this case, I am confused by how to handle the struct as the argument. I have written: ``` Hello p1; (*p1)(....need some arguments to be added here); ``` Please kindly teach me how to complete this maybe sample code could help. Thanks
Here is some code ``` struct point { int x; int y; }; typedef void (*Hello)(struct point *p); void resetPoint(struct point *p) { p->x = 10; p->y = 0; } int main(void) { struct point dot; Hello p1 = resetPoint; p1(&dot); printf("%d\n",dot.x); return 0; } ```
While studying C I faced something that is completely confusing my mind. The expression is: ``` exp(V*log(i))?i%2?s:s--:s++; ``` If ternary operator is Question?Positive:Negative; I thought it was something like: ``` if(pow(i,V)==1&&(i%2)==0) s--; else s++; ``` However, thesdoes not enter in the question, should I ask what does the first expression mean? The program worked perfectly, but I could not understand why. The original program is: ``` main(){ #define V 1 int a, s=0, i; for(i=1000;i>=0;i--) exp(V*log(i))?i%2?s:s--:s++; exp(V*log(i))?printf("%d\t%d\t",-s,i):printf("%d\t%d\t", s,-i); getch(); } ```
If exp(Vlog(i)) is true then test is it odd i%2==1 if it is return s if even return s-- if exp(Vlog(i)) is false return s++ If you write it like this than is easier to see: ``` exp(V*log(i))?(i%2?s:s--):s++; ```
I have an Arduino clone Edison board with an FT801 graphics chip on it. While attempting to run the example sketches with the chip I encounter a chip id error. It's reporting the chip id as 3C074D54 which doesn't match the expected FT801 constant of 10108. From what I can tell the ID should be unique so why then would their sample code include: ``` if(FT801_CHIPID != chipid) ``` Could it be a counterfeit chip? Stephen
May be when they tested the sample code, they used a chip whose ID was 10108 but on the actual board they are using the different chip. They said rightfully..You need to comment out that line to reject any chip ID checking mechanisms. Moreover you can also edit the firmware to suit your chip ID..but before doing that please read its data sheet properly and if possible then try to cross check it several time before updating your firmware.
if we have ``` int a = 1; unsigned int b = -1; ``` what is the type of expression ``` a + b; ``` can i use int to store the result?
There's a set of rules called theusual arithmetic conversionsthat specify the conversions applied when arithmetic operators are used. (If you search that term on here you will find the full list easily) In this case, theintis promoted tounsigned int, retaining the value1, so the result of the addition is well-defined to be(unsigned int)0. Since this value is not greater thanINT_MAX, you can store it in anint.
I'm wondering if there's a macro or a simple way to let the compiler increment either major, minor or revision of my code each time when I compile? By the way I'm using the ARM compiler and uVision from Keil.
To set the version is not a compiler topic. This should be done in connection with a source code control / version control system like cvs/svn/git or others. Your build id should be connected to the content of your source code database to get reproducible builds from checkouts from your version control system. Or, if your code is not already committed to your database a dirty-tag should be provided and compiled in to give the user of the software a chance to see that this is not a controlled version. Simply counting a value in a variable can be done by a Makefile or in pre- and post-build instructions which depends on the used IDE. Sorry, for keil I have no experience...
I compressed a char array by removing leading zeros from integer data and packed them tightly (without leaving spaces bit-wise). I wish to decompress it to get my original data back. The data is 8-bit and can have any number of zeros ranging from 0 to 8. I cannot exceed the 8 bit limit to store flags and cannot send another string of data as the communication speed is not reliable. I am working in C and removed the zeros by counting them and shifting.
Nice try, with just few corrections. You have to store a mark that will give you a clue how long was original value so you can decompress it back. Sure thing, there is nothing new under the moon so you can reuse such thing asVarInt: https://developers.google.com/protocol-buffers/docs/encoding#varints It's wide-spread practice and supported in many libs at broad range of lanuages
I want to know can assign#definewithunsigned char??if can how?? for example: ``` #define ACCESS_PSS {0x32,0xFD,0x6E,0x2D} int main(){ unsigned char ResponseData[100]; for (int i = 0; i <4;i++0){ if (ResponseData[i+5]==ACCESS_PSS){ //how to do this??? cout<<5<<endl; } ``` ResponseDatafrom programm get value and byte 5 ta 8 is equal withACCESS_PSS
Best way: ``` const uint8_t ACCESS_PSS [4] = {0x32,0xFD,0x6E,0x2D}; if(memcmp(&ResponseData[i+5], ACCESS_PSS, 4) == 0) ``` Alternative way (compound literal): ``` if(memcmp(&ResponseData[i+5], (uint8_t[4]){0x32,0xFD,0x6E,0x2D}, 4) == 0) ```
I am getting data packet via HTTP POST request using RESTful API.Then parsed this packet using JNI and it returns the result to java. While it running, after several HTTP POST request tomcat server crashes and shows an error"Error in /usr/bin/java: munmap_chunk(): invalid pointer: 0x00007f40b40011d0".
I got answer for this anyway.Its because of you are freeing the memory before allocating it.Thats the reason for my error. The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed.
This afternoon, I really don't know what I was doing with Operators and C. Eventually, I wrote some code which I was thinking wouldn't compile, But I don't know how it worked. The code is: ``` #include <stdio.h> int main() { int n=2; int sum = n + - + - + - + n; /* This line */ printf("%d\n", sum); return 0; } ``` And the output is: 0 I am completely confused how the code compiled and what is happening behind the scene. How does the lineint sum = n + - + - + - + n;work?
All but the first are justunary operators. ``` n + - + - + - + n ``` is equivalent to ``` n + (-(+(-(+(-(+n)))))) ``` which is in turn simply equal to ``` n + (-n) ``` after resolving all the unary operators. -nis, of course, ordinary negation;+ndoes essentially nothing (though it has the side effect of forcing integral promotion).
I have an Arduino clone Edison board with an FT801 graphics chip on it. While attempting to run the example sketches with the chip I encounter a chip id error. It's reporting the chip id as 3C074D54 which doesn't match the expected FT801 constant of 10108. From what I can tell the ID should be unique so why then would their sample code include: ``` if(FT801_CHIPID != chipid) ``` Could it be a counterfeit chip? Stephen
May be when they tested the sample code, they used a chip whose ID was 10108 but on the actual board they are using the different chip. They said rightfully..You need to comment out that line to reject any chip ID checking mechanisms. Moreover you can also edit the firmware to suit your chip ID..but before doing that please read its data sheet properly and if possible then try to cross check it several time before updating your firmware.
if we have ``` int a = 1; unsigned int b = -1; ``` what is the type of expression ``` a + b; ``` can i use int to store the result?
There's a set of rules called theusual arithmetic conversionsthat specify the conversions applied when arithmetic operators are used. (If you search that term on here you will find the full list easily) In this case, theintis promoted tounsigned int, retaining the value1, so the result of the addition is well-defined to be(unsigned int)0. Since this value is not greater thanINT_MAX, you can store it in anint.
I'm wondering if there's a macro or a simple way to let the compiler increment either major, minor or revision of my code each time when I compile? By the way I'm using the ARM compiler and uVision from Keil.
To set the version is not a compiler topic. This should be done in connection with a source code control / version control system like cvs/svn/git or others. Your build id should be connected to the content of your source code database to get reproducible builds from checkouts from your version control system. Or, if your code is not already committed to your database a dirty-tag should be provided and compiled in to give the user of the software a chance to see that this is not a controlled version. Simply counting a value in a variable can be done by a Makefile or in pre- and post-build instructions which depends on the used IDE. Sorry, for keil I have no experience...
I compressed a char array by removing leading zeros from integer data and packed them tightly (without leaving spaces bit-wise). I wish to decompress it to get my original data back. The data is 8-bit and can have any number of zeros ranging from 0 to 8. I cannot exceed the 8 bit limit to store flags and cannot send another string of data as the communication speed is not reliable. I am working in C and removed the zeros by counting them and shifting.
Nice try, with just few corrections. You have to store a mark that will give you a clue how long was original value so you can decompress it back. Sure thing, there is nothing new under the moon so you can reuse such thing asVarInt: https://developers.google.com/protocol-buffers/docs/encoding#varints It's wide-spread practice and supported in many libs at broad range of lanuages
I want to know can assign#definewithunsigned char??if can how?? for example: ``` #define ACCESS_PSS {0x32,0xFD,0x6E,0x2D} int main(){ unsigned char ResponseData[100]; for (int i = 0; i <4;i++0){ if (ResponseData[i+5]==ACCESS_PSS){ //how to do this??? cout<<5<<endl; } ``` ResponseDatafrom programm get value and byte 5 ta 8 is equal withACCESS_PSS
Best way: ``` const uint8_t ACCESS_PSS [4] = {0x32,0xFD,0x6E,0x2D}; if(memcmp(&ResponseData[i+5], ACCESS_PSS, 4) == 0) ``` Alternative way (compound literal): ``` if(memcmp(&ResponseData[i+5], (uint8_t[4]){0x32,0xFD,0x6E,0x2D}, 4) == 0) ```
I am getting data packet via HTTP POST request using RESTful API.Then parsed this packet using JNI and it returns the result to java. While it running, after several HTTP POST request tomcat server crashes and shows an error"Error in /usr/bin/java: munmap_chunk(): invalid pointer: 0x00007f40b40011d0".
I got answer for this anyway.Its because of you are freeing the memory before allocating it.Thats the reason for my error. The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed.
This afternoon, I really don't know what I was doing with Operators and C. Eventually, I wrote some code which I was thinking wouldn't compile, But I don't know how it worked. The code is: ``` #include <stdio.h> int main() { int n=2; int sum = n + - + - + - + n; /* This line */ printf("%d\n", sum); return 0; } ``` And the output is: 0 I am completely confused how the code compiled and what is happening behind the scene. How does the lineint sum = n + - + - + - + n;work?
All but the first are justunary operators. ``` n + - + - + - + n ``` is equivalent to ``` n + (-(+(-(+(-(+n)))))) ``` which is in turn simply equal to ``` n + (-n) ``` after resolving all the unary operators. -nis, of course, ordinary negation;+ndoes essentially nothing (though it has the side effect of forcing integral promotion).
I want to know can assign#definewithunsigned char??if can how?? for example: ``` #define ACCESS_PSS {0x32,0xFD,0x6E,0x2D} int main(){ unsigned char ResponseData[100]; for (int i = 0; i <4;i++0){ if (ResponseData[i+5]==ACCESS_PSS){ //how to do this??? cout<<5<<endl; } ``` ResponseDatafrom programm get value and byte 5 ta 8 is equal withACCESS_PSS
Best way: ``` const uint8_t ACCESS_PSS [4] = {0x32,0xFD,0x6E,0x2D}; if(memcmp(&ResponseData[i+5], ACCESS_PSS, 4) == 0) ``` Alternative way (compound literal): ``` if(memcmp(&ResponseData[i+5], (uint8_t[4]){0x32,0xFD,0x6E,0x2D}, 4) == 0) ```
I am getting data packet via HTTP POST request using RESTful API.Then parsed this packet using JNI and it returns the result to java. While it running, after several HTTP POST request tomcat server crashes and shows an error"Error in /usr/bin/java: munmap_chunk(): invalid pointer: 0x00007f40b40011d0".
I got answer for this anyway.Its because of you are freeing the memory before allocating it.Thats the reason for my error. The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed.
This afternoon, I really don't know what I was doing with Operators and C. Eventually, I wrote some code which I was thinking wouldn't compile, But I don't know how it worked. The code is: ``` #include <stdio.h> int main() { int n=2; int sum = n + - + - + - + n; /* This line */ printf("%d\n", sum); return 0; } ``` And the output is: 0 I am completely confused how the code compiled and what is happening behind the scene. How does the lineint sum = n + - + - + - + n;work?
All but the first are justunary operators. ``` n + - + - + - + n ``` is equivalent to ``` n + (-(+(-(+(-(+n)))))) ``` which is in turn simply equal to ``` n + (-n) ``` after resolving all the unary operators. -nis, of course, ordinary negation;+ndoes essentially nothing (though it has the side effect of forcing integral promotion).
How to I give the user the ability to name the output .txt file? Here is all I have right now. ``` FILE *f = fopen("output.txt", "a"); ```
You can read the input from user and append.txt ``` char fileName[30]; // ... scanf("%25s", fileName); // max 25 characters because .txt have 4 (25+4 = 29) strcat(fileName, ".txt"); // append .txt extension // ... FILE *f = fopen(fileName, "a"); ```
I am learning C and was trying to figure out how to increment a pointer when I have this instantiation:int A[] = {111, 222, 333}; int *q = A;and then I'm trying to increment the pointerqfrom the zero-index ofAto the next one. I write two functions: ``` void incr_ptr_single ( int *p ) { *&p = *&p + 1; } void incr_ptr_double ( int **h ) { *h = *h + 1; } ``` I understand that sayingvoid incr_ptr( int *p) { p = p+1; } inc_ptr(q);doesn't do what I want because C's functions are "pass by value". For now,incr_ptr_double(&q) == A[1]butincr_ptr_single(q) == A[0]. I'm wondering how to fix theincr_ptr_singlefunction such that it behaves likeincr_ptr_double.
One way to "fix"incr_ptr_singlewould be to have it return the incremented pointer as a function result: ``` int * incr_ptr_single ( int *p ) { return p + 1; } ``` You could then call it as: ``` q = incr_ptr_single(q); ```
Is there anyway i can look into the values of a structure after compilation?objdump -tdgives the function definitions and only the address where the structure is stored. The problem is i am getting a wrong address for one of the threads/functions in a structure when i run a program. The target mcu is lpc1347 (ARM Cortex-m3).
objdumpparses object files (products of the compiler), which are relocatable (not executable) ELF files. At this stage, there is no such notion as the memory address these compiled pieces will run at. You have the following possibilities: Link your*.objfiles into the final non-stripped (-gpassed to compiler) executable ELF image and parse it usingreadelf.Generate the linker map file by adding-Wl,-Map,file.mapto yourLDFLAGSand see the output sections and addresses your data is located at in the map file.Use a debugger/gdb.
I'm trying to understand how the I/O between processes mechanism works. I have tried to run this code: ``` #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> ... char *const paramList[] = {"/bin/cat"}; close(0); open("./my_file", O_RDONLY); execv("/bin/cat",paramList); ... ``` but got nothing going on. (it compiles, though) what did I do wrong and what does my code do?
Per thedocs forexecv: The array of pointersmustbe terminated by aNULLpointer. Thus, addNULLto the end ofparamList. If you're still having trouble, make sure to check the return values from all syscalls, and see if any of your calls are failing.
Actually, I know it's necessary to free the memory allocated with malloc(), but I wonder if I can know there is some memory left being not collected if I forget to collect it with free().
Valgrind would be your best bet http://valgrind.org/
I would like to provoke a situation where there is no file descriptor remaining. I have been thinking about 2 possibilities: Opening thousands of files randomly until the result of open is -1Set a very low number of file descriptor available (let's say stdin, stdout and stderr). How would you do it?
You can limit the number of file descriptors a process can open under Linux using ulimit. Executingulimit -n 3before running your C program should make it an error to open any more files, since stdin, stdout, and stderr take up the first 3 descriptors. An example: ``` $ ulimit -n 3 $ echo > /dev/null zsh: too many open files: /dev/null ``` The shell process itself attempts to open /dev/null to redirect stdout before closing it there, therefore it gets an error. Your C program will be fed the exact same error the first time it callsfopen,open,socket, etc (or anything that allocates a new file descriptor).
I'm usingfscanfto read someintvalues from a file. It works correctly, but the way I did it, compiler gives a few warnings. Source: ``` FILE *fp = NULL; fp = fopen(argv[1],"r"); int num; while(fscanf(fp,"%d",&num) != EOF) // This is the line 46 printf("%d ",num); ``` Warnings: ``` passing argument 1 of ‘fscanf’ from incompatible pointer type format not a string literal and no format arguments [-Wformat-security] passing argument 2 of ‘fscanf’ from incompatible pointer type Line breakpoint: main.c [line: 46] ``` What am I doing wrong?
redefine prototype of fscanf, actual code is different E.gfscanf("%d",&num). (before save?) – BLUEPIXY
hi ı am triying to take the data of files in a folder with system function this is the code ``` char path[100],command[120]; scanf("%s",&path); sprintf(command,"echo $(ls %s) > something.txt",path); system(command); ``` but when I look to the something.txt there is no new line. This is the output, all on one line with many file names omitted: ``` acpi adjtime adobe apparmor.d arch-release asound.conf ati at-spi2 avahi bash.bash_logout ... wpa_supplicant X11 xdg xinetd.d xml yaourtrc ``` I did try-e-E-noptions of echo but it didn't work. How to make a new line after each of these files?
You shouldn't useecho. Do just ``` sprintf(command,"ls %s > something.txt",path); system(command); ``` When you useechoit outputs all command line arguments to the stdout, one by one, separated by the space character. Newline character (which is output oflscommand) works as an argument separator, just as space.
I want to run a program, and allow user input on the same line. I check if the file exists, and if not, print FILE : No such file or directory ``` FILE* filename; filename = fopen(argv[2], "wb"); //validate file name if(!filename) { perror(filename); return EXIT_FAILURE; } ``` When I compile, I get the following warning: expected âconst char *â but argument is of type âstruct FILE *â
In your code above,filenameis aFILE *, not a string with the name of the file. Sinceargv[2]appears to be the filename, you could try: ``` if(!filename) { perror(argv[2]); return EXIT_FAILURE; } ``` ...but you should first check thatargv[2]is set (thatargc > 2).
This question already has answers here:Why is char[] preferred over String for passwords?(17 answers)Closed8 years ago. In a discussion one of our senior told that we should not use String for storing password in a Java project because it's a security risk. But it can be acceptable in C project. I did not get why he said that. Can anyone tell me why so?
In Java,Strings are immutable, so once you use String to store a password, there is no way that content can be changed because any change will produce new String. And the String which contains the password, will be available in memory until it got garbage collected. So it will be remain in memory for long duration which might be a security risk. But, inC language, String is anull terminated character arrayand you can set all the array elements as blank or zero, therefore the password will not be remain in memory.
Is reading from a random address safe? I know writing is undefined behaviour but how about reading only? Well, in many visual debuggers, I can see the contents of the memory in an arbitrary address. How is this done?
Since the behavior is undefined, the answer is undefined - or at the very least, erratic. If you get lucky and the random address iswithin the memory boundsof your program, it would be fine to read most likely and you'd just get random junk. If it's outside of the scope, (i.e. 0x0/NULL), you'd most likely get asegmentation fault(although again, this isn't guaranteed) which would terminate your program - if you'd consider this "safe" then yes, otherwise no.
So following: ``` double t = 244.233; int a = (int) t; ``` is not undefined behaviour since 244 can fit insideintdid I get it right? Otherwise if it was larger value instead of 244 which didn't fit inside int this would be undefined, did I get it right? I am more interested in how C does this. But is there difference in this case w.r.t to C++?
From [conv.fpint]: A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type. So, for example, converting 66666.66 to anint16_twould be undefined behavior, but converting66.66is just fine.
``` #include <stdio.h> #define rows 500 //can define rows as any number int main() { int i,j; for(i=0;i<=rows;++i) { for(j=0;j<(2*i+1);++j) { printf("* "); } printf("\n"); } return 0; } ``` So here is my code, what it does is it prints the number of rows set by #define and creates a right angle triangle. But whatever I set that number to it always prints out 1 extra row of stars, and I can't figure out why. I know I can set it asi=0;i<500;i++and just forget about the#definestatement but I'm trying to make it work with it.
You have made the condition as ``` i=0;i<=rows;++i ``` Probably a typo.It should be ``` i=0;i<rows;++i ``` as 0 to 500 means the loop runs 501 times.
Actually, I know it's necessary to free the memory allocated with malloc(), but I wonder if I can know there is some memory left being not collected if I forget to collect it with free().
Valgrind would be your best bet http://valgrind.org/
I would like to provoke a situation where there is no file descriptor remaining. I have been thinking about 2 possibilities: Opening thousands of files randomly until the result of open is -1Set a very low number of file descriptor available (let's say stdin, stdout and stderr). How would you do it?
You can limit the number of file descriptors a process can open under Linux using ulimit. Executingulimit -n 3before running your C program should make it an error to open any more files, since stdin, stdout, and stderr take up the first 3 descriptors. An example: ``` $ ulimit -n 3 $ echo > /dev/null zsh: too many open files: /dev/null ``` The shell process itself attempts to open /dev/null to redirect stdout before closing it there, therefore it gets an error. Your C program will be fed the exact same error the first time it callsfopen,open,socket, etc (or anything that allocates a new file descriptor).
I'm usingfscanfto read someintvalues from a file. It works correctly, but the way I did it, compiler gives a few warnings. Source: ``` FILE *fp = NULL; fp = fopen(argv[1],"r"); int num; while(fscanf(fp,"%d",&num) != EOF) // This is the line 46 printf("%d ",num); ``` Warnings: ``` passing argument 1 of ‘fscanf’ from incompatible pointer type format not a string literal and no format arguments [-Wformat-security] passing argument 2 of ‘fscanf’ from incompatible pointer type Line breakpoint: main.c [line: 46] ``` What am I doing wrong?
redefine prototype of fscanf, actual code is different E.gfscanf("%d",&num). (before save?) – BLUEPIXY
hi ı am triying to take the data of files in a folder with system function this is the code ``` char path[100],command[120]; scanf("%s",&path); sprintf(command,"echo $(ls %s) > something.txt",path); system(command); ``` but when I look to the something.txt there is no new line. This is the output, all on one line with many file names omitted: ``` acpi adjtime adobe apparmor.d arch-release asound.conf ati at-spi2 avahi bash.bash_logout ... wpa_supplicant X11 xdg xinetd.d xml yaourtrc ``` I did try-e-E-noptions of echo but it didn't work. How to make a new line after each of these files?
You shouldn't useecho. Do just ``` sprintf(command,"ls %s > something.txt",path); system(command); ``` When you useechoit outputs all command line arguments to the stdout, one by one, separated by the space character. Newline character (which is output oflscommand) works as an argument separator, just as space.
I want to run a program, and allow user input on the same line. I check if the file exists, and if not, print FILE : No such file or directory ``` FILE* filename; filename = fopen(argv[2], "wb"); //validate file name if(!filename) { perror(filename); return EXIT_FAILURE; } ``` When I compile, I get the following warning: expected âconst char *â but argument is of type âstruct FILE *â
In your code above,filenameis aFILE *, not a string with the name of the file. Sinceargv[2]appears to be the filename, you could try: ``` if(!filename) { perror(argv[2]); return EXIT_FAILURE; } ``` ...but you should first check thatargv[2]is set (thatargc > 2).
This question already has answers here:Why is char[] preferred over String for passwords?(17 answers)Closed8 years ago. In a discussion one of our senior told that we should not use String for storing password in a Java project because it's a security risk. But it can be acceptable in C project. I did not get why he said that. Can anyone tell me why so?
In Java,Strings are immutable, so once you use String to store a password, there is no way that content can be changed because any change will produce new String. And the String which contains the password, will be available in memory until it got garbage collected. So it will be remain in memory for long duration which might be a security risk. But, inC language, String is anull terminated character arrayand you can set all the array elements as blank or zero, therefore the password will not be remain in memory.
I was wondering if there is any way of protecting a variable for being modified once initialized (something like "constantize" a variable at runtime ). For example: ``` #include <stdio.h> #include <stdlib.h> int main(void) { int v, op; scanf( "%d", &op ); if( op == 0 ) v = 1; else v = 2; // here transform v to a constant... . . // ...and that any attempt to modify v yields to an error. . . return EXIT_SUCCESS; } ```
You can make the result of the input beconstlike this: ``` int func() { int op = 0; scanf( "%d", &op ); if( op == 0 ) return 1; else return 2; } int main() { const int v = func(); // ... } ``` NB. Of course, there is no way to prevent undefined behaviour happening later in the program which appears to changev(since undefined behaviour can, by definition, have any effect).
So I have avoid *data of 32 bit unsigned integers which represents the pixels. Is it okay for me to access one of the pixels with achar *and modify the values directly? Or is it better to store my new pixel in a temporaryuint32_tvariable and then assign with the correct pointer dereferencing or at leastmemcpy? Will I have problems with memory alignment or possibly performance depending on the hardware platform?
Yes, this is correct. The only danger would be generating a bit pattern that does not correspond to any int, but on modern systems there are no such patterns. Also, if the data type wasuint32_tspecifically, those are prohibited from having any such patterns anyway. Note that the inverse situation of using auint32_tto write multiplechars at once is not permitted (strict aliasing rule).
The man page ofnmhere:MAN NMsays that The symbol type. At least the following types are used; others are, as well, depending on the object file format. If lowercase, the symbol is usually local; if uppercase, the symbol is global (external) And underneath it has "b" and "B" for "uninitialized data section (known as BSS)" and "d" and "D" for "initialized data section" But I thought local variables always goto Stack/Heap and not to "Data" or "BSS" sections. Then what local variables is nm talking about?
"local" in this context means file scope. That is: ``` static int local_data = 1; /* initialised local data */ static int local_bss; /* uninitialised local bss */ int global_data = 1; /* initialised global data */ int global_bss; /* uninitialised global bss */ void main (void) { // Some code } ```
The man page ofnmhere:MAN NMsays that The symbol type. At least the following types are used; others are, as well, depending on the object file format. If lowercase, the symbol is usually local; if uppercase, the symbol is global (external) And underneath it has "b" and "B" for "uninitialized data section (known as BSS)" and "d" and "D" for "initialized data section" But I thought local variables always goto Stack/Heap and not to "Data" or "BSS" sections. Then what local variables is nm talking about?
"local" in this context means file scope. That is: ``` static int local_data = 1; /* initialised local data */ static int local_bss; /* uninitialised local bss */ int global_data = 1; /* initialised global data */ int global_bss; /* uninitialised global bss */ void main (void) { // Some code } ```
I observed thatrand()library function when it is called just once within a loop, it almost always produces positive numbers. ``` for (i = 0; i < 100; i++) { printf("%d\n", rand()); } ``` But when I add tworand()calls, the numbers generated now have more negative numbers. ``` for (i = 0; i < 100; i++) { printf("%d = %d\n", rand(), (rand() + rand())); } ``` Can someone explain why I am seeing negative numbers in the second case? PS: I initialize the seed before the loop assrand(time(NULL)).
rand()is defined to return an integer between0andRAND_MAX. ``` rand() + rand() ``` could overflow. What you observe is likely a result ofundefined behaviourcaused by integer overflow.
How can I determine the length, in seconds, of the Ogg Vorbis stream with libvorbis and/or libvorbisfile? As far as I can tell, there's nothing in thevorbis_infostructure that tells me the length of the stream.
Using the lower level API, you can do this withov_time_total.