question
stringlengths
25
894
answer
stringlengths
4
863
I am new to C and am having a problem reading this matrix declaration in a function. void foo(int (*array)[][3], int row, int col) and in the function how do I access an array element - say to print it's value.
``` int (*array)[][3] ``` declaresarrayto be a pointer to a 2D array whose second dimension is3. Example usage: ``` #include <stdio.h> void foo(int (*array)[][3], int row, int col) { printf("%d\n", (*array)[row][col]); } int main() { int array[10][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; foo(&array, 2, 2); return 0; } ``` Output: ``` 9 ```
I've tried to invert an array element today and it didn't work. Is there a reason that e.g. ``` uint8_t array[2] = {0xFF,0x0A}; ... if( 0xF5 == ~(array[1]){ // never got here } ``` Doesn't work? Compiler didn't show any errors.
C promotes integer types toint(or larger) when performing integer arithmetic. To get the value you desire, you can cast the result of the bitwise complement back down touint8_tbefore comparing, as follows: ``` if (0xF5 == (uint8_t) ~array[1]) { ... } ```
The first way looks like this: ``` int *p_number = &number; ``` And the second like: ``` int *p_number; p_number = &number; ``` I don't get why the first way look as it looks, because I get thatp_numberis the address ofint *p_numberand we are basically givingp_numberthe address ofnumberwith the&operator. But why do we initialize*p_numberwith&number? Wouldn't that mean that the pointee ofp_numberis the address of number?
I believe what's confusing you is the syntax ``` int *p_number = &number; ``` well, you can rewrite it as ``` int* p_number = &number; ``` which is same as ``` int *p_number; p_number = &number; ``` The first one is actually a combined step of definition and initialization.
I would like to detect hardware breakpoints. I am able to read the register values using: ``` unsigned sp; __asm __volatile("movl %%esp, %0" : "=r" (sp)); return sp; ``` Trying to readdr0on a 64 machine I getError: unsupported instruction 'mov'. I managed to compile with-m32, but I get a segmentation fault when I try to run. How can I check the debug registers? I am interested in both 32 and 64 bit solutions.
You need to use a 64 bit register in 64 bit mode, that's why it doesn't compile (presumably, since you have not showed the actual code you tried...) In any case, you can't read debug registers in user mode. You should say why you need access to them otherwise it's an XY problem. My best guess is that you might be interested in theptraceAPI instead.
I need to allocate some memory chunk in my C++ program with two requirements. First the address of the allocation needs to be aligned on the chunk size, second it needs to be allocated below 4GB virtual address space. memalign()helps me with the first requirement, andmmap()helps me with the second, since I can passMAP_32BITflag as a parameter. But is it possible to somehow combine them both in a simple solution? (Technically of course I can usemmap()with any address I want, but the solution probably won't be very portable).
Just mmap a block that is (first rounded to the next power of) twice as big as what you need and then munmap what is not needed.
What happens when we try to increment a string in C? ``` #include <stdio.h> void foobar(char *str1, char *str2) { while (*((str1++)+6) == *((str2++)+8)); } int main(){ char str1[] = "Hello World"; char str2[] = "Foo Bar Bar"; foobar(str1,str2); printf``("%s %sn",str1, str2); return 0; } ``` The output was: Hello World Foo Bar Barn
I've no idea what you are trying to do but your functionfoobardoes nothing as all you do is iterate through the strings on the local variables str1 - changes to which will not be passed back to main. Well, that's not completely true.Foobarcould potentially run off the end of the strings and crash the way it is written now.
I am maintaining a c/c++ program under linux, which will change BIOS settings and reboot to enable new settings. Now test teams need to verify exit status, but the program will reboot right now after termination, so their script doesn't have enough time to record the status. I have trysystem("shutdown -r -t 1"), but it will wait for 1 minute.I just need few seconds delay time butshutdownhas no option for it. Are there other methods( besidesatorcron) to implement a few seconds reboot delay time after program termination?
You can try next line: ``` system("nohup bash -c 'sleep 10; shutdown -r -t now' > /tmp/shutdown.log&"); ``` This with return inmedialty your program and after 10 seconds will invoke the sutdown
I would like to retrieve time passed since kernel's start (in kernel space). It should be the match the timeprintk();is using (For example:[ 5.832000] message). jiffiesprovide different time, so I am not sure it fits me. How can I achieve this?
What about usingget_monotonic_boottime?jiffiesare initialized to 5 minutes before boot to ensure that there is an overflow soon after booting and detect bugs.
Today I gave a test there was the following question written and because I am new to C++, I became confused to the following question. Why doesn't the following statement work? ``` char str[ ] = "Hello" ; strcat ( str, '!' ) ; ```
``` char str[] = "Hello"; strcat (str, '!') ; ``` strcatsecond argument must be a pointer to a string, but you are passing a character constant. The correct call would bestrcat(str, "!");(note the"instead of the') but you also need to reserve enough space instrwhich is only large enough to hold the"Hello"string. For example, for your test, you can reserve more bytes withchar str[64] = "Hello";
I am developing an application that requires the ability to be able to set the IP address. Using command prompt Netsh interface IP set address.... It works but what is the equivalent in c? Thanks
I think you need AddIPAddress() API. Refer toAddIPAddress functionat MSDN documentation with a good example. You can refer to a majority of networking APIs (query, set, delete IPs etc) athttps://msdn.microsoft.com/en-us/library/windows/desktop/aa366071(v=vs.85).aspx.
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed7 years ago. ``` #include <stdio.h> int main(void) { int i=1; printf("%d %d\n", i+=1, i); printf("%d %d\n", i, i+=1); return 0; } ``` The above code shows different output in Linux and Mac. In Linux: (gcc version 4.9.2 20150212 (Red Hat 4.9.2-6)) ``` 2 2 3 3 ``` In Mac: (Apple LLVM version 7.0.0 (clang-700.0.57.2)) ``` 2 2 2 3 ``` In Linux, I tried with c11, c99, c89. But the output is same. So I don't think it's a C standard Issue. Why such behaviour?Which one is correct and why?
This order of computation is not guaranteed by the C reference. That means that every compiler is free to do it in whatever order it sees fit. For that reason (and for the sake of readability) you should avoid writing in this manner.
``` #include <stdio.h> int number, total; int main (void) { total = 0; while (true) { printf ("Enter a number (-1 to stop)\n"); scanf (" %d", &number); if (number < 0) { break; } total = number + total; } printf ("The total is %d", total); return 0; } ``` When I use awhile (true)loop in a C program on OSX, I get the following error ``` 'error': use of undeclared identifier 'true' while (true) ``` However when I run this on my Windows partition (through the GCC program), I get no error.. Is this a limitation of GCC on osx?
Add the following to the top of the file: ``` #include <stdbool.h> ``` That will definebool,true, andfalse.
How do I convert from string to unsigned int? I know thatstrtoul()converts from string tounsigned long int, but I want normalintand notlong int. I haven't been able to find a function that does that.
but I want normal [unsigned] int and not long [unsigned] int. You want to usestrtoul(), assign it to along unsigned int, test the result for being in the range of[0..UINT_MAX]and if this is the case assign thelong unsigned intto anunsigned int.
This question already has answers here:How to correctly printf strings and characters with %s and %c(7 answers)Closed7 years ago. When to use %s instead of %c. For example: ``` #include <stdio.h> #include <string.h> int main(void) { char name[31] = "My name is Arnold"; printf(" %c \n", name); return 0; } ``` If I change %c to %s I get : My name is Arnold, but if change %s to %c I get something weird like this: ``` ▒ ```
Passing wrong arguments to format specifiers isundefined behavior. Therefore you obtain such a weird output. "%s"expects a pointer to a null-terminated string (char*)."%c"expects a character (int). Surprised? Readthis. To print the nthcharacter ofname, use ``` printf(" %c \n", name[n]); ```
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question could someone explain me how this function works? I can'n understande the passage where it says k--, what does it means? and when do i have to consider the last line? when the two " if " clauses are false? ``` int h(int n, int k) { int i; for(i=2;i<=n;i++) { if (g(i) && n%i==0) k--; if (k==0) return i; } return 0; } ```
k--; it`s the same that k= k-1 When g(i) and n%i==0 are true,the function subtract 1 to k, if k==0 then the function returns i; but if i>= n, then h returns 0. The two " if " clauses are independent. Without the function g we can`t say anything more.
I am trying to learn OpenCL. I got an environment correctly setup (tested with some example programs). Now I am trying to program an example kernel where it simply squares the number that is passed to it. However, I get random data in the return buffer and never the correct answer. Here is my code: https://gist.github.com/kylecook80/1582719480e4f40d2939
You should always check the return status of each OpenCL call to see if it was successful or not. If you do that, you will notice an error at line 47: ``` cl_kernel kernel = clCreateKernel(program, "hello", NULL); ``` You have no OpenCL kernel named"hello", it should be"square".
For example the text file contains a line :A B CSo the method will declare 3 variables:in A, B ,C;
No . This type of facility is available in scripting languages like python and ruby but not in c/c++. You can use hashing or a struct to store this type of information.
CASE 1: ``` #include <stdio.h> int main() { int a = 5,*p; *p = &a; printf("%d",*p); } ``` the above mentioned program gives the segmentation fault problem. but in the case 2 it works fine. CASE 2: ``` #include <stdio.h> int main() { int a = 5,*p = &a; printf("%d",*p); } ``` can anyone please explain this problem. Thank you.
``` *p = &a; ``` Dereferencespand assigns&ato the memory locationpis pointing to. The pointer is uninitialized, so dereferencing it yieldsundefined behavior(thus the segmentation fault). ``` int a = 5,*p = &a; ``` Definesaandp, where the asterisk doesn't indicate dereferencing but distinguishes a usualintdefinition from aint*pointer definition. The line is equivalent to ``` int a = 5; int* p = &a; ```
I'm trying to read floats from string splitting them up to 2 integers. ``` sscanf(line, "%d.%d", &dec, &frac)); ``` This works with strings like this: ``` "0.25" ``` But if theres an optional sign before the number, it doesn't work anymore. ``` "-0.25" ``` How can i 'tell' sscanf, that there might be an optional sign before the number?
As far as I can see%dis fine because it is for signed integer, but the issue here comes from the fact that-0is0... You will have to find a workaround since I don't think you can find a clean and easy way for that specific case.
This question already has answers here:Error: lvalue required in this simple C code? (Ternary with assignment?)(4 answers)Closed7 years ago. at this code ``` (nr % 10) % 2 == 0 ? a[i] = nr % 10 + 1 : a[i] = nr % 10; ``` I get alvalue required as left operand of assignment. Can anyone help me with this?
The overall problem with this code is that conditional operator is anexpression, not astatement. Although you can use assignment expressions as its part, it's better to do the assignment of the whole expression, like this: ``` a[i] = (nr % 2) == 0 ? nr % 10 + 1 : nr % 10; // ^^^^^^^^ // No need to obtain a remainder of division by 10, // because 2 is a divisor of 10. ``` Note:You could avoid the conditional altogether with a simple trick: ``` a[i] = nr % 10 + (1 - (nr % 2)); ```
I have array of numbers like: ``` int a[10]={1,1,1,1,1,1,1,1,2,1}; ``` I find position of 2 and then change the value of indexof(2)+4 and -4 to 2 too. Problem is that indexof(2)+4 does not exist which mean c will overwrite some memory that does not belong to array. How can I stop c to writing into indexes that exceed length of the array?
In C, there is no built-in checking (i.e. that happens without programmer involvement) to ensure array indexing keeps within bounds. If you want to access (read or write)a[i]then you need to write code check thatiis a valid index before doing so, and don't accessa[i]ifiis invalid. That means ensuring the value is between0andn-1, wherenis known to be the number of elements in the array. There are various options to obtain or set the value ofn. Each have limits on applicability.
I've been toying with basic client/server communication in C, and I'm trying to determine the best way of detecting a disconnected client. I know that if I want a blocking solution I can simply branch off read(). However, in a non-blocking context, particularly with a network disruption rather than a clean disconnect, will read() still detect the broken connection in a timely manner? Right now I'm just sending keep-alive messages from the client on an interval and checking for timeouts server-side, and I'm wondering if there's a cleaner way.
Regardless of the blocking mode, a series of TCPsend()operations will eventually fail withECONNRESETif the peer has disconnected for any reason, and a TCPrecv()will return zero if the peer has disconnected cleanly.
So, I have written a simple program inCwhich opens a file calledprog6_input.txtand generates another file calledprog_output.txt. However, the code below works perfectly for Windows but fails whenever I compile on a Mac. (I also assume this is having the same issue with create the file as well) ``` FILE *ptr_file = fopen("prog6_input.txt", "r"); // We Don't have a input file if(!ptr_file) { perror("Error Reading Input file.\n"); return 1; } ``` For perror:No Such file or directory The file, as seen in the screenshot below, is in the same directory. This works in windows, but does not in Mac OSX? Why is this and how would i fix it? UPDATE: In order to vompile i usedmake mainin the directory using terminal.
You should open up a terminal,cdto yourProg6directory, and run your executable with./main.
I am a beginner in learning c although I took two java courses at school. I just started learning c with "The C Programming" book. I am trying to compile my first program, "hello.c" I typed in as the book says: ``` #include <stdio.h> main() { printf("hello, world\n"); } ``` However, it says that I have to write the type specifier 'int' before main(). I'm trying to understand why this is so because the book dosen't indicate about the type specifier. Thank you!
Yourmainfunction needs to return something, that's what the compiler is telling you. ``` #include <stdio.h> #include <stdlib.h> int main() { printf("hello, world\n"); return EXIT_SUCCESS; } ``` EXIT_SUCCESSis defined instdlib. It means that the application successfully ended. Its value is usually 0.
i'm looking at part of an algorithm, and most of my c knowledge comes from knowing java. i understand that this is a conditional, but what exactly is the order of execution here/what's happening step by step? Thanks! ``` int i, j, k; int *x = malloc(n * sizeof (int)); for (i = 0, j = m, k = 0; k < n; k++) { x[k] = j == n ? a[i++] : i == m ? a[j++] : a[j] < a[i] ? a[j++] : a[i++]; } free(x); ```
It is equivalent to: ``` for (i = 0, j = m, k = 0; k < n; k++) { if (j == n) x[k] = a[i++]; else if (i == m) x[k] = a[j++]; else if (a[j] < a[i]) x[k] = a[j++]; else x[k] = a[i++]; } ```
I have a GArray of GValue (all non-zero) which has been allocated at runtime with g_array_append_val. I wonder how can I find out what's the index of the last element, or more precisely how many elements does the array hold. Code like ``` for (length=0;g_value_get_int(&g_array_index(array, GValue, length)); length++); return length ``` would fail with an out of bounds.
It doesn't seem to be well-documented, but the number of the elements in the array is stored in the fieldarray->len. It's describedhere.
I don't understand what a pointer does in theforloop.What does the*pdo in the following loop? ``` char str[128] = "Some Text"; char *p; for (p = str; *p /*what does this mean?*/; p++) { // Code } ``` I do understand the rest, but why isn't*plikep > 3or something like that?Why is it alone?Why is it written that way?
In a Boolean context such as the condition of aforloop, each expression in C evaluates to true (non-zero) or false (zero). You want theforloop to terminate, when it reaches the end of the string. In C, each string is terminated with the character'\0', which is practically0. So, when theforloop reaches the end of string,*pevaluates to'\0', which is0, which evaluates to false, which terminates theforloop.
I have a select based server system, where I can manage multiple clients. The server automatically reads and responds to the client, which is great. But there's a minor issue. For instance user#1 changes directory (coded withchdir), all of the other users are affected by this change. I really do wish that prevented for happening.
There's two ways to solve this: Fork off a separate process to handle each connection. This process can have its own state, including current working directory. The disadvantages are that you'll need to refactor your code quite a lot, and if you have a lot of concurrent connections then it can be a performance problem. This is harder on Windows that *nix, but not impossible.Keep the current directory as a per-connection settingwithinyour program, and (re)set the directory before executingeveryuser command.
As I know the memory location 0x00000000 isn't accessible through a pointer in C, but recently in my project I was able to access the zeroth location using a pointer. The the zeroth location is flash memory. But according to the postWhy is address zero used for the null pointer?, referencing zero through pointer is a reserved value. So, my question is as it is a reserved value why this doesn't hold true for memory mapped to flash at location zero? Processor :TMS470Rxx OS :Micro C OS-II Thanks
There are many platforms where address zero behaves differently than on the typical desktop PC. There are microcontrollers where hardware devices are memory-mapped at device zero. There are operating systems that will happily let you specifically map something at address zero if you wish to. If you have writable flash mapped there, then you can write there. Different platforms work in different ways.
As I know the memory location 0x00000000 isn't accessible through a pointer in C, but recently in my project I was able to access the zeroth location using a pointer. The the zeroth location is flash memory. But according to the postWhy is address zero used for the null pointer?, referencing zero through pointer is a reserved value. So, my question is as it is a reserved value why this doesn't hold true for memory mapped to flash at location zero? Processor :TMS470Rxx OS :Micro C OS-II Thanks
There are many platforms where address zero behaves differently than on the typical desktop PC. There are microcontrollers where hardware devices are memory-mapped at device zero. There are operating systems that will happily let you specifically map something at address zero if you wish to. If you have writable flash mapped there, then you can write there. Different platforms work in different ways.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question How can i combine one increment and one decrement statements into one single statement in C language. ex: a++ and b-- into one single statement.
Writea++,b--; Two expressions separated by a comma are evaluated left to right.
I have a structure like this ``` for(..;..;..) { if(true) { } //statements } ``` I want to write a statement inside if except goto that will send the control only outside if and execute statements that I have marked.
A common way to handle this situation is to put the body of theifstatement into a separate function, and then return from the middle of the function if, for some reason, the function is unable to finish. After the function returns, the remainder of the statements in theforloop will run. ``` void foo(void) { //statements //statements if ( something_bad_happened ) return; //statements //statements if ( some_other_bad_thing_happened ) return; //statements //statements } void bar(void) { for(..;..;..) { if ( some_foo_is_needed ) foo(); //statements //statements } } ```
I tried to make a dynamic 5x5 int array ``` int **data=malloc(5*5); ``` But I get segmentation fault on trying to access it.
You need to allocate memory for the 2d-array you want to make (which I think you understand). But first, you will have to allocate the space for pointers where you will store the rows of the 2D-array. ``` int **data=(int**)malloc(sizeof(*data)*5); //Here 5 is the number of rows ``` Now you can allocate space for each row. ``` for(int r=0;r<5;r++){ data[r]=(int*)malloc(sizeof(**data)*5);//here 5 is the width of the array } ``` If you want contiguous block of memory for the whole array, you can allocate a single dimension array of size 25, and access it likedata[r*5+c]. PS: Instead ofsizeof(*data)andsizeof(**data), you can usesizeof(int*)andsizeof(int)to avoid confusion with* PS: If you are not using C++, removing the casts from return value of malloc is better (see comments).
I have aCcode that executes some commands on the shell. The code is something like this: ``` int main(){ int x=0; x=system("some command"); printf("Exit Status:%d\n",x); return 0; } ``` The problem here is upon failure I get some other values than the exit values into x. Suppose if we executexyzonbashit exits with status=127 as the command is not found or 1 if the command exists and fails. How do I get this 127 or 1 into myCcode.
Use (on Linux at least) the macros related towaitpid(2) ``` int x = system("some command"); if (x==0) printf("command succeeded\n"); else if (WIFSIGNALED(x)) printf("command terminated with signal %d\n", WTERMSIG(x)); else if (WIFEXITED(x)) printf("command exited %d\n", WEXITSTATUS(x)); ``` and so on. Read more aboutsystem(3). Beware ofcode injectionwhen passing tosystemsome runtime-generated string.
Here's my problem.. I have two arrays: one has the total marks of students and another is a character string. So, I want the computer to assign a letter grade to the character string when the array with the total marks is in within a range.. Here's what a came up with but it won't compile and I don't have anything else in mind:
Try this: ``` sprintf(grade[i], "%s", "A+"); ```
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.Closed7 years ago.Improve this question I'm new to C and reading in C11 , is it sufficient to depend on standard C11 threading functions in "thread.h" like cnd_init, cnd_destroy, cnd_signal, cnd_broadcast, cnd_wait, or there are other libraries I shall consider for using threads in server applications.
Implementations of C11 threads are, unfortunately, still pretty uncommon. You might be interested inTinyCThread(disclaimer: I am the maintainer), which is basically a C11-compatible wrapper on top of pthreads and the Windows API. That lets you start using the C11 API right now, and on platforms where C11 threads are available you can just use that instead of TinyCThread without any code changes.
I didnt get the logic behind the answer. I tried to print the value of a after definition and it shows a=72. Please help. ``` #include<stdio.h> main() { int a=400*400/400; if(a==400) printf("Do good"); else printf("Have good"); } ``` output : Have Good
I guess that on your platformintis 2 byte wide, 16 bit. Then ``` 400*400 = 28928 ``` Due to overflow ``` 28928/400 = 72 ```
I'm looking at this function, ``` int func(int a, int b){ return (a ^ (1 << b)); } ``` What is actually going on? I understand that it's basically saying, " a XOR (2^b) ", that is, a xor 2 to the power of b. But beyond that what is actually happening, and why? I guess I'm looking for some sort of pattern in this formula.
This particular expression toggles the b-th bit of a. This could be useful for example if you want to treat yourintas a boolean array (or a bitmask), and negate the entry at position b.
I would like to know if this is possible and where something like this can be applied. I got asked this question somewhere and my thinking is you would have a const for something whose value you know is not going to change or rather you would not want to change. By definition however, volatile variables can change at any time even by code outside the current scope. So it seems to me that both these two qualifiers contradict each other.
Yes, there are cases where it can make sense. In summary, aconst volatilemeans that the code cannot change the value of the variable, but something outside of the program can. Some usecases for this include: Read-only hardware registersRead-only shared memory buffers where one CPU writes and another only reads Here is a good article with much more detail:http://embeddedgurus.com/barr-code/2012/01/combining-cs-volatile-and-const-keywords/
I got this sample code and I really do not understand how does it work. It is compiled by GCC and there are no errors at all. Also, can you please tell me what this piece of code "i = i&1" does? Thank you! ``` int main(void){ int i; for (i = 5; i--; i = i&1) { puts("iteration"); } printf("%d\n",i); return 0; } ``` Output of this program is: iteration-1
At the begin of the for-Loop: i is set to 5 Next step is: Check i--, which means: First: i = 5 > 0 => trueSecond: set i to i - 1 => i = 4 Next step: do the inner block. Next step: i = i & 1, which results in: 4&1 => 0100 & 0001 => i = 0 Next step: Check i-- First: i = 0 => falseSecond: set i to i - 1 => i = -1
A function I want to use requires an input of afloat **array. How can i initialize this to be a 2x2 array? Just usingfloat[2][2] = {{0,100},{0,200}}obviously doesn´t work. I also tried ``` float** ranges = new float*[2]; ranges[0] = {0,100}; ranges[1] = {0,200}; ```
``` float** ranges = new float*[2]; ranges[0] = {0,100}; ranges[1] = {0,200}; ``` doesn't work since: The RHS is an initilaization list that cannot be assigned to a pointer.range[0]andrange[1]are pointers for which memory needs to be allocated first. And then, you can assign values to individual elements. You can use: ``` ranges[0] = new float[2]{0,100}; ranges[1] = new float[2]{0,200}; ``` or ``` ranges[0] = new float[2]; ranges[0][0] = 0; ranges[0][1] = 100; ranges[1] = new float[2]; ranges[1][0] = 0; ranges[1][1] = 200; ``` Of course, make sure to add code todeletethem.
I am not sure why my program is not showing "Hello World". I am trying by executing onlyprintf(). Is there anything I am missing here? Below is my complete program ``` #include <stdio.h> int main() { printf("Hello World"); return 0; } ```
Myguessis that the console window which contains the output flashes by so quickly that you don't have time to see it. You need to put in something to halt the program so you can see the output. One way of doing it is to ask the user to press theEnterkey. Something like ``` #include <stdio.h> int main(void) { printf("Hello World\n"); printf("Press the Enter key to continue\n"); (void) getc(stdin); return 0; } ```
I'm reading up onlibmill, and it's written on the landing page that "It can execute up to 20 million coroutines and 50 million context switches per second." While this is impressive, why even include this number? Wouldn't these numbers vary with the type of hardware the library is being used on? If the limitation is imposed by the library or the language, why would such a limitation exist?
This is more boasting and not a serious constraint. What most likely happened is that they ran some sort of benchmark on a machine and are now advertising that fact. Much more akin to "Look! We made it so you can even execute 20 million coroutines and 50 million context switches per second! Impressive, huh?" rather than "We have this technical limitation that says you can only execute 20 million coroutines and 50 million context switches per second." That you seem to have read into it :)
I'm using GMP and I need an array ofmpz_t.sizeof(mpz_t)gives 16, but the numbers I'm storing are considerably larger than that. Doesmpz_tgrow "in place", i. e. do I need to allocate more memory and allow for growth in-place, or does GMP allocate the space for them elsewhere and just keep references (in which case, I'm assuming, I won't have to take any special precautions.)
It is safe to declare an array to store a number ofmpz_tvalues. According tothe GNU MP manual: mpz_tis actually implemented as a one-element array of a certain structure type. This is why using it to declare a variable gives an object with the fields GMP needs, but then using it as a parameter passes a pointer to the object. Note that the actual contents of anmpz_tare for internal use only and you should not access them directly if you want your code to be compatible with future GMP releases.
Consider I calledaio_write()to write large portion of file asynchronously. Then program continued to execute and calledwrite(). FlagNON_BLOCKis not set. Will write() wait until aio_write() is finished? Is it correct to mixwrite()andaio_write()?
Nowrite()will not wait foraio_write()to finish. However, practically - depending upon filesystem, load on a machine, size of IO - you may see thatwrite()finishes afteraio_write(). But there is no guarantee that write issued first will finish first. Mixingaio_write()andwrite()is fine if they do not write to same blocks. If they overlap, you will have to handle all cases of which IO completed first, bit more complicated.
So right now i have this ``` unsigned char getlsbs(unsigned char *p){ int r; unsigned char newByte, temp; newByte = 0; for(r = 0; r < 8; r++){ temp = p[r]; temp &= -temp; // Gets the LSB of p[r] ((newByte & (1 << r)) >> r) |= temp; //This line does not work } return newByte; } ``` for the line that doesn't work I am trying to set the rth int of newByte into the LSD so I can turn 00000000 into something like 10100001 any help would be greatly apreciated
You can't assign to an expression. To simplify the problem:a + 1 = bdoesn't work. Rewrite that asa = b - 1instead. I would just do: ``` for(r = 0; r < 8; r++){ newByte |= (p[r] & 1) >> r; } ```
I'm using GMP and I need an array ofmpz_t.sizeof(mpz_t)gives 16, but the numbers I'm storing are considerably larger than that. Doesmpz_tgrow "in place", i. e. do I need to allocate more memory and allow for growth in-place, or does GMP allocate the space for them elsewhere and just keep references (in which case, I'm assuming, I won't have to take any special precautions.)
It is safe to declare an array to store a number ofmpz_tvalues. According tothe GNU MP manual: mpz_tis actually implemented as a one-element array of a certain structure type. This is why using it to declare a variable gives an object with the fields GMP needs, but then using it as a parameter passes a pointer to the object. Note that the actual contents of anmpz_tare for internal use only and you should not access them directly if you want your code to be compatible with future GMP releases.
Consider I calledaio_write()to write large portion of file asynchronously. Then program continued to execute and calledwrite(). FlagNON_BLOCKis not set. Will write() wait until aio_write() is finished? Is it correct to mixwrite()andaio_write()?
Nowrite()will not wait foraio_write()to finish. However, practically - depending upon filesystem, load on a machine, size of IO - you may see thatwrite()finishes afteraio_write(). But there is no guarantee that write issued first will finish first. Mixingaio_write()andwrite()is fine if they do not write to same blocks. If they overlap, you will have to handle all cases of which IO completed first, bit more complicated.
So right now i have this ``` unsigned char getlsbs(unsigned char *p){ int r; unsigned char newByte, temp; newByte = 0; for(r = 0; r < 8; r++){ temp = p[r]; temp &= -temp; // Gets the LSB of p[r] ((newByte & (1 << r)) >> r) |= temp; //This line does not work } return newByte; } ``` for the line that doesn't work I am trying to set the rth int of newByte into the LSD so I can turn 00000000 into something like 10100001 any help would be greatly apreciated
You can't assign to an expression. To simplify the problem:a + 1 = bdoesn't work. Rewrite that asa = b - 1instead. I would just do: ``` for(r = 0; r < 8; r++){ newByte |= (p[r] & 1) >> r; } ```
Consider I calledaio_write()to write large portion of file asynchronously. Then program continued to execute and calledwrite(). FlagNON_BLOCKis not set. Will write() wait until aio_write() is finished? Is it correct to mixwrite()andaio_write()?
Nowrite()will not wait foraio_write()to finish. However, practically - depending upon filesystem, load on a machine, size of IO - you may see thatwrite()finishes afteraio_write(). But there is no guarantee that write issued first will finish first. Mixingaio_write()andwrite()is fine if they do not write to same blocks. If they overlap, you will have to handle all cases of which IO completed first, bit more complicated.
So right now i have this ``` unsigned char getlsbs(unsigned char *p){ int r; unsigned char newByte, temp; newByte = 0; for(r = 0; r < 8; r++){ temp = p[r]; temp &= -temp; // Gets the LSB of p[r] ((newByte & (1 << r)) >> r) |= temp; //This line does not work } return newByte; } ``` for the line that doesn't work I am trying to set the rth int of newByte into the LSD so I can turn 00000000 into something like 10100001 any help would be greatly apreciated
You can't assign to an expression. To simplify the problem:a + 1 = bdoesn't work. Rewrite that asa = b - 1instead. I would just do: ``` for(r = 0; r < 8; r++){ newByte |= (p[r] & 1) >> r; } ```
I'm working in C, and assume I have 2 bytes in little endian: ``` buffer[0] = 0x01; buffer[1] = 0x02; ``` How can I convert the above into a combined 12 bit number? So after combining it should look like: ``` 0x0201 ```
This is a 16 bit number. each byte is 8 bits. int i = (buffer[0] & 0xFF) | (buffer[1] << 8); If you want 12 bits then this int i = (buffer[0] & 0xFF) | ((buffer[1] & 0x0F) << 8); Convert back to buffer ``` char buffer[2]; buffer[0] = i & 0xFF; buffer[1] = (i >> 8) & 0x0F; ```
Is there a way of using the-wrapoption for all functions defined in a source file, without listing them by hand? I thought about some wildcard for that option, but my research resulted in nothing. I also considered investigating a way for extraction of source file functions withmake, also without success. Is there any other way to do it?
You may usectagsas suggestedhere,sedto add-wrapin front of each and inject the result on the command line. --- Edit --- For example, something like: ``` a=`ctags -o- --fields=-fkst --c-kinds=f myprint.c | cut -f1 | sed -e 's/^\(.*\)/-wrap \1/g'` echo $a ``` would give you: ``` -wrap main -wrap myprint ``` You can also combine everything in one line: ``` ld ... `ctags -o- --fields=-fkst --c-kinds=f myprint.c | cut -f1 | sed -e 's/^/-wrap /'` ```
I am embedding Neko VM into my desktop application. I did a lot of searching, but I am still unable to find out any helpful information regarding these 2 functions, which are declared in theneko_vm.h: ``` void *neko_vm_custom( neko_vm *vm, vkind k ); void neko_vm_set_custom( neko_vm *vm, vkind k, void *v ); ``` What are these functions for? Update 1 Got some responsehere.
Withneko_vm_set_customyou can attach a custom variable (a context for example) of a user defined kind to your Neko virtual machine. Withneko_vm_customyou get that variable of that kind back. An example might be: you have one or more VMs running, which are connected to their databases. Withneko_vm_set_customyou attach the database connection for specific VM and withneko_vm_customyou can get it back.
I am embedding Neko VM into my desktop application. I did a lot of searching, but I am still unable to find out any helpful information regarding these 2 functions, which are declared in theneko_vm.h: ``` void *neko_vm_custom( neko_vm *vm, vkind k ); void neko_vm_set_custom( neko_vm *vm, vkind k, void *v ); ``` What are these functions for? Update 1 Got some responsehere.
Withneko_vm_set_customyou can attach a custom variable (a context for example) of a user defined kind to your Neko virtual machine. Withneko_vm_customyou get that variable of that kind back. An example might be: you have one or more VMs running, which are connected to their databases. Withneko_vm_set_customyou attach the database connection for specific VM and withneko_vm_customyou can get it back.
I am embedding Neko VM into my desktop application. I did a lot of searching, but I am still unable to find out any helpful information regarding these 2 functions, which are declared in theneko_vm.h: ``` void *neko_vm_custom( neko_vm *vm, vkind k ); void neko_vm_set_custom( neko_vm *vm, vkind k, void *v ); ``` What are these functions for? Update 1 Got some responsehere.
Withneko_vm_set_customyou can attach a custom variable (a context for example) of a user defined kind to your Neko virtual machine. Withneko_vm_customyou get that variable of that kind back. An example might be: you have one or more VMs running, which are connected to their databases. Withneko_vm_set_customyou attach the database connection for specific VM and withneko_vm_customyou can get it back.
What is the Win32 API for sending messages between computers? I mean, what used to be achieved by the "net send" command and is now using "msg". I imagine it is some API over NetBIOS?
Bothnet sendandmsguse theWTSSendMessage()function.
I was using Sublime Text to compile a code I made, but it gave me this error: ``` [Decode error - output not utf-8] [Finished in 0.2s with exit code 1] ``` I though it was because I didn't save it to UTF-8, but when I save with UTF-8 it gives me the same error. I tried to compile it using IdeOne, it compiles fine, but it gives Time limit exceeded, but this is because of the code. Here is my code: ``` #include <stdio.h> int main(void) { int x, d; for(x=1; ; x++){ for(d = 2; d <= 20; d++){ if(x%d != 0){ break; } } if(d == 21){ break; } } printf("%d", x); return 0; } ``` It may seem it has an infinite loop but it didn't.
Your program is fine but it takes a while (2.3s on my computer, yours might be slower) to terminate which is the reason why IdeOne complains. The firstxto satisfy your test is232792560.
If some memory is already allocated (for example usingmalloc), is it possible to then share that memory with another process, for example by marking the page as shared? To be clear, this is distinct from initially allocating the memory as shared memory, for example usingshmgetand similar. Obviously it is possible to do this withmemcpy, but is there a way to do it directly?
``` mmap() creates a new mapping in the virtual address space of the calling process. The starting address for the new mapping is specified in addr. The length argument specifies the length of the mapping. ``` So I imagine: Open a file in donor process for writing.mmap() your existing malloc'd memory.Open same file in another process.Enjoy shared memory.
I have some code which extracts bits from a number: ``` uint32_t foo = getValue(); /*this just returns a value for `foo`*/ while (foo){ foo <<= 2; doSomethingWithFoo(foo); } ``` I'm worried that I have undefined behaviour here since I'll end up "overshifting"foo. Am I correct?
Your code is safe. That's because the behaviour of several shifts is well-defined (so long as each one doesn't shift by too much). Essentially, you're starting with a brand newfooon each iteration. The problems only arise if you attempt to shift by more bits than there are in the typein one go.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question I have tried to do the following:system("SMC_v3 %s %s %s %s %s %s %s", trials, Np, Ni, Nn, w, Structure, V);to call SMC_v3.exe with command line variables. But there are too many variables. How can I use system() with the command line variables? (this needs to go in a loop)
systemdoes not understand the same%sspecifiers asprintfdoes. You will have to build the string first, for example usingsprintf, and then callsystemwith that string.
I have the following code, where we try to left shift certain bits of a value: ``` int main() { unsigned long mvb = 1; mvb << 8; printf("The shift value is %u\n", mvb); mvb << 56; printf("The shift value is %u\n", mvb); } ``` but the result for all those two operation are both1, what is the reason, and how use it correctly?
You need to assign it back to mvb after shifting like: ``` mvb = mvb << 8; ```
here is my code, I try sample code fromhere ``` #include <stdio.h> #define type_idx(T) _Generic( (T), char: 1, int: 2, long: 3, default: 0) int main(int argc, char *argv[]) { puts(type_idx("smth")); } ``` the output in clion is: ``` /home/roroco/.CLion12/system/cmake/generated/c9a7a4c5/c9a7a4c5/Debug/ex/ex Signal: SIGSEGV (Segmentation fault) ``` and here is my CMakeLists.txt ``` cmake_minimum_required(VERSION 3.3) project(c) set(CMAKE_C_COMPILER /usr/bin/gcc-4.9) set(CMAKE_CXX_COMPILER /usr/bin/g++-4.9) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c11") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") ```
The string literal"smth"decays into a pointer of typechar*, which will get translated to the default clause of _Generic. You get the value 0, so your code is equivalent to ``` puts(0); ``` Which doesn't make any sense and will cause your program to crash.
What are the differences, if any, between ``` *a = b; ``` and ``` a = &b; ``` Are these two different ways to make a var point to another var?
No, they do not do the same thing.*a = b;does not changeabut it changes whatapoints to.a = &b;does changeabut it does not change whatapointed to.
The below code should output 100 to my knowledge of stringification.vstr(s)should be expanded with value of 100 thenstr(s)gets 100 and it should return the string "100". But, it outputs "a" instead. What is the reason? But, if I call with macro defined constantfoothen it output "100". Why? ``` #include<stdio.h> #define vstr(s) str(s) #define str(s) #s #define foo 100 int main() { int a = 100; puts(vstr(a)); puts(vstr(foo)); return 0; } ```
The reason is thatpreprocessorsoperate on tokens passed into them, not on values associated with those tokens. ``` #include <stdio.h> #define vstr(s) str(s) #define str(s) #s int main() { puts(vstr(10+10)); return 0; } ``` Outputs: 10+10
i need to write a program to simulate rolling of two dice and store their sum in an array. it is given that frequency of sum=2&12 should be minimum and frequency of sum=7 is maximum. this is the code i've written. i need random numbers between 2 and 12 with said frequencies ``` #include <stdio.h> #include <stdlib.h> #include<time.h> int main() { int i, n; n = 5; srand ( time(NULL) ); for( i = 0 ; i < n ; i++ ) { printf("%d\n", rand() % 12); } return(0); } ```
Callrand()to generate a number for each of the 36 pairs, then return the sum. ``` int dice2sum(void) { int r = rand()%36; int die1 = r%6 + 1; int die2 = r/6 + 1; return die1 + die2; } ```
I'm trying to create a window, let's say 400x400: ``` SDL_Init(SDL_INIT_VIDEO); Uint32 mode = SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE; SDL_Window* window; SDL_Renderer* renderer; if (SDL_CreateWindowAndRenderer(400, 400, mode, &window, &renderer)) return 2; if (!window || !renderer) return 2; SDL_RenderClear(renderer); SDL_RenderPresent(renderer); SDL_Event event; int quit = 0; while (!quit) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) quit = 1; } } SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); ``` I see a window filled with black pixels. However, the window's size is 500x500 withouth borders, and 502x540 with them, but why?
On Windows, the OS may stretch your window in the case when you are using a high DPI monitor. You can disable this stretching using: ``` SDL_SetHint(SDL_HINT_VIDEO_HIGHDPI_DISABLED, "1") ```
I have successfully loaded and played a sound clip but want to update it from disk while the application is running. I'm calling alBufferData again for my clip but get Invalid Operation error. Both old and new sound clips are valid and work in isolation, it's only the reloading that fails. How can I reload sound data for a clip? I'm using OpenAL on OS X but remember having the same problem also on Windows with OpenAL-soft.
CallingalSourcei( srcID, AL_BUFFER, 0 );beforealBufferData()solved the problem.
I am currently attempting to learn C, and have made this program to calculate the area of a regular hexagon: ``` #include <stdio.h> #include <math.h> void main(){ int a; float ans; scanf("%d", &a); // get length of side ans = ((pow(a, (1/3)))/2)*(a*a); printf("%f", ans); } ``` However, it outputs seemingly random numbers.
Firstly your code doesn't compile (Missing semicolon) and also you should useint main()instead ofvoid main(). Secondly your formula also wrong, the area of a regular hexagon of side lengthais calculated as((3√3)/2)*a². Thirdly Expression like1/3always yield zero as both are integer, to get expected behavior make one of them float/double. like1.0/3or(float)1/3etc. ``` #include <stdio.h> #include <math.h> int main() { int a; float ans; scanf("%d", &a); // get length of side ans = (3*sqrt(3)/2.0)*a*a; printf("%f", ans); } ```
When I run the following code (on Eclipse), I get a pop-up message that the .exe has stop working: ``` #include <stdio.h> main () { int x; x = 1; printf(x); } ``` I know that I should code it as follows in order to make it run: ``` printf("%d", x); ``` However, my question is simply what's going on "in there" when I code it the former way.
Theprintf()first parameter is meant to be a string. In C, the value '1' is pushed onto the stack to call printf. printf is expecting a string, so it starts to treat 1 as an address. This causes the "stops working" - when it tries to look at the characters at address 1.
Creating an uint8_t "string" works fine for me: ``` uint8_t myString[] = "Foo"; ``` However when I try to declare it in a struct, it does not work: ``` #ifndef PLAYER_H_ #define PLAYER_H_ #include <stdint.h> typedef struct{ uint32_t id; uint8_t name[]; uint16_t life; uint16_t mana; uint16_t fist; uint16_t shielding; } player; #endif // PLAYER_H_ ``` I get a compilation message saying:Field has incomplete type uint8_t[]. What am I missing here guys?
``` uint8_t name[]; ``` You have not mentioned size here , either mention size ofname. You cannot create array of unknown size in somewhere middle of your structure. ``` uint8_t name[50]; // this could do ``` And you could initialize it like this - ``` player p1={.name="hello"}; ``` Or usememcpy.
``` #include<stdio.h> int main(void) { char op; int arr[3]; printf("input "); scanf("%d %c %d", arr,&op,arr+1); arr[3]=arr[0]-arr[1]; //here printf("[%c] %d\n", op, arr[3]); return 0; } ``` arr[3]=arr[0]-arr1; printf("[%c] %d\n", op, arr[3]); why does not print %c ?
This: ``` arr[3]=arr[0]-arr[1]; printf("[%c] %d\n", op, arr[3]); ``` should be ``` arr[2] = arr[0] - arr[1]; printf("[%c], %d\n", op, arr[2]); ``` because array indices start from 0 and end at length - 1. Usingarr[3]leads to Undefined Behavior as you access memory locations that you shouldn't. In your case,arr[3]might've beenop. So in the examples you've given,op's value is changed to 2 and 1 respectively, and thus, theprintftries to print an unprintable control character and the terminal displays a space as these control characters are unprintable.
I have a function provided by a library (so I can't edit the source code for it), that prints output to stdout. I wish to get that output in a string variable, so that I can check some conditions on it. What is the best way to do this? Can I do it without multithreading and file I/O? [EDIT] Similar questions(pointed out in comments): Using multithreading: Capture Output of Spawned Process to string If you know output size beforehand: redirect output from stdout to a string?
Use rdbuf. ``` std::stringstream stream; auto * old = std::cout.rdbuf(stream.rdbuf()); CallFunction(); std::cout.rdbuf(old); std::string value = stream.str(); ```
``` #include<stdio.h> int main(void) { char op; int arr[3]; printf("input "); scanf("%d %c %d", arr,&op,arr+1); arr[3]=arr[0]-arr[1]; //here printf("[%c] %d\n", op, arr[3]); return 0; } ``` arr[3]=arr[0]-arr1; printf("[%c] %d\n", op, arr[3]); why does not print %c ?
This: ``` arr[3]=arr[0]-arr[1]; printf("[%c] %d\n", op, arr[3]); ``` should be ``` arr[2] = arr[0] - arr[1]; printf("[%c], %d\n", op, arr[2]); ``` because array indices start from 0 and end at length - 1. Usingarr[3]leads to Undefined Behavior as you access memory locations that you shouldn't. In your case,arr[3]might've beenop. So in the examples you've given,op's value is changed to 2 and 1 respectively, and thus, theprintftries to print an unprintable control character and the terminal displays a space as these control characters are unprintable.
I have a function provided by a library (so I can't edit the source code for it), that prints output to stdout. I wish to get that output in a string variable, so that I can check some conditions on it. What is the best way to do this? Can I do it without multithreading and file I/O? [EDIT] Similar questions(pointed out in comments): Using multithreading: Capture Output of Spawned Process to string If you know output size beforehand: redirect output from stdout to a string?
Use rdbuf. ``` std::stringstream stream; auto * old = std::cout.rdbuf(stream.rdbuf()); CallFunction(); std::cout.rdbuf(old); std::string value = stream.str(); ```
Starting from ``` char tval[20] = "temp:26.62"; ``` how can I add a space character untiltvalis filled? I need that in the end to obtain this: ``` char tval[20] = "temp:26.62 "; ```
Like this, probably ``` size_t prevlen = strlen(tval); memset(tval + prevlen, ' ', 19 - prevlen); *(tval + 19) = '\0'; ```
I need to debug an application written in C that reads and writes to segment register FS. To debug this application I need to see the memory address where FS points to. The application uses code like this: ``` mov rdx, fs:[rcx] mov fs:[rcx], rsi ``` How do I get the linear virtual address of a read/write from/to segment registers? I can compile this application for either Linux or Winodws.
On linux, you can usearch_prctl(ARCH_GET_FS, &fsbase). In windows, if theFSis pointing to the TEB as usual, you can readfs:[0x18]to get the base address, or use features of your debugger if available.
This article :https://superuser.com/questions/724301/how-to-solve-bash-cannot-execute-binary-filecan not help me to solve my problem. The step is below: ``` gcc -c hello.c -o hello.o ``` when I enter command : ``` ./hello.o ``` the message is : ./hello.o: command not found I try this: ``` chmod 755 ./hello.o ``` execute again, the message is : -bash: ./hello.o: cannot execute binary file I have checked the file version, it isMach-Oformat for binaries. I enter this command: ``` file ./hello.o ``` it shows: ./hello.o: Mach-0 64-bit object x86_64 How can I solve this problem?
Remove -c from the compilation command. With -c you are producing an object file, not an executable. And probably you do not want to call your executable hello.o as the convention is for .o files to be object files. Sogcc -o hello hello.c; ./hello
I want to allocate space for an array of pointers to structs so here is what I did. ``` typedef struct A_example{ struct B_example* B_array[MAX_SIZE]; } A typedef struct B_example{ int a; }B A A_array[MAX_SIZE2]; ``` so to allocate memory for B_Array for an element of A_array I do this: ``` A_array[current_element].B_array[i] = (struct B_example*)malloc(sizeof(struct B_example)); ``` is this correct? and how should I free the memory for this?
Your allocation appears to be correct (aside from the standard advice that is normally given to not cast the return ofmalloc). You canfreeit viafree(A_array[current_element].B_array[i]);.
I have scanned other questions with similar headers, but non worked with me. I am using cygwin on windows 7 with its opencv package using clang compiler for c, When I tried a simple program to view an image it gave me this message Gtk-WARNING **: cannot open display I have tried setting DISPLAY = 0.0 and didn't solve it just added 0.0 Gtk-WARNING **: cannot open display :0.0
The problem was with cvNamedWindow GUI. It has to be opened from x server(x app menu), so just setup cygwin/x. I didn't open webcam, so I have changed to MinGW and cmake.
I am using the following command to load the c file program and run it in GDB from terminal in one click: ``` gdb --eval-command='file c.out' --eval-command='c' ``` I want to sleep some seconds after loading the program but before starting the program in GDB, some thing like: ``` gdb --eval-command='file c.out' --eval-command='<sleep 5>' --eval-command='c' ```
One way to give gdb a command-line option that will make it pause for 5 seconds is to tell it to run the "sleep 5" command in a shell: ``` --eval-command="shell sleep 5" ```
I need to debug an application written in C that reads and writes to segment register FS. To debug this application I need to see the memory address where FS points to. The application uses code like this: ``` mov rdx, fs:[rcx] mov fs:[rcx], rsi ``` How do I get the linear virtual address of a read/write from/to segment registers? I can compile this application for either Linux or Winodws.
On linux, you can usearch_prctl(ARCH_GET_FS, &fsbase). In windows, if theFSis pointing to the TEB as usual, you can readfs:[0x18]to get the base address, or use features of your debugger if available.
This article :https://superuser.com/questions/724301/how-to-solve-bash-cannot-execute-binary-filecan not help me to solve my problem. The step is below: ``` gcc -c hello.c -o hello.o ``` when I enter command : ``` ./hello.o ``` the message is : ./hello.o: command not found I try this: ``` chmod 755 ./hello.o ``` execute again, the message is : -bash: ./hello.o: cannot execute binary file I have checked the file version, it isMach-Oformat for binaries. I enter this command: ``` file ./hello.o ``` it shows: ./hello.o: Mach-0 64-bit object x86_64 How can I solve this problem?
Remove -c from the compilation command. With -c you are producing an object file, not an executable. And probably you do not want to call your executable hello.o as the convention is for .o files to be object files. Sogcc -o hello hello.c; ./hello
Pretty simple, I need to test a C program by inputting a large number of integers into it. To do this, for this particularly case, I need to run the program, then when it waits for user input (scanf("%d, integer)), I need to give it the integer from the loop I'm currently at. right now I have ``` for i in {1..5}; do (echo -n "$i" && ./a2 $i) done ``` but it still just waits for user input, then after user input is given, prints the integer of the loop I'm on. I've tried a few examples from similar problems I've found on stack exchange and elsewhere but so far no luck. I haven't ever really needed to mess about with shell scripting before so it's probably something simple I'm doing backasswordsly but no one else has done wrong before.
Try this! ``` for i in `seq 1 1000`; do echo $i | ./a2; done ``` Your solution ``` echo -n "$i" && ./a2 $i ``` would pass $i as argument for a2 not input.
I want a bool to determine whether the if condition needs to be reversed, I use my most straight forward way to write this but seems looks dirty! ``` bool isReverseCondition=true; int a=0; bool myCondition=a>0; if(isReverseCondition){ myCondition=!myCondition; } if(myCondition){ printf("OK!"); } ``` It looks dirty, especially need a temp variable "myCondition" to store my actual condition, also it appears not only once! I know it is simple but have no idea to rewrite :( Can anyone give suggestion?
You can use the xor operator like ``` bool myCondition = (a > 0) ^ isReverseCondition; ```
Pretty simple, I need to test a C program by inputting a large number of integers into it. To do this, for this particularly case, I need to run the program, then when it waits for user input (scanf("%d, integer)), I need to give it the integer from the loop I'm currently at. right now I have ``` for i in {1..5}; do (echo -n "$i" && ./a2 $i) done ``` but it still just waits for user input, then after user input is given, prints the integer of the loop I'm on. I've tried a few examples from similar problems I've found on stack exchange and elsewhere but so far no luck. I haven't ever really needed to mess about with shell scripting before so it's probably something simple I'm doing backasswordsly but no one else has done wrong before.
Try this! ``` for i in `seq 1 1000`; do echo $i | ./a2; done ``` Your solution ``` echo -n "$i" && ./a2 $i ``` would pass $i as argument for a2 not input.
I want a bool to determine whether the if condition needs to be reversed, I use my most straight forward way to write this but seems looks dirty! ``` bool isReverseCondition=true; int a=0; bool myCondition=a>0; if(isReverseCondition){ myCondition=!myCondition; } if(myCondition){ printf("OK!"); } ``` It looks dirty, especially need a temp variable "myCondition" to store my actual condition, also it appears not only once! I know it is simple but have no idea to rewrite :( Can anyone give suggestion?
You can use the xor operator like ``` bool myCondition = (a > 0) ^ isReverseCondition; ```
Pretty simple, I need to test a C program by inputting a large number of integers into it. To do this, for this particularly case, I need to run the program, then when it waits for user input (scanf("%d, integer)), I need to give it the integer from the loop I'm currently at. right now I have ``` for i in {1..5}; do (echo -n "$i" && ./a2 $i) done ``` but it still just waits for user input, then after user input is given, prints the integer of the loop I'm on. I've tried a few examples from similar problems I've found on stack exchange and elsewhere but so far no luck. I haven't ever really needed to mess about with shell scripting before so it's probably something simple I'm doing backasswordsly but no one else has done wrong before.
Try this! ``` for i in `seq 1 1000`; do echo $i | ./a2; done ``` Your solution ``` echo -n "$i" && ./a2 $i ``` would pass $i as argument for a2 not input.
I want a bool to determine whether the if condition needs to be reversed, I use my most straight forward way to write this but seems looks dirty! ``` bool isReverseCondition=true; int a=0; bool myCondition=a>0; if(isReverseCondition){ myCondition=!myCondition; } if(myCondition){ printf("OK!"); } ``` It looks dirty, especially need a temp variable "myCondition" to store my actual condition, also it appears not only once! I know it is simple but have no idea to rewrite :( Can anyone give suggestion?
You can use the xor operator like ``` bool myCondition = (a > 0) ^ isReverseCondition; ```
This question already has answers here:scanf() only sign and number(2 answers)Closed7 years ago. I need to parse input like this: "+ 704"Into: switcher = "+" and c = 749I got this: ``` scanf("%c %d", &switcher, &c); ``` This does not work.Scanf returns 1 instead of 2, c = 4196080 andprintf("%c", switcher)prints a newline.What am i missing?
So basically, there's a newline waiting on the buffer. To get rid of it, simply add one space to the beginning of your formatting string. ``` scanf(" %c %d", &switcher, &c); ```
I have a program written in C and the command I am supposed to run it with on linux looks like this: ``` ./program --something X Y ``` What exactly does that mean? I think X Y will be the arguments soargc[2]will beXandargc[3]will beY? But what about--something? Thanks a lot!
The C runtime does not discriminate any arguments, whether they start with--or not. So you have, ``` argv[0] = "./program" argv[1] = "--something" argv[2] = "X" argv[3] = "Y" argv[4] = NULL ``` It is your program that assigns meaning to those values.
There are some#definestatements in my C language code, and now i find some bug. But the codeblocks IDE can not step into the #define block. so i want to get the Pre-compiled source code, which will expand the#definemacro.
If you use the-Eoption of gcc, you can expand the macros to a C file, and then compile the C file.
I'm having a bit of difficulty trying to figure out a way to print some numbers in an array. I have an array[0,1,2,3,4,5,6] and I would like print the numbers 0,1,4,5. Is it possible to create a loop that can read the first two numbers skipping the next two and reading the following two numbers.
You can simply use modulo operation on current index to check if this number belongs to "print 2" or "skip 2": ``` int a[17]; int length = sizeof(a) / sizeof(a[0]); for (int i = 0; i < length; i++) { if (i % 4 < 2) printf("%d ", a[i]); } ``` So, foriequal to 0 and 1, it will output value. Fori == 2andi == 3, the condition will result to false. Next, it will take 4,4 % 4is 0, and it will repeat it every 4 steps.
Withfopen, by setting it towwill automatically clear the file for me. However now I'm trying to do the same thing withopen, ``` int file = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); ``` This won't guarantee that the file is empty and write at the beginning(?). How can I achieve that?
AddO_TRUNC- Initially clear all data from the file.
What are the main differences (and advantages/disadvantages) between using a large time quantum or a small time quantum in respect to round robin CPU scheduling?
In Round Robin Scheduling the time quantum is fixed and then processes are scheduled such that no process get CPU time more than one time quantum in one go. If time quantum is too large, the response time of the processes is too much which may not be tolerated in interactive environment. If time quantum is too small, it causes unnecessarily frequent context switch leading to more overheads resulting in less throughput. In this paper a method using fuzzy logic has been proposed that decides a value that is neither too large nor too small such that every process has got reasonable response time and the throughput of the system is not decreased due to unnecessarily context switches. Edit: Link to article referenced:http://ieeexplore.ieee.org/document/4741092/
I'm looking to write a multithreaded application where one thread waits for another to signal it before continuing. According tohere,sigsuspendis not MT-safe because of a race condition. According tohere,sigwaitshould be used in these cases. I'm trying to understand why. Based on the man page descriptions (sigwaitandsigsuspend), it appears that... sigsuspend (const sigset_t *mask)actually changes theprocess'ssignal mask, which would affect all threads. sigwait (const sigset_t *set, int *sig)just waits for one of the indicated signals insetwithoutchanging the thread's (or process's) signal mask. Is this understanding correct? And if so, how doessigwaitblock without changing the signal mask?
Actually sigwait changes the mask but then restore it, see this (Advanced Programming in the UNIX Environment):Signals and Threads. And also this:Oracle Multithreaded Programming Guide
First time publishing hereSimple situation: In PUTTY, i have to create a file named admin.pid where it stores a PID when the user starts the "app" i'm creating. How can i do this? Thanks
Get the PID usinggetpid().Open the file usingfopen().Write the PID to the file byfprintf().Close the file usingfclose().
First I have used mpg123 remotely using FIFOs to implement Pause functionality, but now I want to close the mpg123 player when file is played through automatically. The code for playing current is ``` pid p = fork(); if (p<0) return; else if (p==0) execlp("mpg123", "mpg123", "-R", "--fifo", "aFifo", NULL); else system("load test.mp3 > aFifo"); ``` Currently if the file is played through then also child processelse if (p==0)will stay there and mpg123 player process will continue to exist
You have no?in your question, but any way your code looks wrong, becausesystemusesforkandexecunder the hood. So instead of oneforkand oneexecyou useforkthree times and usesexecvtwice. Read how to run process here:how to correctly use fork, exec, wait after you run process in proper way, you have real pid ofmpg123, and so you can kill it if you want, or pause or what else you want.
I have a SPARC embedded executable built with debugging symbols. I ran this executable on a machine using a debug monitor, but without a debugger. The program crashed (segfault) and I found out the value of the PC register from the monitor (note: not a debugger). If I were using gdb at the time I would've known which line number it got stuck in. However, I wasn't using GDB at the time. I want to find out what C line number the PC value corresponds to. What tool or gdb command can I use to find this out?
Fromthis part of the documentationyou can use theinfocommand: ``` info line *0x63ff ``` That gets the line information for the code at address0x63ff. Replace the address in the example with your own.
There are some#definestatements in my C language code, and now i find some bug. But the codeblocks IDE can not step into the #define block. so i want to get the Pre-compiled source code, which will expand the#definemacro.
If you use the-Eoption of gcc, you can expand the macros to a C file, and then compile the C file.