question
stringlengths
25
894
answer
stringlengths
4
863
I wrote a simple program below: ``` #include <stdio.h> unsigned int *time = 0; int main(){ printf("time = %u\n", *time); return 0; } ``` This will gives me segmentation fault on x86-64. Could someone explain the root cause?
As some of the comments mention, you are dereferencing a pointer that is pointing into an area of memory that it should not be. ``` unsigned int *time = 0; ``` is declaring a pointer to an unsigned integer, and the memory address it is pointing to is address 0x0. You are then dereferencing this pointer, which is a problem, because you are asking to read the contents at address 0x0, which results in a segmentation fault. Perhaps if you elaborate more on what you are trying to do, we could give you some additional information on how to proceed, but I'm not really sure exactly what you are going for with the above program.
I started my adventure withcmockalibrary, and I have two questions. Is it possible to find out if free() operation was made correctly? I mean, I would like to test function which is cleaning up tree structure. I've read about test_free(), but honestly I don't understand idea behind that.The second thing is case of catching standard library exceptions. I know about functionexpect_assert_failure, but how to use it? For example I would to do something what will throw segmentation fault, but I would like to pass test anyway.
You need to add ``` #define UNIT_TESTING 1 ``` before you include thecmocka.hheader file, thenmalloc,reallocand free get overridden and will warn you about memory leaks. expect_assert_failure()if for checking that anassert()condition is really hit.
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed8 years ago.Improve this question If a function, sayfoo(), is called in different ways on varius platforms, is it bad practice to use a macro? For example: ``` #ifdef WIN32 #define ffoo(a) foo(0) #else #define ffoo(a) foo(a) #endif ```
In C++ it is considered bad practice, there you have so many other possibilities like inheritance, overloading etc that it is not really needed.
Has anyone had any experience with linking libuv in xcode? I've created a submodule in git to allow easy updating to the library but I can't quite figure out how to correctly add the library to the project to allow me to include uv.h. Any help would me greatly appreciated.
You can use GYP to generate an xcodeproj for libuv (as explained in libuv's README) and add this xcodeproj to your main Xcode project. It can be automated (for easy updating) with a simple shell script (assumes you put the libuv submodule inExternals/libuv, but can be changed): ``` git submodule update --init git clone https://chromium.googlesource.com/external/gyp.git Externals/libuv/build/gyp Externals/libuv/gyp_uv.py -f xcode ``` Then you'll be able to add libuv as a dependency and to the libraries to link your target to: The last thing to do is to tell Xcode where are libuv's headers:
I have this kind of C code, and after first input, if I enter a big string, finally the latter characters are executed as command in my Linux Shell, which can be used for command injection, as I've found read() function is a main reason why this happens, but don't understand why,valis just an int: ``` if (val > 0) { struct in_addr *addr; int addrMultVal = val*sizeof(*addr); char *buf2 = malloc(addrMultVal); for (i = 0; i < val; i++) { if (read(0, buf2, sizeof(*addr)) < 0) { return 0; } } done = 1; } ```
YouraddrMultValvariable has to count the size of the type of addr, then you have tosizeof(*addr) Your code,sizeof(addr), is returning you the size of pointer, that is probably 4. Take also note thatread()doesn't add'\0'to terminate to make it string (just gives raw buffer).
Can you, please, explain me this case: ``` struct REGISTRU { int bit3:4; }; struct REGISTRU bit={13}; printf("\n%d", bit.bit3); ``` Why is the result -3 ?
We need to be very careful while using bit-fields. As you declared variable as onlyint, in C it is defaultsigned int. If you see binary value of 13, it is 1101. SoMSBis taken as sign value so you are getting -3. If you want it to take value as 13 use below code: ``` struct REGISTRU { unsigned int bit3:4; }; void main() { struct REGISTRU bit={13}; printf("\n%d", bit.bit3); } ```
C/C++: Can I access static variables inside a function from outside? For example: ``` #include <iostream> using namespace std; void f() { static int count = 3; cout << count << endl; } int main(int argc, char** argv) { f::count = 5; // apparently this is an invalid syntax. f(); return 0; } ```
No, you can't, neither in C nor in C++. If you want to maintain state associated with a function, define a class with the appropriate state and a member function. (In C++. You've also tagged the question with C; the same technique works but you need to do all the groundwork yourself.) Although they have their uses, most of the time non-const static locals are a bad idea. They make your function thread-unsafe, and they often make it "call-once".
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.Closed8 years ago.Improve this question I was wondering how can you type something in one line in C? This is the normal way it outputs. Output ``` > <text> ``` Instead ``` > <text> ```
From your tags, I'm guessing you're using printf(). Simply leave out the "\n" character, which means "newline.". In other words. printf("> "); printf("text\n"); This will print: > text
The code snippet is: ``` int main() { int a = 1, b = 2, c = 3; printf("%d", a += (a += 3, 5, a)); } ``` Though it displays 8 in the terminal as an output. But am not getting the concept behind it.
The expressiona += (a += 3, 5, a)will invoke undefined behavior. C standard says C11: 6.5.16 Assignment operators (p3): [...] The side effect of updating the stored value of the left operand is sequenced after the value computations of the left and right operands.The evaluations of the operands are unsequenced. It is not guaranteed that whether the left mostawill be evaluated before or after the evaluation of(a += 3, 5, a). That will result in undefined behavior.
I am trying to perform swap operation as shown in below program, but it seems to crash when I am copying the element b into a (line 3 in swap() method) - this happens if the input is a char string i.e, char *str; If it is a character array instead (as in char str[];) the swap operation works fine. ``` #include<stdio.h> void swap(char *a, char *b) { char tmp; tmp = *a; *a = *b; /* crash occurs here */ *b = tmp; } void func(char *a) { swap(a+1, a+2); } int main() { char *str = "abc"; // char str[] = "abc"; /* with this char array, the above swap func works */ func(str); } ``` I think this is related to some C string rules that I seem to be unaware of. Please help!
String literals areread-only, trying to modify a string literal leads toundefined behavior. Simplest solution? Declare it as an array instead: ``` char str[] = "abc"; ```
I need to know what's the address from which/bin/lsprogram execution starts (after dynamic linker fix the environment, what address gets the control?) I need it in hexadecimal (0xNNN...) or decimal format
That would be platform dependent. For a recent system, that should actually be randomized.
How do I save parameters before closing my Windows Phone Runtime app and use these parameters when I activate my app? I have a String and an int that I need to save.
You can use LocalSettings for that. Use below code to save values in to the settings ``` Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; localSettings.Values["exampleSetting"] = "test"; ``` to retrieve settings use below code ``` var value = localSettings.Values["exampleSetting"] as string; ``` More details availablehere
I'm reading code and I come across this code: for (p = prevp->s.ptr; ; prevp = p, p = p->s.ptr) How should I interpret it? Does the for loop have multiple increments? I've seen multiple conditions before, separated by comma, but I never saw multiple increments before.
In this case, on every iteration of the loop, both statements are called. It appears to be some sort of linked-list. You can clearly see how this works if you write it as a while loop: ``` p = prevp->s.ptr; while (true) { //Loop body here prevp = p; p = p->s.ptr; } ```
I have aMakefile.amwith twonoinst_LIBRARIES, and one of them needs to link with the other. Adding it to theCFLAGSthrows a compiler warning, but as far as I know, automake likes to freak out about usingLDADDwith libraries, since they are not complete programs. How can I do this, assuminglibb.aneeds to pull inliba.a?
You can't do it. Actually, what you are trying to do doesn't really make sense. Static libraries are just archives containing object files and a table of contents. Put simply, you can think of a static library as a.zipcontaining.ofiles. The linking phase only takes place when compiling a shared object or executable. When your program is linked againstliba.a, you also need to specify-static -lbor similar and that's it.
I need to read strings in the rows of a 2D array in C, use of %s qualifier and scanf is mandatory,code used is ``` int tc; scanf("%d",&tc); char ar[100][tc]; for(int i=0;i<tc;i++){ printf("\n enter the string \n"); scanf("%s",ar[][i]); printf("%s",ar[][i]); } ``` I have tried using ``` scanf("%s",ar[100*i]); ``` but i am getting an error as "expected primary-expression before ']' token".... how to do it?
It tooks liketcis test case count. You need to havechar ar[tc][100]; Then in loop, which runs tilltcis exhausted, do stuffs : ``` scanf("%s",ar[i]); // Pass address of ith string printf("%s",ar[i]); ```
This question already has answers here:What does it mean when a numeric constant in C/C++ is prefixed with a 0?(7 answers)printf with "%d" of numbers starting with 0 (ex "0102") giving unexpected answer (ex '"66")(4 answers)Closed8 years ago. With this code snippet: ``` int a = 011; printf("a = %d", a); ``` Why is the result a = 9
011is an octal value and its decimal equivalent is 9. Preceding integer literal with0indicates octal value.Use%ospecifier inprintfto print the value in octal.
I have to insert uncompressed data in between the compressed data bytes. Type 0 header in zlib allows me to do that. But How can i do that ? any clues ?
There is no type 0 allowed in a zlib header. There is a stored block type in the deflate format used within a zlib stream. zlib will automatically use stored blocks if they are smaller than the same data compressed.
I have a question related to bit-fields in C. Here I have such a structure: ``` struct Register { int bit:1; }; int main(void) { struct Register bit = {1}; printf("\nbit = %d", bit.bit); return 0; } ``` Can you please explain me why do I get: bit = -1
If you're working with bitfields, you should useunsigned int.signed intis a problem for bit-fields.
Is solving equations possible in c programming using math library? If I have two equations ``` y-y1=m1(x-x1) ``` and ``` y-y2=m2(x-x2) ``` I'll be generating the values ofm1,m2,x1,x2,y1,y2through the fomrula in the program. Will I be able to find the value ofxandy? I tried, but I couldn't.
If m1, m2, x1, x2, y1, y2 are known then using this formulae you can find them X = [(2*y1)/(m2-m1)] - [(2*m1*x1)/(m2-m1)] + [(m1*x1)/(m2-m1)] + [(m2*x2)/(m2-m1)] + [(y1+y2)/(m2-m1)] and for y: Y = [(y1+y2)/2] + [(m1+m2)*X/2] - [(m1*x1)/2] - [(m2*x2)/2] Note: In the formula for Y appears X, but if you compute it before it is not a problem
I am trying to perform swap operation as shown in below program, but it seems to crash when I am copying the element b into a (line 3 in swap() method) - this happens if the input is a char string i.e, char *str; If it is a character array instead (as in char str[];) the swap operation works fine. ``` #include<stdio.h> void swap(char *a, char *b) { char tmp; tmp = *a; *a = *b; /* crash occurs here */ *b = tmp; } void func(char *a) { swap(a+1, a+2); } int main() { char *str = "abc"; // char str[] = "abc"; /* with this char array, the above swap func works */ func(str); } ``` I think this is related to some C string rules that I seem to be unaware of. Please help!
String literals areread-only, trying to modify a string literal leads toundefined behavior. Simplest solution? Declare it as an array instead: ``` char str[] = "abc"; ```
I need to know what's the address from which/bin/lsprogram execution starts (after dynamic linker fix the environment, what address gets the control?) I need it in hexadecimal (0xNNN...) or decimal format
That would be platform dependent. For a recent system, that should actually be randomized.
How do I save parameters before closing my Windows Phone Runtime app and use these parameters when I activate my app? I have a String and an int that I need to save.
You can use LocalSettings for that. Use below code to save values in to the settings ``` Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; localSettings.Values["exampleSetting"] = "test"; ``` to retrieve settings use below code ``` var value = localSettings.Values["exampleSetting"] as string; ``` More details availablehere
I'm reading code and I come across this code: for (p = prevp->s.ptr; ; prevp = p, p = p->s.ptr) How should I interpret it? Does the for loop have multiple increments? I've seen multiple conditions before, separated by comma, but I never saw multiple increments before.
In this case, on every iteration of the loop, both statements are called. It appears to be some sort of linked-list. You can clearly see how this works if you write it as a while loop: ``` p = prevp->s.ptr; while (true) { //Loop body here prevp = p; p = p->s.ptr; } ```
I have aMakefile.amwith twonoinst_LIBRARIES, and one of them needs to link with the other. Adding it to theCFLAGSthrows a compiler warning, but as far as I know, automake likes to freak out about usingLDADDwith libraries, since they are not complete programs. How can I do this, assuminglibb.aneeds to pull inliba.a?
You can't do it. Actually, what you are trying to do doesn't really make sense. Static libraries are just archives containing object files and a table of contents. Put simply, you can think of a static library as a.zipcontaining.ofiles. The linking phase only takes place when compiling a shared object or executable. When your program is linked againstliba.a, you also need to specify-static -lbor similar and that's it.
I need to read strings in the rows of a 2D array in C, use of %s qualifier and scanf is mandatory,code used is ``` int tc; scanf("%d",&tc); char ar[100][tc]; for(int i=0;i<tc;i++){ printf("\n enter the string \n"); scanf("%s",ar[][i]); printf("%s",ar[][i]); } ``` I have tried using ``` scanf("%s",ar[100*i]); ``` but i am getting an error as "expected primary-expression before ']' token".... how to do it?
It tooks liketcis test case count. You need to havechar ar[tc][100]; Then in loop, which runs tilltcis exhausted, do stuffs : ``` scanf("%s",ar[i]); // Pass address of ith string printf("%s",ar[i]); ```
I use Visual studio 2012 and I created a x64 bit program that returns the value of the SIDT function (without the offset). The problem is that when I initially run the program, it returns the right value, but when I run the program multiple times, it returns the right value occasionally main.cpp: ``` #include <iostream> #include <conio.h> #include <stdlib.h> using namespace std; extern "C" unsigned long long int sidt_function(); int main() { printf("%llx\n", sidt_function()); _getch(); return 0; } ``` sidt_function.asm: ``` .code sidt_function proc push rbp mov rbp, rsp sub rsp, 130h sidt tbyte ptr [rbp-10] mov rax, [rbp-8] leave ret sidt_function endp end ```
Each core (physical or virtual) in a multi-core CPU has its own IDT. What you're seeing are the IDTR values for different cores in your system. None of them are incorrect.
This question already has answers here:printf("%f", aa) when aa is of type int [duplicate](2 answers)Closed8 years ago. Every time I run this program I get different and weird results. Why is that? ``` #include <stdio.h> int main(void) { int a = 5, b = 2; printf("%.2f", a/b); return 0; } ``` Live Demo
``` printf("%.2f", a/b); ``` The output of the division is again of typeintand notfloat. You are using wrong format specifier which will lead to undefined behavior.You need to have variables of type float to perform the operation you are doing. The right format specifier to print outintis%d
I need to convertchararray of C into string c++ but thechararray is an element ofstruct. Code: This is my Structure in C ``` typedef struct myStruct { char name[50]; char abc[50]; ESL_BOOL status; }MyStruct; ``` and I want to accessname[50]in c++ but for that I have to convert it into string. I have triedstrcpyandmemcpy. I am usingESL_BOOL status;and it is working but confused withname[50].
The first thing you should change in theclassname in your struct because that will likely cause problems because it is a keyword in C++. Then for converting a C string into a C++ one, you can simply use thestd::stringconstructor that accepts C-style strings. ``` std::string myCppString(MyStruct.name); ```
I have a simple OS which has its ownmakefileto build itsfloppyas output and thepicoc(a tiny c compiler) which also has its ownMakefileto built its own executable output file. Now I want to move this "picoc" to my OS which means I should move all the files to my OS and build the app inside my OS files andmakethe OS and get one output asfloppywhich has thepicocincluded. Now I have no idea how to merge these two makefiles together? (I'm not good at make files at all). Now the question is: is there anyway I can merge these two apps by merging the makefiles? I've read the related topics about my problem but none of them was about my case.
It could be something along the lines: ``` floppy: picoc command to make floppy picoc: make -C directory/of/picoc all .PHONY : picoc ``` This is more for guidelines then full solution, because I'm not sure if I understood your project structure.
I have a simple OS which has its ownmakefileto build itsfloppyas output and thepicoc(a tiny c compiler) which also has its ownMakefileto built its own executable output file. Now I want to move this "picoc" to my OS which means I should move all the files to my OS and build the app inside my OS files andmakethe OS and get one output asfloppywhich has thepicocincluded. Now I have no idea how to merge these two makefiles together? (I'm not good at make files at all). Now the question is: is there anyway I can merge these two apps by merging the makefiles? I've read the related topics about my problem but none of them was about my case.
It could be something along the lines: ``` floppy: picoc command to make floppy picoc: make -C directory/of/picoc all .PHONY : picoc ``` This is more for guidelines then full solution, because I'm not sure if I understood your project structure.
Here's a snippet of my code in C: ``` const char *d = "dictionary.dict"; struct dictionary *dict = dictionary_load_lang(d); // Compile error here ``` The type of dictionary_load_lang() isstruct dictionary *dictionary_load_lang(const char *lang). When trying to compile the compiler says "initializer element is not constant" and I can't see why. What's going on?
dictionary_load_lang()is a function, hence a non-constant. You can't use a non-constants for static storage variables (read: global and/orstatic): As per C99 Standard: Section 6.7.8: All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals. However, you can do such an initialization if within a function and for a non-static variable.
Suppose that I have a C function with the following API : ``` int c_function(int **a); ``` How should I go about declaring a Fortran array/pointer to array, and passing it to the function, assuming that the C function is responsible for memory allocation ?
You must declare a Fortan c-pointer oftype(c_ptr) ``` type(c_ptr) :: ptr ``` then call your function (with proper interface) ``` n = c_function(ptr) ``` and only then point a Fortran array pointer there ``` real, pointer :: Array(:) call c_f_pointer(ptr, Array, [n]) ``` I assumed thatnis the size of the array. You must know it, otherwise it is impossible. The interface could look like ``` interface integer(c_int) function c_function(ptr) bind(C,name="c_function") use iso_c_binding type(c_ptr) :: ptr end function end interface ```
I have two files, "abc.c" and "run" and I want to make a executable binary file which perform below two intstructions ``` gcc -m32 -O2 -Wall -DRUNTIME -shared -fPIC -o a.so abc.c -ldl LD_PRELOAD="a.so" ./run ``` I tried to use makefile in linux, but failed. Can I use makefile to make executable binary file ?
Ideally, makefile should be used for compilation. For automating the shell commands, you can use a shell script. Maybe, in your case, you can write a shell script, which will call themake -f <SomeMakeFile>command first to compile and generate the library (.so) and then run the target binary with alogwith theLD_PRELOADinstruction.
I have an uint8_t array: ``` uint8_t theArray[12] = { 0x00,0x01,0x00,0x00,0x00,0x06,0xFE,0x03,0x01,0xC1,0x00,0x01 }; ``` And I need the array that has 5 of those theArrays, but first value must change by one. 0x00, 0x01, 0x02 and so on. How can I build that array without rewriting theArray multiple times?
Simply copy an array and change the first value. ``` uint8_t array[5][12] = { { 0x00, 0x01,0x00,0x00,0x00,0x06,0xFE,0x03,0x01,0xC1,0x00,0x01 } } ; for (int i = 1; i < 5; i++ ) { array[i][0] = i; for (int j = 1; j < 12; j++ ) { array[i][j] = array[0][j]; } } ``` Typed in Safari.
I wrote two programs which prints out the variable the pointerppoints to: First program: ``` #include <stdio.h> int main (void){ int *p; int a=5, q; p=&a; q=*p; printf("%d", q); } ``` Second program: ``` #include <stdio.h> int main(void) { int a=5; int*p; p= (int*)&a; printf("%d", *p); return 0; } ``` My question: Both the programs print the value ofawhich is5. However, the second program usesp=(int*)&a;instead of justp=&a;. Could someone please tell me the significance of(int*)casting here?
Casting is a way for a programmer to tell the computer that, even though the computer thinks something is one type, we want to treat it as another type. But here the cast is of no use as here a is an integer and thus address of a will need no cast here for integer pointer.
I have an uint8_t array: ``` uint8_t theArray[12] = { 0x00,0x01,0x00,0x00,0x00,0x06,0xFE,0x03,0x01,0xC1,0x00,0x01 }; ``` And I need the array that has 5 of those theArrays, but first value must change by one. 0x00, 0x01, 0x02 and so on. How can I build that array without rewriting theArray multiple times?
Simply copy an array and change the first value. ``` uint8_t array[5][12] = { { 0x00, 0x01,0x00,0x00,0x00,0x06,0xFE,0x03,0x01,0xC1,0x00,0x01 } } ; for (int i = 1; i < 5; i++ ) { array[i][0] = i; for (int j = 1; j < 12; j++ ) { array[i][j] = array[0][j]; } } ``` Typed in Safari.
I wrote two programs which prints out the variable the pointerppoints to: First program: ``` #include <stdio.h> int main (void){ int *p; int a=5, q; p=&a; q=*p; printf("%d", q); } ``` Second program: ``` #include <stdio.h> int main(void) { int a=5; int*p; p= (int*)&a; printf("%d", *p); return 0; } ``` My question: Both the programs print the value ofawhich is5. However, the second program usesp=(int*)&a;instead of justp=&a;. Could someone please tell me the significance of(int*)casting here?
Casting is a way for a programmer to tell the computer that, even though the computer thinks something is one type, we want to treat it as another type. But here the cast is of no use as here a is an integer and thus address of a will need no cast here for integer pointer.
Theintversions of the overflow-checking add/subtract/multiply builtins in GCC return anintresult (good), and thelong intversions return along intresult (also good), but thelong long intversions return along intresult (not good). Why is this? It seems insane to me. Example: ``` bool __builtin_uadd_overflow (unsigned int a, unsigned int b, unsigned int *res) bool __builtin_uaddl_overflow (unsigned long int a, unsigned long int b, unsigned long int *res) bool __builtin_uaddll_overflow (unsigned long long int a, unsigned long long int b, unsigned long int *res) ``` This is so broken, I can't even believe it. It means that on a target wherelongandlong longare different sizes (for example, 32-bit ARM iOS targets), thellversions of the functions are completely useless.
This is a bug in GCC that hasn't been fixed yet. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=65007
Say I have an unsigned char (or byte) array. I want to take array[1] and array[2] from memory and cast it as short int (2 bytes). Something similar to how a union works, but not starting from the first byte. Example: ``` #include <stdio.h> void main() { unsigned char a[28]; unsigned short t; a[0]=12; a[1]=10; a[2]=55; t=(short) *(a+1); printf("%i", t); } ``` What I want is the value 14090 in decimal. Or 370Ah. Thank you. EDIT: I forgot to say, but most of you understood from my example, I am working on a little-endian machine. An 8bit Atmel microcontroller.
It's very simple: ``` unsigned short t = (a[2] << 8) | a[1]; ``` Note, this assumesunsigned charis 8 bits, which is most likely the case.
``` int j = 1; if((estado = open(SHELL, O_WRONLY))== -1){ if(errno == ENOENT){ mkfifo(SHELL,0666); estado = open(SHELL, O_WRONLY); } else{ perror("Erro a abrir pipe de estado da shell : "); exit(1); } } write (estado, &j,1); /************************************************/ ``` for some reason this program never computes after one of these open() (don't know which one) it just stalls and keeps there doing something forever... Am I missing anything? EDIT: I want to thank everyone who answered, I was able to understand better how pipes work with your help and solve my issue. Thanks!
As noted by sjnarv (I didn't the comment it until I was finished with my answer...), anopen()call for writing to a FIFO will block until the FIFO is opened for reading by either another thread or another process.
Reading chromium code, found helpful macro for handling EINTR errno of system calls on POSIX compliant systems. Here are the code(base/posix/eintr_wrapper.h): ``` #define HANDLE_EINTR(x) ({ \ decltype(x) eintr_wrapper_result; \ do { \ eintr_wrapper_result = (x); \ } while (eintr_wrapper_result == -1 && errno == EINTR); \ eintr_wrapper_result; \ }) ``` The question is what is the role of last statement in macroeintr_wrapper_result;? If we use commas instead of semicolons - it will be clear - to return the result of last operation(comma operator). But what is purpose in this case?
This macro uses theStatement-ExpressionsGCC extension. The last expression in the inner block serves as the value for the whole, once it has been executed, much like the comma operator.
I have the code ``` #include <stdio.h> #include <math.h> double x = round(3.2/2.0); int main() { printf("%f", x); } ``` When I try to compile, I get the errorinitializer element is not a compile-time constant. Withoutround, it compiles without a hitch. I want to round x while having it as a global variable. Is this possible?
In C language objects with static storage duration can only be initialized withintegral constant expressions. You are not allowed to call any functions in integral constant expressions. You will have to find a way to generate your value through an integral constant expression. Something like this might work ``` double x = (int) (3.2 / 2.0 + 0.5); ```
Reading chromium code, found helpful macro for handling EINTR errno of system calls on POSIX compliant systems. Here are the code(base/posix/eintr_wrapper.h): ``` #define HANDLE_EINTR(x) ({ \ decltype(x) eintr_wrapper_result; \ do { \ eintr_wrapper_result = (x); \ } while (eintr_wrapper_result == -1 && errno == EINTR); \ eintr_wrapper_result; \ }) ``` The question is what is the role of last statement in macroeintr_wrapper_result;? If we use commas instead of semicolons - it will be clear - to return the result of last operation(comma operator). But what is purpose in this case?
This macro uses theStatement-ExpressionsGCC extension. The last expression in the inner block serves as the value for the whole, once it has been executed, much like the comma operator.
I have the code ``` #include <stdio.h> #include <math.h> double x = round(3.2/2.0); int main() { printf("%f", x); } ``` When I try to compile, I get the errorinitializer element is not a compile-time constant. Withoutround, it compiles without a hitch. I want to round x while having it as a global variable. Is this possible?
In C language objects with static storage duration can only be initialized withintegral constant expressions. You are not allowed to call any functions in integral constant expressions. You will have to find a way to generate your value through an integral constant expression. Something like this might work ``` double x = (int) (3.2 / 2.0 + 0.5); ```
I'm usingWindows API CryptEncrypt with CALG_AES_256I want to use a password to encrypt, from what I understand ``` 1. CryptAcquireContext 2. CryptCreateHash (CALG_MD5) 3. CryptHashData 4. CryptDeriveKey 5. CryptEncrypt ``` I need to decrypt withnodejs crypto& I usedopensslenc to testnodejsdecrypting was successful but with C code the message is different How does windows use the hash ?
You should be using a password-hash function, not just a normal hash. A password-hash is salted and has a work-factor that makes it harder for an attacker to guess the password using a dictionary attack. Microsoft has createdan implementation of PBKDF2in the CNG framework.PBKDF2 is also contained in OpenSSL.
How does an#ifPreprocessor stage statement which contain variable of compile time get resolved at preprocessor stage itself? Below is the code which runs without any error: ``` #include<stdio.h> void main() { int num=10; /* compile time */ #if((num%2)==0) /* #if is preprocessor stage but has num of compile time why not error here? */ printf("\nNumber is Even"); #else printf("\nNumber is Odd"); #endif } ```
For the evaluation in#if, the preprocessor replaces all identifiers that are already defined macros by their appropriate expansion. All identifiers that remain after that have the value0.
This question already has answers here:strtok function thread safety(2 answers)Closed8 years ago. I am reading a lot negative things aboutstrtok(), some say it is obsolete, some say it is not thread safe, etc. So what is the truth, can I usestrtok()? and is it thread safe? Note:I am using Visual C++.
You can use it, it's a part of the standard library. It uses internal storage that is shared across all users of the function, sonoit's not thread-safe. It alsomodifiesthe string you hand to it, which is quite scary. I would not recommend using it, in most cases.
I am struggling to write a program in C. I want to disintegrate a number (only if it can be disintegrated) into a smaller numbers which can only be fibonacci numbers. For example : If I have a number n = 20 then my output should be 1,1,2,3,5,8 so when I add these smaller fibonacci numbers it gives me number 20.
Every integer has a representation as a sum of unique Fibonacci numbers. This is easy to prove by induction: if such a representation exists for all numbers up to Fib(n), then Fib(n)+k for k in 1, 2, ..., Fib(n-1) has the representation of Fib(n) + (representation for k). The proof suggests a simple recursive algorithm for finding the presentation for N: pick the greatest Fibonacci number that is less than N, say it's Fib(k). Then find the representation for N-Fib(k).
I'm new to C++ and I can't seem to wrap my head around accessing a 2d array from another class. This is my attempt so far but I'm confused. This is from what I've tried to gather online, but I don't understand for example, why the getter function is returning a char type, but in the form of a pointer? Game Header ``` class Game { public: char (*getLevel())[28]; private: char level[16][28]; } ``` Game.cpp ``` char (*Game::getLevel())[28] { return level; } pacman->moveEntity(getLevel(), pacman->getXPos(), pacman->getYPos(), direction); ``` Pacman.cpp ``` void Pacman::moveEntity(char level, int x, int y, char dir) { level[y][x] = ' '; } ``` [y] is redlined, and says Expression must have pointer to object type
The type oflevelin the function signature must match the type you call it with, in this particular casechar level[][28].
If we use for example: ``` char* strs[2]; strs[1] = "Hello"; strs[2] = "World!"; strcat(strs[1],strs[2]); ``` Then an access violation comes up (Access violation writing location 0x0028CC75). So why useconst char *strs[2];since thestrs1[1],strs1[2]cannot be changed?
``` // string literals are non-writeable so const is appropriate here const char* strs[2] = {"Hello", "World!"}; // let's create a target buffer with sufficient space char buffer[20]; // copy the first string there strcpy(buffer, strs[0]); // add the second string there strcat(buffer, strs[1]); ```
I am trying to understand the inner workings of the VLFeat SIFT algorithm and I notice this statement when computing the image gradient: ``` *grad++ = vl_mod_2pi_f (vl_fast_atan2_f (gy, gx) + 2*VL_PI); ``` I am wondering if this expression is not the same asvl_fast_atan2_f (gy, gx)as we are adding2 PIand the modulo of the expression on RHS should evaluate toatan2(gy, gx)?
vl_fast_atan2_fis an approximated (and thus faster) version ofatan2(seethis docfor more details). Still it returns results in[-pi, pi]so adding2.piand take the modulus (vl_mod_2pi_f) rescales the result into[0, 2.pi]which is how the gradient angle is represented.
I am struggling to write a program in C. I want to disintegrate a number (only if it can be disintegrated) into a smaller numbers which can only be fibonacci numbers. For example : If I have a number n = 20 then my output should be 1,1,2,3,5,8 so when I add these smaller fibonacci numbers it gives me number 20.
Every integer has a representation as a sum of unique Fibonacci numbers. This is easy to prove by induction: if such a representation exists for all numbers up to Fib(n), then Fib(n)+k for k in 1, 2, ..., Fib(n-1) has the representation of Fib(n) + (representation for k). The proof suggests a simple recursive algorithm for finding the presentation for N: pick the greatest Fibonacci number that is less than N, say it's Fib(k). Then find the representation for N-Fib(k).
I'm new to C++ and I can't seem to wrap my head around accessing a 2d array from another class. This is my attempt so far but I'm confused. This is from what I've tried to gather online, but I don't understand for example, why the getter function is returning a char type, but in the form of a pointer? Game Header ``` class Game { public: char (*getLevel())[28]; private: char level[16][28]; } ``` Game.cpp ``` char (*Game::getLevel())[28] { return level; } pacman->moveEntity(getLevel(), pacman->getXPos(), pacman->getYPos(), direction); ``` Pacman.cpp ``` void Pacman::moveEntity(char level, int x, int y, char dir) { level[y][x] = ' '; } ``` [y] is redlined, and says Expression must have pointer to object type
The type oflevelin the function signature must match the type you call it with, in this particular casechar level[][28].
I am pretty new in C language. I am trying to use strcat, the following example works: ``` char s1[20] = "Happy "; char s2[15] = "world"; char s3[40] = ""; strcat(s3,s1); ``` Although, i wanted to practise a bit the pointers i have seen earlier, so: ``` char *s1 = "Happy"; char *s2 = "World"; strcat(*s2,*s1); ``` produces argument of type "char" is incompatible with parameter of type "const char *. Again, this might be easy, but be as clarifying as possible
In the second example, ``` strcat(*s2,*s1); ``` has a type mismatch problem, as*s2and*s1are of typechar. If you use: ``` strcat(s2,s1); ``` It would still be wrong, becauses2points to a string literal, which can't be modified.
I'm trying to create adoubleby appending the binary representations of twoints. This is what I have now: ``` int i = arc4random(); *(&i+1) = arc4random(); double d = *(double*)&i; ``` I hoped thedoublepointer would also use the value in the&i+1address, and this is indeed the case. When I print the binary representations ofiand*(&i+1)and compare them to the binary representation ofd, d is composed by appending*(&i+1)andi. So*(&i+1)comes first?! Why is this the case? EDIT:also take a look at the answers of Juan Catalan and Mark Segal to know what's the right way of doing what I did using unions.
Use aunioninstead. You still could generate a NaN But won't have memory management issues. This is the whole purpose of aunion, share a memory block among several different types. Make sure in your architecturesizeof(double)is equal to twicesizeof(int)
I am looking for better algorithm to solve a problem. Problem: Check a given string if given substring is present and reverse all the substrings in the given string. Example: String: Can you can a can as a canner can can a can Substring: can Output: nac you nac a nac as a nacner nac nac a nac What would be a better algorithm to solve this problem?
You can first search for those substrings usingKnuth-Morris-Prattand then you can simply replace them with the reverse order. As I've passed my Data Structure course in university, this algorithm has a very good performance, intime complexitypoint of view.
In ex 1.18 of Kernighan & Ritchie's The C Programming Language, the reader is asked to write a program to remove trailing blanks and tabs, and to delete entirely blank lines. What is meant by trailing blanks and tabs? Are consecutive tabs or spaces trailing blanks and tabs? Also an entirely blank line means just consecutive'\n's or will"\n \n"be considered a blank line too?
Trailing whitespace usually refers to whitespace that follows the last non-whitespace character of a line. I think"\n \n"should be considered a blank line (that's the blank vs. empty distinction used by theApache StringUtils: empty strings have length 0, blank strings contain only whitespace). You'll delete them either way, since you'd delete trailing whitespace first, leaving them empty.
Here's a snippet of code that causes segmentation fault: ``` void test_list(char **list) { *list = malloc (100 * sizeof(char)); *list[0] = 't'; *list[1] = 'e'; // SIGSEGV here *list[2] = 's'; *list[3] = 't'; } int main() { char *list; test_list(&list); return 0; } ``` What has just happened?
Beware ofoperator precedence- change: ``` *list[0] = 't'; ``` to ``` (*list)[0] = 't'; ``` (and so on...)
I am looking to convert a simple comma separated string like this: ``` apples, pears, oranges, ``` into aC String Array(NOT A CHARCHTER ARRAY)similar to the one found here:How do I create an array of strings in C? I know how to do this in Python and Javascript, but how would I go about creating this in C?
Usestrtoklike the following...arrayOfStringwill have list of strings. ``` #include <string.h> #include <stdio.h> int main() { char str[80] = "apples, pears, oranges,"; char* arrayOfString[3]; const char s[2] = ", "; char *token; int i=0; /* get the first token */ token = strtok(str, s); /* walk through other tokens */ while( token != NULL ) { arrayOfString[i] = token; token = strtok(NULL, s); i++; } for(i=0;i<3;i++) printf("%s\n", arrayOfString[i]); return(0); } ```
I came across this piece of code in C: ``` #include <stdio.h> main( ) { int i = 5; workover(i); printf("%d",i); } workover(i) int i; { i = i*i; return(i); } ``` I want to know how the declaration of the function "workover" is valid? What happens when we don't mention the return type of a function? (can we return anything?).The parameter is also just a variable name, how does this work?
If you do not specify a return type or parameter type, C will implicitly declare it asint. This is a "feature" from the earlier versions of C (C89 and C90), but is generally considered bad practice nowadays. Since the C99 standard (1999) does no longer allow this, a compiler targeting C99 or later will likely give you a warning similar to the following: ``` program.c: At top level: program.c:8:1: warning: return type defaults to ‘int’ workover(i) ^ ```
I saw in a CUDA code example thatmemsetis used to initialize vectors to all 0's that will store the sum of two others vectors. For example: ``` hostRef = (float *)malloc(nBytes); gpuRef = (float *)malloc(nBytes); memset(hostRef, 0, nBytes); memset(gpuRef, 0, nBytes); ``` What purpose does this serve if nothing else is done with these vectors? You can see the code here:https://books.google.com/books?id=Jgx_BAAAQBAJ&pg=PA42#v=onepage&q&f=false Not sure how long the link will work though.
It would serve no purpose if nothing else were done with those vectors, but that is not the case. The code runs a CUDA vector sum, and then copies the result into*gpuRef. It then performs the same sum on the host CPU, and puts the result in*hostRef. Finally, it compares the two results. Of course, it doesn't do anything with either array before copying new data into it, so the initialization to zero still serves no purpose.
I am now starting to learn C. I would like to know why I get the warning. I declared a bidimensional char array, but why the character"d"is not allowed? ``` char array[3][3] = {{1,"d",3},{3,2,1},{2,1,3}}; ```
Replace "d" with 'd' 'd' is a character "d" is a string
Code: ``` FILE *fp = fopen(filename, "r"); if (!fp) { fprintf(stderr, "Failed to open a file\n"); // fclose(fp) <-- should I close file here? exit(1); } // Some operations on the file. fclose(fp); ``` Question: Iffopen()fails to open a file, should I still callfclose()?
No, you don't need to callfclose()insideifblock. Oncefopen()fails, it retruns NULL which need not beclosed. To elaborate, iffopen()is success, it will return aFILE *. That needs to be closed. FWIW, the returned pointer in this case, be of whatevervalue, gurantees to compare unequal with a NULL. In other words, iffopen()is a success, the returned pointer will alwaysFAILtheif(!fp)check. In error scenario (when the file cannot be opned forsomereason), NULL will be retrurned. A NULL return value means, the file wasnotopened. You don't close what is not already opened. Simple.
I couldn't find it in the docs anywhere, all I did find was that it returns a negative number when an error occurs. What error can it be? The error occurs in a function that looks like this: ``` void foo(wchar_t** a) { for (int i = 0; i < N; i++) if (fwprintf(stderr, L"%ls ", a[i]) < 0) puts("OOPS!"); fwprintf(stderr, L"\n"); } ``` Also, this error appears only at one point during the program execution and stays there, as if some kind of limit was reached.
I believe, the failure reasons forfwprintf()are mostly the same with that offputwc(). You can always check theerrnogo get the exact nature of errors. To quote the man page, type of the errors are, [EAGAIN][EBADF][EFBIG][EFBIG][EINTR][EIO][ENOSPC][EPIPE][ENOMEM][ENXIO][EILSEQ][EINVAL]
I have a custom target, and I want it to depend on the default target (the one that is built withmake). ``` add_custom_target(foo ....) add_dependency(foo default_target_name_goes_here) ``` What is the name of the default target? I've triedALL,ALL_BUILD,MyProjectsName,DEFAULT,... Finding anything in the CMake documentation is always an unsuccessful adventure... UPDATE: it seems CMake was designed in such a way that this is extremely hard to fix/implement:bugreport getting +1's since 2009. Who indeed would like to have a custom target that depends on, for example, thealltarget? Or in other words: who does ever writemake && make test?...
The default build target does not exist as a CMake target at CMake configure time. It is only exists in the generated build system. Therefore it is not possible to have the default target depend on a custom target.
I am reading / studying the book:Linux System Programming: Talking Directly to the Kernel and C Libraryand quoting from this book: The compiler used in a Unix system—Linux included—is highly relevant to system programming, as the compiler helps implement the C standard and the system ABI. What is meant bycompiler helps implement the C standard?
Disclaimer: I have not read the relevant paragraph. compiler helps implement the C standard In general sense, C standard are a set of rules and/or guidelines, how the language syntax and semantics are to be used. To create and run a binary (executable), or better to say, to have animplementationof the rules mentioned in the standard, we need to have a compiler. If I may, we can also say, in other words, compiler uses the C standards to generate an exectable from a C source code, which is C standard compilant.
Suppose I have some C code like this, which declares a small multidimensional array: ``` #include <stdio.h> #include <conio.h> int main(void) { int mat[5][2] = { {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0} } do scanf("%i", &mat[][]); while (getchar() != '\n'); return 0; } ``` and I want to changedo scanf("%i", &mat[][]);, and possibly the line below it, to something which will allow me to read user-supplied integers into only the 2nd column of this 5-by-2 multidimensional array. I am trying to find the simplest possible solution, without concern for software security and hopefully without unnecessarily calling libraries.
You want something like this. ``` int i=0; do{ scanf("%d", &mat[i][1]); i++; }while (getchar() != '\n'); ```
I have an application that at some point calls ``` system("/usr/sbin/iptables -t nat F") ``` to flush the ip tables. Since the application is multi threaded and developed by multiple developers, at some point the iptables stopped being set. It turned out that I'm not able to lunch external processes (have also triedsystem("/bin/ls")without success). The commands can be run from the shell with no issues. I get the return value-1regardless of the command called. Is there a way to get some more information on why this is failing?
Try printing out theerrornoor its descriptive string after thesystemcall. Add the following: ``` #include <errno.h> system("/bin/ls"); printf ("Error: %s\n",strerror(errno)); ``` Might give you more details.
How to convert a variable of data typeuint8_ttoint32_tusing Neon? I could not find any intrinsic for doing this.
Assuming you want to convert a vector of 16 x 8 bit ints to four vectors of 4 x 32 bit ints, you can do this by first unpacking to 16 bits and then again to 32 bits: ``` // load 8 bit vector uint8x16_t v = vld1q_u8(p); // load vector of 16 x 8 bits ints from p // unpack to 16 bits int16x8_t vl = vreinterpretq_s16_u16(vmovl_u8(vget_low_u8(v))); // 0..7 int16x8_t vh = vreinterpretq_s16_u16(vmovl_u8(vget_high_u8(v))); // 8..15 // unpack to 32 bits int32x4_t vll = vmovl_s16(vget_low_s16(vl)); // 0..3 int32x4_t vlh = vmovl_s16(vget_high_s16(vl)); // 4..7 int32x4_t vhl = vmovl_s16(vget_low_s16(vh)); // 8..11 int32x4_t vhh = vmovl_s16(vget_high_s16(vh)); // 12..15 ```
I'm trying to read from a binary file by closing and opening it but it seems like it doesn't work. When I change it towb+and use the commented outfseekinstead of closing and opening it does read. What am I doing wrong with closing and opening the file? ``` int main(){ FILE * tfp = fopen("test.bin", "wb"); char src[] = "1233 asd 333"; fputs(src, tfp); char aw[20]; //fseek(tfp, SEEK_SET, 0); fcloseall; tfp = fopen("test.bin", "rb"); fread(aw, sizeof(char), 20, tfp); fcloseall; getchar(); } ```
The problem wasfcloseall;instead offcloseall();
Compiling with-jNwill compile faster, because it's compiling several parts at the same time. But GCC docs say (I can't find the exact link though) that compiling with-j1will produce a better optimized binary. Can you explain all the benefits of compiling with-j1? Can you even provide a small POC that proves that compiling with-j1generates a more optimized (in performance terms) binary than-jN?
-j option is for make. There's no such option for gcc I think you are talking about -O option. Here's the man page for -O1 -O1 Optimize. Optimizing compilation takes somewhat more time, and a lot more memory for a large function. With -O, the compiler tries to reduce code size and execution time, without performing any optimizations that take a great deal of compilation time.
I am now starting to learn C. I would like to know why I get the warning. I declared a bidimensional char array, but why the character"d"is not allowed? ``` char array[3][3] = {{1,"d",3},{3,2,1},{2,1,3}}; ```
Replace "d" with 'd' 'd' is a character "d" is a string
Code: ``` FILE *fp = fopen(filename, "r"); if (!fp) { fprintf(stderr, "Failed to open a file\n"); // fclose(fp) <-- should I close file here? exit(1); } // Some operations on the file. fclose(fp); ``` Question: Iffopen()fails to open a file, should I still callfclose()?
No, you don't need to callfclose()insideifblock. Oncefopen()fails, it retruns NULL which need not beclosed. To elaborate, iffopen()is success, it will return aFILE *. That needs to be closed. FWIW, the returned pointer in this case, be of whatevervalue, gurantees to compare unequal with a NULL. In other words, iffopen()is a success, the returned pointer will alwaysFAILtheif(!fp)check. In error scenario (when the file cannot be opned forsomereason), NULL will be retrurned. A NULL return value means, the file wasnotopened. You don't close what is not already opened. Simple.
I couldn't find it in the docs anywhere, all I did find was that it returns a negative number when an error occurs. What error can it be? The error occurs in a function that looks like this: ``` void foo(wchar_t** a) { for (int i = 0; i < N; i++) if (fwprintf(stderr, L"%ls ", a[i]) < 0) puts("OOPS!"); fwprintf(stderr, L"\n"); } ``` Also, this error appears only at one point during the program execution and stays there, as if some kind of limit was reached.
I believe, the failure reasons forfwprintf()are mostly the same with that offputwc(). You can always check theerrnogo get the exact nature of errors. To quote the man page, type of the errors are, [EAGAIN][EBADF][EFBIG][EFBIG][EINTR][EIO][ENOSPC][EPIPE][ENOMEM][ENXIO][EILSEQ][EINVAL]
I have a custom target, and I want it to depend on the default target (the one that is built withmake). ``` add_custom_target(foo ....) add_dependency(foo default_target_name_goes_here) ``` What is the name of the default target? I've triedALL,ALL_BUILD,MyProjectsName,DEFAULT,... Finding anything in the CMake documentation is always an unsuccessful adventure... UPDATE: it seems CMake was designed in such a way that this is extremely hard to fix/implement:bugreport getting +1's since 2009. Who indeed would like to have a custom target that depends on, for example, thealltarget? Or in other words: who does ever writemake && make test?...
The default build target does not exist as a CMake target at CMake configure time. It is only exists in the generated build system. Therefore it is not possible to have the default target depend on a custom target.
I am reading / studying the book:Linux System Programming: Talking Directly to the Kernel and C Libraryand quoting from this book: The compiler used in a Unix system—Linux included—is highly relevant to system programming, as the compiler helps implement the C standard and the system ABI. What is meant bycompiler helps implement the C standard?
Disclaimer: I have not read the relevant paragraph. compiler helps implement the C standard In general sense, C standard are a set of rules and/or guidelines, how the language syntax and semantics are to be used. To create and run a binary (executable), or better to say, to have animplementationof the rules mentioned in the standard, we need to have a compiler. If I may, we can also say, in other words, compiler uses the C standards to generate an exectable from a C source code, which is C standard compilant.
Suppose I have some C code like this, which declares a small multidimensional array: ``` #include <stdio.h> #include <conio.h> int main(void) { int mat[5][2] = { {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0} } do scanf("%i", &mat[][]); while (getchar() != '\n'); return 0; } ``` and I want to changedo scanf("%i", &mat[][]);, and possibly the line below it, to something which will allow me to read user-supplied integers into only the 2nd column of this 5-by-2 multidimensional array. I am trying to find the simplest possible solution, without concern for software security and hopefully without unnecessarily calling libraries.
You want something like this. ``` int i=0; do{ scanf("%d", &mat[i][1]); i++; }while (getchar() != '\n'); ```
I have an application that at some point calls ``` system("/usr/sbin/iptables -t nat F") ``` to flush the ip tables. Since the application is multi threaded and developed by multiple developers, at some point the iptables stopped being set. It turned out that I'm not able to lunch external processes (have also triedsystem("/bin/ls")without success). The commands can be run from the shell with no issues. I get the return value-1regardless of the command called. Is there a way to get some more information on why this is failing?
Try printing out theerrornoor its descriptive string after thesystemcall. Add the following: ``` #include <errno.h> system("/bin/ls"); printf ("Error: %s\n",strerror(errno)); ``` Might give you more details.
How to convert a variable of data typeuint8_ttoint32_tusing Neon? I could not find any intrinsic for doing this.
Assuming you want to convert a vector of 16 x 8 bit ints to four vectors of 4 x 32 bit ints, you can do this by first unpacking to 16 bits and then again to 32 bits: ``` // load 8 bit vector uint8x16_t v = vld1q_u8(p); // load vector of 16 x 8 bits ints from p // unpack to 16 bits int16x8_t vl = vreinterpretq_s16_u16(vmovl_u8(vget_low_u8(v))); // 0..7 int16x8_t vh = vreinterpretq_s16_u16(vmovl_u8(vget_high_u8(v))); // 8..15 // unpack to 32 bits int32x4_t vll = vmovl_s16(vget_low_s16(vl)); // 0..3 int32x4_t vlh = vmovl_s16(vget_high_s16(vl)); // 4..7 int32x4_t vhl = vmovl_s16(vget_low_s16(vh)); // 8..11 int32x4_t vhh = vmovl_s16(vget_high_s16(vh)); // 12..15 ```
I'm trying to read from a binary file by closing and opening it but it seems like it doesn't work. When I change it towb+and use the commented outfseekinstead of closing and opening it does read. What am I doing wrong with closing and opening the file? ``` int main(){ FILE * tfp = fopen("test.bin", "wb"); char src[] = "1233 asd 333"; fputs(src, tfp); char aw[20]; //fseek(tfp, SEEK_SET, 0); fcloseall; tfp = fopen("test.bin", "rb"); fread(aw, sizeof(char), 20, tfp); fcloseall; getchar(); } ```
The problem wasfcloseall;instead offcloseall();
Compiling with-jNwill compile faster, because it's compiling several parts at the same time. But GCC docs say (I can't find the exact link though) that compiling with-j1will produce a better optimized binary. Can you explain all the benefits of compiling with-j1? Can you even provide a small POC that proves that compiling with-j1generates a more optimized (in performance terms) binary than-jN?
-j option is for make. There's no such option for gcc I think you are talking about -O option. Here's the man page for -O1 -O1 Optimize. Optimizing compilation takes somewhat more time, and a lot more memory for a large function. With -O, the compiler tries to reduce code size and execution time, without performing any optimizations that take a great deal of compilation time.
Suppose I have some C code like this, which declares a small multidimensional array: ``` #include <stdio.h> #include <conio.h> int main(void) { int mat[5][2] = { {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0} } do scanf("%i", &mat[][]); while (getchar() != '\n'); return 0; } ``` and I want to changedo scanf("%i", &mat[][]);, and possibly the line below it, to something which will allow me to read user-supplied integers into only the 2nd column of this 5-by-2 multidimensional array. I am trying to find the simplest possible solution, without concern for software security and hopefully without unnecessarily calling libraries.
You want something like this. ``` int i=0; do{ scanf("%d", &mat[i][1]); i++; }while (getchar() != '\n'); ```
I have an application that at some point calls ``` system("/usr/sbin/iptables -t nat F") ``` to flush the ip tables. Since the application is multi threaded and developed by multiple developers, at some point the iptables stopped being set. It turned out that I'm not able to lunch external processes (have also triedsystem("/bin/ls")without success). The commands can be run from the shell with no issues. I get the return value-1regardless of the command called. Is there a way to get some more information on why this is failing?
Try printing out theerrornoor its descriptive string after thesystemcall. Add the following: ``` #include <errno.h> system("/bin/ls"); printf ("Error: %s\n",strerror(errno)); ``` Might give you more details.
How to convert a variable of data typeuint8_ttoint32_tusing Neon? I could not find any intrinsic for doing this.
Assuming you want to convert a vector of 16 x 8 bit ints to four vectors of 4 x 32 bit ints, you can do this by first unpacking to 16 bits and then again to 32 bits: ``` // load 8 bit vector uint8x16_t v = vld1q_u8(p); // load vector of 16 x 8 bits ints from p // unpack to 16 bits int16x8_t vl = vreinterpretq_s16_u16(vmovl_u8(vget_low_u8(v))); // 0..7 int16x8_t vh = vreinterpretq_s16_u16(vmovl_u8(vget_high_u8(v))); // 8..15 // unpack to 32 bits int32x4_t vll = vmovl_s16(vget_low_s16(vl)); // 0..3 int32x4_t vlh = vmovl_s16(vget_high_s16(vl)); // 4..7 int32x4_t vhl = vmovl_s16(vget_low_s16(vh)); // 8..11 int32x4_t vhh = vmovl_s16(vget_high_s16(vh)); // 12..15 ```
I'm trying to read from a binary file by closing and opening it but it seems like it doesn't work. When I change it towb+and use the commented outfseekinstead of closing and opening it does read. What am I doing wrong with closing and opening the file? ``` int main(){ FILE * tfp = fopen("test.bin", "wb"); char src[] = "1233 asd 333"; fputs(src, tfp); char aw[20]; //fseek(tfp, SEEK_SET, 0); fcloseall; tfp = fopen("test.bin", "rb"); fread(aw, sizeof(char), 20, tfp); fcloseall; getchar(); } ```
The problem wasfcloseall;instead offcloseall();
Compiling with-jNwill compile faster, because it's compiling several parts at the same time. But GCC docs say (I can't find the exact link though) that compiling with-j1will produce a better optimized binary. Can you explain all the benefits of compiling with-j1? Can you even provide a small POC that proves that compiling with-j1generates a more optimized (in performance terms) binary than-jN?
-j option is for make. There's no such option for gcc I think you are talking about -O option. Here's the man page for -O1 -O1 Optimize. Optimizing compilation takes somewhat more time, and a lot more memory for a large function. With -O, the compiler tries to reduce code size and execution time, without performing any optimizations that take a great deal of compilation time.
This question already has answers here:What is array to pointer decay?(11 answers)Closed8 years ago. When I declareint a[5][3];what exactly isa[2], is it a pointer to array or does it decays to a pointer to inta[2][0]. I want to talk about 2D arrays, and I am concerned in decay whethera[2]decays or not when used independently.
Itsa[2]is an array of 3 int's. However if you are looking for Array decaying then you can look for thiswhat is array decaying? I want to talk about 2D arrays, and I am concerned in decay whether a[2] decays or not when used independently. It will not decay all by itself.
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.Closed8 years ago.Improve this question When I run the code, I get this error : ``` In function 'print': error: expected ';' before '{' token ``` I'm usinggcccompiler, I can't really find what I'm missing here: Code: ``` #include <stdio.h> void print(char *C) { int i = 0; While(C[i] != '\0') { printf("%c",C[i]); i++; } printf("\n"); } int main() { char C[20] = "Hello"; print(C); } ```
``` While(C[i] != '\0') ``` should be ``` while(C[i] != '\0') /* Note the lower-case 'w' */ ``` Remember that the C programming language is case sensitive.
I am trying to write a program that could read/write the rolodex info (the file will be named myRolodex by default). But I think the line:strcpy(filename,"myRolodex");causes Segmentation fault (core dumped) in my GCC compiler. Any help to fix would be grateful! ``` #include<stdio.h> #include <stdlib.h> #include<string.h> #include<stdbool.h> int main(int argc, char* argv[]){ char filename[250]; if (argv[1]==NULL){ strcpy(filename,"myRolodex"); } strcpy(filename,argv[1]); printf("%s",filename); return 0; } ```
Correct your code as follows ``` if (argv[1]==NULL){ strcpy(filename,"myRolodex"); }else{ strcpy(filename,argv[1]); } ``` The problem is, even if you check argv[1]==NULL, statment strcpy(filename,argv[1]); will be always be executed since it's not in else block.
I have an app that opens the console and then it opens the GUI, but the console does not disappear. Is there any way of hiding the console window? Thanks
``` #include <windows.h> int main(void) { printf("%s", "Hello from the console.\n"); MessageBox(NULL, "Click OK to hide the console.", "", MB_ICONINFORMATION); ShowWindow(GetConsoleWindow(), SW_HIDE); MessageBox(NULL, "Console is now hidden.", "", MB_ICONINFORMATION); return 0; } ```
This question already has answers here:Can I call memcpy() and memmove() with "number of bytes" set to zero?(2 answers)Closed8 years ago. Is there a problem in passing0tomemcpy(): ``` memcpy(dest, src, 0) ``` Note that in my code I am using a variable instead of0, which can sometimes evaluate to0.
As one might expect from a sane interface, zero is a valid size, and results in nothing happening. It's specifically allowed by the specification of the various string handling functions (includingmemcpy) in C99 7.21.1/2: Where an argument declared assize_t nspecifies the length of the array for a function,ncan have the value zeroon a call to that function. [...] On such a call, a function that locates a character finds no occurrence, a function that compares two character sequences returns zero, anda function that copies characters copies zero characters.
This is a sample code I have from someone and it runs giving the answers 3, 2, 15 Can someone please explain how this piece of code works and how it got to those outputs? Code: ``` int a[5] = { 5, 1, 15, 20, 25 }; int i, j, m; i = ++a[1]; j = a[1]++; m = a[i++]; printf("%d, %d, %d", i, j, m); _getch(); ```
You should know aboutpre-increment(++var) andpost-increment(var++). Let's break down the code line by line, shall we? i = ++a[1];Here,a[1]is1, (2nd element of arraya), is pre-incremented to2and that value is stored intoi.j = a[1]++;same, the2is stored intojand thena[1]is post-incremented to the value3.m = a[i++];a[2], i.e.,15is stored intom, andiis post-incremented to3.printf("%d, %d, %d", i, j, m);-- Surprise!!
The problem is quite simple. My code is : ``` __attribute__ ((naked)) void function(int arg1, int arg2, int arg3) { _asm("push {r0-r6}\n" " .... "); if(checkSomeValue(arg3)) callSomeFunction(arg1, arg2); } ``` The asm code What I expected : ``` push {r0-r6} .... instruction of if ~ callSomefunction ``` But.. the result is : ``` str r1, [sp+0x0c] str r2, [sp+0x08] // back up register for if~ callsomefunction statement push {r0-r6} ... ``` How can I place my asm code in the beginning of function?
My way : ``` __attribute__ ((naked)) void function(int arg1, int arg2, int arg3) { _asm("push {r0-r6}\n" "bl calleeFunction\n" "pop {r0-r6}\n" "b backToOriginal\n" ); } void calleeFunction(int arg1, int arg2, int arg3) { if(checkSomeValue(arg3)) callSomeFunction(arg1, arg2); } ```
I am trying to write a program that could read/write the rolodex info (the file will be named myRolodex by default). But I think the line:strcpy(filename,"myRolodex");causes Segmentation fault (core dumped) in my GCC compiler. Any help to fix would be grateful! ``` #include<stdio.h> #include <stdlib.h> #include<string.h> #include<stdbool.h> int main(int argc, char* argv[]){ char filename[250]; if (argv[1]==NULL){ strcpy(filename,"myRolodex"); } strcpy(filename,argv[1]); printf("%s",filename); return 0; } ```
Correct your code as follows ``` if (argv[1]==NULL){ strcpy(filename,"myRolodex"); }else{ strcpy(filename,argv[1]); } ``` The problem is, even if you check argv[1]==NULL, statment strcpy(filename,argv[1]); will be always be executed since it's not in else block.
The code here is a typical example for shallow copy, it ought to got the warning when running, but on my Xcode, it's running well and result is hi,hihi,hi why? The code: ``` struct pc { char *p; }; int main() { struct pc pc1; pc1.p = malloc(100); strcpy(pc1.p, "hi"); struct pc pc2 = pc1; // shallow copy printf("%s,%s\n", pc1.p, pc2.p); free(pc1.p); printf("%s,%s", pc1.p, pc2.p); return 0; } ```
Accessing memory after you'vefree()d it invokesundefined behaviour. You shouldnotbe using theprintf()with thefree()d memory after you call ``` free(pc1.p); ```
it is my first type to encounter this type of code. I am having a hard time understanding it. ``` #ifndef A #define A #endif #ifndef B #define B #endif void funct (structA* A paramA, structB* B paramB){}; ``` What is the purpose of preprocessor A and B in the parameter?
For: ``` #define A this_is_a ``` The preprocessor will replaceAwiththis_is_a. For: ``` #define A ``` The preprocessor will replaceAwith nothing. So in your example code,AandBsymbols are just discarded. People use this technique to annotate code sometimes, for example: ``` #define IN #define OUT ``` Now you can annotate function parameters showing whether they are "in" or "out" parameters: ``` void my_function(IN int i, OUT int& x) { ... } ```
Sorry if this is too stupid but I couldn't resist asking.I wish to create a C application with an embedded MYSQL database(libmysqld)in it. What I am confused about is the size of the application.Since the application itself embeds a mysql db in it, would the size of the application be the size of the binary(excluding db) + size of the embedded db?If this is the case wouldn't it be difficult run standalone applications which deals with large volumes of mysql data as they would consume a lot of RAM? Am I missing the concept here?
Embedding mysql means embedding the "server" code, not data. Database tables will be stored in configured datadir.
On the CPU, I have an array of positions and colors: ``` [ x0, y0, z0, col0, x1, y1, z1, col1 ...] ``` On the device, I have a 3D texture. Is there any efficient way to modify that texture so that positionx0, y0, z0's color becomes col0 and so on?
glTexSubimage3d will work if you can arrange your data into cubes. Doing it one texel at a time would be miserable though. https://www.opengl.org/sdk/docs/man3/xhtml/glTexSubImage3D.xml
for example : ``` void size(int a, int array[a][a]){ .......... } ``` (I mean is it ok to pass int a and also have varaible a as size of an array im also passing to the same function? I would also like to ask if is it possible to pass 2D array using a double pointer for e.g: void smthn(int **array){...}?)
This declaration ``` void size(int a, int array[a][a]); ``` is equivalent to ``` void size(int a, int ( *array )[a] ); ``` wherearrayis a pointer to a Variable Length Array withaelements. It is a valid syntax in C99. Here is a demonstrative program ``` #include <stdio.h> void f( size_t n, int a[n][n] ) { printf( "%zu\n", sizeof( *a ) / sizeof( **a ) ); } int main(void) { int a[3][3]; int b[10][10]; f( 3, a ); f( 10, b ); return 0; } ``` The program output is ``` 3 10 ```
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.Closed6 years ago.Improve this question Is there a way to convertcdatatouserdata? How can I use the C api to push/retrievecdatato/from the stack? Edit:The original title mentioned luajit but not Torch. In that context the other answers beside the one I finally had submitted myself (e.gwolfgang's) made perfect sense.
There is no extension to the Lua C API to access cdata objects as created by LuaJIT's FFI library. So, the simple and recommended way is to do your marshalling from the Lua side if you're dealing with cdata. So, call a C function from Lua and pass thatcdataas a parameter.