question
stringlengths
25
894
answer
stringlengths
4
863
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed10 years ago.Improve this question I wrote a very basicHello Worldprogram to know about sections. After usingobjdumpI got a...
You should google it :here is the first result. It's a good start to learn more about ELF format. About.initand.fini,it's here. Here is a list of the ELF sectionswith a brief description.
I am encountering a problem to print multiple variables (say 25) in a function onGDB Prompt. Is there any convenient way to do this instead of printing every variables manually ? can I have a script or a simpler way which can do my job ?
You can print multiple values usingprintfcommand in gdb. ``` printf "%d,%d\n", a, b ``` To use it in future, you can either define a gdb-function or use gdb-history feature. To define a gdb-function, create/modify file$HOME/.gdbinitwith the following conten,define print_all printf "%d,%d\n", a, b end document p...
I'm having to do the following a lot in a USB (libusb) C based command line utility I am writing: ``` char pid[20]; sprintf(pid, "Product ID : %#06x", anInteger); puts(pid); ``` Is there a shorter, one-liner way to do this?
Instead of usingsprintf&puts, just change toprintf: ``` printf("Product ID : %#06x", descriptor.idVendor); ```
I'm trying to compile libzqm on windows using MinGW (GCC 4.8). Compilation terminates with this error: ``` 'strndup' was not declared in this scope ``` So,strndupshould be instring.hright? I tried to add/mingw/x86_64-w64-mingw32/includetoCXXFLAGSbut didn't work. Any suggestion ?
Try to add ``` #define _GNU_SOURCE ``` before ``` #include <string.h> ``` strndupis not standard C but if you use GNU libc, then you do get it by including the extensions as above.
I have one-dimentional array initialized globally in C++ ``` Gfloat cone1[] = { 0.0f, 2.4f, -11.0f, 30.0f, -1.5, 0.0, 0.0 }; ``` I want to update its all values with different numbers of my choice within my main function writing minimum/one line(s) of code. Is it possible? I don't want to do like :- ``` cone1[0] ...
If you are willing to switch to usingstd::vectororstd::arrayyou can use uniform initialization and an assignment. The following example usesstd::vectorfor a variable sized array. ``` #include <vector> int main() { std::vector<Gfloat> cone1 { 0.0f, 2.4f, -11.0f }; cone1 = { 30.0f, -1.5, 0.0 }; } ``` The fo...
Why when I execute this code: ``` #include <stdio.h> #include <string.h> #include <stdlib.h> int main(){ size_t size = 4; char *str = malloc(size); str = "hello"; printf("malloc %s: %d\n", str, size); printf("strlen %s: %d\n", str, strlen(str)); printf("sizeof %s: %d\n", str, sizeof("hello"))...
With your linestr = "hello", you are reassigning your pointer to point to a spot in memory where"hello"is created. What you're doing here is having a small memory leak with yourmalloc, since you no longer have a reference to the requested heap space.
Is there a good way to split a string (in C or C++) by multiple delimiters while keeping the delimiters as part of the split strings? The only way I've found to do this is using regex and I'd rather not have to pull in another library just to do this? (I'm using STL for strings, not using Boost).
Without regexp, though I'm not sure if it's faster or slower: ``` vector<string> split(string& stringToSplit) { vector<string> result; size_t pos = 0, lastPos = 0; while ((pos = stringToSplit.find_first_of(";,|", lastPos)) != string::npos) { result.push_back(stringToSplit.substr(lastPos, pos-l...
Say, I bind0.0.0.0port X, listen on it, and then accept new connection. How can my server find destination IP address the client used to connect to? Also, via which interface (assuming multihomed server) the SYN arrived?
Thegetsockname()call on the socket returned byaccept()will give you the address of the local end of the connection. The best way to determine the interface is probably just to match up the local IP address fromgetsockname()against the interface addresses.
why do i get a kernel crash ofcpuacct_chargewhen i try to allocate 600 blocks of 2 MB memory using -pci_alloc_consistent, is there a better way to do it ?
You are probably running out of 32-bit-addressable memory. If your PCIe chip actually supports larger addresses, your driver should usedma_set_maskanddma_set_consistent_maskto tell the kernel about this. (SeeDocumentation/DMA-API-HOWTO.txt.)
I tried to use an external struct but when I compile my c code I obtained this message: subscripted value is neither array nor pointer nor vector. Why? messaggio.h ``` struct Request { struct { u_int data_len; float *data_val; } data; bool_t last; }; typedef struct Request Request; ``` ...
Thex.datais a struct, so you cannot use[]with it. Maybe you wantx.data.data_val[0]. Try this code: ``` struct Request x; x.data.data_len = 5; // initialize the length, use any value you need x.data.data_val = (float *) malloc(x.data.data_len * sizeof(float)); x.data.data_val[0] = 4.6 ```
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.Closed10 years ago.Improve this question Basically I am a Java programmer, and not very well know about pointers in C. so, ``` #include<stdio.h> ...
This should print "world", yes. It looks a bit like it's trying to play with the GCC built-in preprocessor symbol__TIME__, but of course it's spelled wrong to do that.
My little program: ``` #include <stdio.h> int main() { signed char c = -128; c = -c; printf("%d", c); return 0; } ``` print: ``` -128 ``` Is minus (-) operator portable across CPU?
The operand of the unary minus first undergoes standard promitions, so it is of typeint, which can represent the value-128. The result of the operation is the value128, also of typeint. The conversion frominttosigned char, being a narrowing of signed types, is implementation-defined. (Your implementation seems to do ...
I want to send data from one file descriptor to another via linux-aio without buffering and without transferring data to and from user space. Is such a sendfile64() funktion possible with linux-aio? I looked at some linux-aio examples (in C/C++) and simple file-copy programs. All these examples do reading -> buffer -...
It's possible if you mmap the file, then you can make a aio sendfile. It's faster then sendfile via do_splice and should not sync at i_mutex. Look at the lighttp linux_aio module.
I have this byte:10111011and i want to split into 2 nibble (msb and lsb).After that i want to take the last 2 bits from the lsb (so i want11from1011).I know that:With10011011 >> 4i get the msb (1001)With10011011 & 0xfi get the lsb (1011)Now what can i do to take the11from lsb1011?
Just the same:bits = lsb & 0x03
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed10 years ago.Improve this question I wrote a very basicHello Worldprogram to know about sections. After usingobjdumpI got a...
You should google it :here is the first result. It's a good start to learn more about ELF format. About.initand.fini,it's here. Here is a list of the ELF sectionswith a brief description.
Alright, I was trying to make a simple function to constantly change its PID, but I get this: ``` error: ‘SIGKILL’ undeclared (first use in this function) ``` here is my code: ``` #include <stdio.h> int changePID(void) { int pid = fork(); printf(pid); sleep(3); kill(pid, SIGKILL); ...
you are missing the line#include <signal.h>for the SIGKILL printf(pid);is not going to work since printf need achar*and you give him apid_t What's the point of killing a child in a loop ? printf is going to segv in the father so you will never reach kill and in the son you are going to kill every process in the p...
I got the following code from internet: ``` struct { int x; struct { int y, z; } nested; } i = { .nested.y = 5, 6, .x = 1, 2 }; ``` The result is: ``` i.nested.y = 2 i.nested.z = 6 ``` But I don't know why,the article from the net doesn't give any explanation.
Non-designated initializers operate always on the next element in the structure. So the latest2operates on what comes after.x, which is.nested.y. In the same way the6goes for thenested.z. If an initializer has several values for an element, the last in the list wins. But if you have compiler that implements designat...
In C, I try to assign a string: ``` void addressItem_icon_download_callback(const char* res_name, int success, void *context, char *last_modified){ char *icon = ((AddressItem_Callback_Contex...
Assuming theAddressItem_Callback_ContextTypeis a struct with a field Icon (char*) ``` typedef struct { char *Icon; }AddressItem_Callback_ContextType; ``` try ``` char *icon = ((AddressItem_Callback_ContextType*)context)->Icon; ``` First you must cast your context into a pointerAddressItem_Callback_ContextType*an...
Just a small question: Can C++ use C header files in a program? This might be a weird question, basically I need to use the source code from other program (made in C language) in a C++ one. Is there any difference between both header files in general? Maybe if I change some libraries... I hope you can help me.
Yes, you can include C headers in C++ code. It's normal to add this: ``` #ifdef __cplusplus extern "C" { #endif // C header here #ifdef __cplusplus } #endif ``` so that the C++ compiler knows that function declarations etc. should be treated as C and not C++.
I dont know why we always declare like this ``` char* name="Srimanth" ``` instead of ``` char name[]={"Srimanth"} ``` I am new to this things. so please be more specific while you are giving me an answer.. thank you.
String literal is a special, simple, form of writing an array aggregate: you can write"hello"instead of{'h', 'e', 'l', 'l', 'o', '\0'}(note the terminating zero, which is added automatically). Note that an array declaration is not only possible, but is sometimes desirable: ``` char str[] = "hello"; str[0] = 'H'; // ...
I have the following code: ``` printf("+--------------+----------\n" " Postal number| Tele\n" "----------+-----------------+---------------\n" "%u | %u", number, tele); ``` but right now the output looks like: ``` +--------------+---------- Postal number | Tele ----------+-----...
There's no direct way to center text. You'll have to combine several elements: Figure out how many digits you have.Calculate how many spaces you want before and after the number.Print:printf("%*s%d%*s", spaces_before, "", num, spaces_after, ""); %*sconsumes two parameters - the first is the length, the second is the...
I created a textbox with following code. It is placed under WM_COMMAND of WNDPROC function. ``` htextbox=CreateWindowEx(WS_EX_CLIENTEDGE,TEXT("Edit"), TEXT("test"), WS_CHILD \ | WS_VISIBLE | WS_BORDER, 100, 20, 140, 20, hWnd, NULL, NULL, NULL); ``` I want to update the element "test" written...
I think you can simply do it like this: ``` SetWindowText(htextbox, TEXT("new text")); ```
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed10 years ago. hello I am learning basics of C programming language, recently i have studied aboutpost and pre increment/decrementoperators and also aboutlvalue and rvalue, the following pr...
Well, let's see what is happening in--x--. At first, post-decrement executes:--(x--).(x--) = 7. After that result of this operation is placed to the original structure:--7- doesn't make sense - thus you getlvalue requirederror
Is there any specific function or any way by which the number of lines in aGDBMfile can be counted?Otherwise, I want to retrieve all the lines in aGDBMfile at once(Iam able to retrieve the key value pairs usinggdbm_fetch()but only one at a time.
I got the solution to the above problem. Now I am able to retrieve all the key value pairs. Solution :here
I had a problem about gwan cache, currently I visit a page serve by gwan (write in C) , which will execute some functions during visit, however, when I visit the same page few more time, gwan will directly give me the result without execute the function... As the function is to update the information about user activ...
You must use different urls every req. For example: ``` /?activity&secret=mq4s1Xsi&timestamp=19457278 ```
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed10 years ago.Improve this question I want to use telnet to send shell command or execute shell scripts on server automatica...
It's all about socket communication. You need to know how socket works. Then, implementTelnet protocolby yourself. If you don't want to implement your own telnet libraries. You might downloadputty sourceand see if you could leverage from it.
Just a small question: Can C++ use C header files in a program? This might be a weird question, basically I need to use the source code from other program (made in C language) in a C++ one. Is there any difference between both header files in general? Maybe if I change some libraries... I hope you can help me.
Yes, you can include C headers in C++ code. It's normal to add this: ``` #ifdef __cplusplus extern "C" { #endif // C header here #ifdef __cplusplus } #endif ``` so that the C++ compiler knows that function declarations etc. should be treated as C and not C++.
I dont know why we always declare like this ``` char* name="Srimanth" ``` instead of ``` char name[]={"Srimanth"} ``` I am new to this things. so please be more specific while you are giving me an answer.. thank you.
String literal is a special, simple, form of writing an array aggregate: you can write"hello"instead of{'h', 'e', 'l', 'l', 'o', '\0'}(note the terminating zero, which is added automatically). Note that an array declaration is not only possible, but is sometimes desirable: ``` char str[] = "hello"; str[0] = 'H'; // ...
I have the following code: ``` printf("+--------------+----------\n" " Postal number| Tele\n" "----------+-----------------+---------------\n" "%u | %u", number, tele); ``` but right now the output looks like: ``` +--------------+---------- Postal number | Tele ----------+-----...
There's no direct way to center text. You'll have to combine several elements: Figure out how many digits you have.Calculate how many spaces you want before and after the number.Print:printf("%*s%d%*s", spaces_before, "", num, spaces_after, ""); %*sconsumes two parameters - the first is the length, the second is the...
I created a textbox with following code. It is placed under WM_COMMAND of WNDPROC function. ``` htextbox=CreateWindowEx(WS_EX_CLIENTEDGE,TEXT("Edit"), TEXT("test"), WS_CHILD \ | WS_VISIBLE | WS_BORDER, 100, 20, 140, 20, hWnd, NULL, NULL, NULL); ``` I want to update the element "test" written...
I think you can simply do it like this: ``` SetWindowText(htextbox, TEXT("new text")); ```
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed10 years ago. hello I am learning basics of C programming language, recently i have studied aboutpost and pre increment/decrementoperators and also aboutlvalue and rvalue, the following pr...
Well, let's see what is happening in--x--. At first, post-decrement executes:--(x--).(x--) = 7. After that result of this operation is placed to the original structure:--7- doesn't make sense - thus you getlvalue requirederror
Is there any specific function or any way by which the number of lines in aGDBMfile can be counted?Otherwise, I want to retrieve all the lines in aGDBMfile at once(Iam able to retrieve the key value pairs usinggdbm_fetch()but only one at a time.
I got the solution to the above problem. Now I am able to retrieve all the key value pairs. Solution :here
I had a problem about gwan cache, currently I visit a page serve by gwan (write in C) , which will execute some functions during visit, however, when I visit the same page few more time, gwan will directly give me the result without execute the function... As the function is to update the information about user activ...
You must use different urls every req. For example: ``` /?activity&secret=mq4s1Xsi&timestamp=19457278 ```
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed10 years ago.Improve this question I want to use telnet to send shell command or execute shell scripts on server automatica...
It's all about socket communication. You need to know how socket works. Then, implementTelnet protocolby yourself. If you don't want to implement your own telnet libraries. You might downloadputty sourceand see if you could leverage from it.
char *p = "a";is valid but notint *p = 2;andchar *p = 'a';Why are they designed like that?
Anything wrritten inside" "is considered as string in C.So char *p = " a"says you are passing base address of string to char pointer.which is Valid. int *psayspis a pointer to integer sopcan hold a address to integer soint *p = 2is not valid. Similarlychar *pis pointer to character sopcan hold address of a characte...
Can anyone please tell me. I'm trying to understand a Pascal code in which there is one linewriteln(arr[i]:0:14); Can anyone please tell me the meaning of this in C ?
It's a format for real numbers: ``` writeln( foo:N:M ); ``` prints the value offooin a field width ofNand showsMdecimal places. So inCyou'd use: ``` printf( "%N.Mf\n", foo ); ``` IfNis is too small to hold the formatted value (given the size ofM), it will use the space it needs to print the number. In Pascal, you...
I have a pre-processor directive as such, ``` //#define SPEC_CONTROL // Is not defined, but can be if need be #define SPEC_A_CONTROL // Is defined #ifdef SPEC_CONTROL || SPEC_A_CONTROL ; // do something #else ; // do something else #endif ``` Is it correct syntax to use the||in the manner I did?
I can assure yout that at least ``` #if defined(SPEC_CONTROL) || defined(SPEC_A_CONTROL) ``` works on Windows and several UNIX platforms. Im not sure about ``` #ifdef SPEC_CONTROL || SPEC_A_CONTROL ```
Normally when I have a big for loop I put messages to inform me in which part of the process my program is, for example: ``` for(i = 0; i < large_n; i++) { if( i % (large_n)/1000 == 0) { printf("We are at %ld \n", i); } // Do some other stuff } ``` I was wondering if this hurts too much the perfor...
Maybe you can split the large loop in order to check the condition sometimes only, but I don't know if this will really save time, that depends more on your "other stuff". ``` int T = ...; // times to check the condition, make sure large_n % T == 0 for(int t = 0; t < T; ++t) { for(int i = large_n/T * t; i < large_n...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do...
There are several options which you may choose from. As perhttp://msdn.microsoft.com/en-us/library/bb677133.aspx Note: Java is not on this list and cannot be used for app development in Windows mobile.
``` int main(void){ char * strPtr="Hello World"; printf("\n%s", strPtr); *(strPtr+2)='Z'; printf("\n%s", strPtr); getch(); } ``` I want to change 2nd element of char array by ``` *(strPtr+2)='Z'; ``` Compiler does not give any errors but when I execute , code hangs computer. Where is...
Because when you declare something like ``` char * strPtr="Hello World"; ``` it's actually aconst char *so you can't modify it. You can change your code to ``` char * strPtr= strdup("Hello World"); //free it after ``` or ``` char strPtr[30] = {0}; strncpy(strPtr, "Hello World", 11); ``` and your code will be wo...
I have a function A that has achar *parameter. InA(), I usesizeofto calculate the size of buf , but I got 8 in i686 machine and 4 in armel machine. why is not it 128? The snippet is as below: ``` void A(char *p) { printf("sizeof p is %d\n", sizeof(p)); } int main(void) { char buf[128]; printf("sizeof b...
Inmain()function,bufis an array, sosizeof bufgives the size of this array:sizeof(char[128])(128 bytes). That's because an array is notconvertedto a pointer when used as operand ofsizeofoperator.InA()function,pis a pointer, sosizeof pgives the size of this pointer:sizeof(char *)(8 bytes on your implementation).
I want to read a file forever how can I go to the beginning of the fileHere is my code ``` FILE* inp_file=fopen("Input_file.bin","rb"); uint8* buffer; buffer=(uint8*)malloc(nSize); uint32 nSize =1000; while(1) { while(! feof (inp_file)) { memset (buffer,'0',nSize); fread (buf...
Take a look tofseekandSEEK_SET Also note that ``` uint8* buffer; buffer=(uint8*)malloc(nSize); uint32 nSize =1000; ``` should be ``` uint8* buffer; uint32 nSize =1000; buffer=(uint8*)malloc(nSize); ```
I need to split a char array into CSV's. Actually we can do the reverse of it usingstrtok()like: ``` #include <stdio.h> #include <string.h> int main () { char str[] ="This,a,sample,string."; char * pch; printf ("Splitting string \"%s\" into tokens:\n",str); pch = strtok (str,","); while (pch != NULL) { prin...
Just iterate over the string until you hit the end-of-string'\0'character. Or use the length of the data in the array (which may be smaller than the array size) and use a simpleforloop.
I am trying to understand scanset in C. I want to input string that consist of letter A-Z ,a-z and can have spaces between it. Example : if input is :ABCD abcd 123 then output should be :ABCD abcd. I tried to do this by :scanf("%[A-ZA-Z^\n]",c), wherecis char array but it doesn't read space. Please suggest a way...
You can't have the inversion (^) in the middle like that, it has to be the first character in the set, if used. You can of course just include a space in the set: ``` scanf("%[A-Za-z ]", c); ``` should work.
Is ``` *(ary[3]+8) ``` and ``` ary[3][8] ``` are the same ? If yes, please explain how ? ary[3] returns the address of first element or the value in ary[3][0] ? ary is a two dimensional array. Thanks in advance.
Yes a[i]is same as*(a+i) ary[i][j]is same as*( *(ary+i)+j))
``` char myArray[6]="Hello"; //declaring and initializing char array printf("\n%s", myArray); //prints Hello myArray="World"; //Compiler says"Error expression must a modifiable lvalue ``` Why can't I change myArray later? I did not declare it as const modifier.
When you writechar myArray[6]="Hello";you are allocating 6chars on the stack (including a null-terminator). Yes you can change individual elements; e.g. myArray[4] = '\0' will transform your string to "Hell" (as far as the C library string functions are concerned), but you can't redefine the array itself as that woul...
I am trying to show user a text file after an operation completed in a c program using winapi but I want the file to be opened using notepad (or the default text processor application). how do I do this (opening a text file using window's default application) using winapi?
ShellExecute()is what you are looking for, eg: ``` #include <shellapi.h> ShellExecute(NULL, NULL, "C:\\path\\to\\myfile.txt", NULL, NULL, SW_SHOWNORMAL); ```
i know that \x is hexadecimal representation of ASCII literal ``` printf("%c",'\x41'); // A printf("%c",'\X41'); // 1 ``` why? reference:http://c.comsci.us/etymology/literals.html(see most bottom table)
This is not standard, so results will vary. Given that\Xis not a valid control sequence, your particular compiler is choosing the last character in the single-quotes and using that. So, if you did:'\X12345'you would probably get5. There is nothing special about\X. If you take that out of your dodgey character lite...
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.Closed10 years ago.Improve this question I was wondering why there is sqrt() function in C/c++ as we can achieve the same us...
I ran a test for you to check the performance ofsqrt(x)andpow(x,0.5) 1. ``` for(int i=0;i<100000000;i++) pow(double(i),0.5); ``` 2. ``` for(int i=0;i<100000000;i++) sqrt(double(i)); ``` 1st one took around 20 seconds where as 2nd one took around 2 seconds on my computer. So performance is way better. As ...
When I read thePHP source code written in C, I can't find themain()method; could somebody help me?
Themain()functions in PHP are defined within the SAPI, as they are specific to the mode that PHP is being run in. For instance, for the command-line SAPI, it is defined insapi/cli/php_cli.c; for the CGI/FastCGI SAPI, it is defined insapi/cgi/cgi_main.c. Some other SAPIs, such as theapache2SAPI, do not define amain()f...
Where are the options forcurl_easy_setoptdefined? I'm trying to look for the integer values of CURLOPT_VERBOSE and some others, but these don't seem to be explicitly defined incurl.h
Line 792: ``` #ifdef CURL_ISOCPP #define CINIT(na,t,nu) CURLOPT_ ## na = CURLOPTTYPE_ ## t + nu ``` line 953: ``` CINIT(VERBOSE, LONG, 41), /* talk a lot */ ``` There it is.
Does multiple #define of the same string use the same constant string? Say I do the following in multiple places: ``` #define TEST @"test" ``` Compiler is smart enough to know it refers to the same constant string in the data section right?
Truly your question does not have much to do with what#definedoes, but rather about how string literals are treated by the compiler. The compiler inserts the string object into the program image, which is read-only and doesn't implement the retain count. This is an optimization so that the string doesn't need to be cr...
As a simple example, I want to allow this kind of usage in a python script assumingmycustom_CTypeis an instance of my definedPyTypeObjectin C: ``` print('foo' in mycustom_CType) ``` What slots and functions inPyTypeObject's struct does python need for this to work? I'm guessing possiblytp_iterandtp_iternextbut I can...
Thetp_as_sequence.sq_containsmember of the type is invoked for containment checking.
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.Closed10 years ago.Improve this question I'm trying to print in a file a string with a fixed size. Something like this: ``` #define SIZE 30 main()...
You should define your format string like the following: ``` fprintf(fp, "%*s", SIZE, s); // Right aligned string fprintf(fp, "%-*s", SIZE, s); // Left aligned string ``` From theprintfman page: The precisionInstead of a decimal digit string one may write"*"to specify that the precision is given in the next argume...
Is it safe to assume that assigning and accessing 32 bit integers on an ARM Cortex-A9 MPCore implementations are atomic operations and that the assigned value is synchronized with all cores? Will the C compiler guarantee that ``` uint32_t *p; *p = 4711; ``` and ``` uint32_t *p; return *p; ``` are translated to ato...
"Atomic" and "synchronized with all cores" are different requirements. All ARM cores in the market implement 32 bit operations to memory atomically (which is to say you can never see "part" of the word written without the rest).Notall of them are cache-coherent between cores, and the details (especially with the more...
I want to deal 52 cards numbered from 1 to 52. To share it into 4 groups of 13 cards and to separate them, I put "-" in the code below to make them appear nice. The other group starts with card numbers 14,27 and 40. I could not find a better way then 2 OR's in if statement. What I want to ask is if there is an easier ...
Use the modulo operator: ``` if ((cardNo - 1) % 13 == 0) ```
I am wondering if there is a difference between doing this ``` char ** str; str=(char **)malloc(sizeof(char*) * ARRAY_LEN); ``` and doing this : ``` str=(char*)malloc(sizeof(char)* ARRAY_LEN); for(i=0;i<ARRAY_LEN;i++) *(str+i)=(char*)malloc(sizeof(char)* ARRAY_LEN); ``` and doing this is the same too : ``` char s...
Yes, one is a pointer to a pointer tochar, and the other is a pointer tochar, there is a very big difference. between those. You can think of it as an array of strings in the first case, and a single string in the second. Of course, in the first case you have to somehow allocate memory for the actual strings in the "...
``` int main(void){ char * strPtr="Hello World"; printf("\n%s", strPtr); *(strPtr+2)='Z'; printf("\n%s", strPtr); getch(); } ``` I want to change 2nd element of char array by ``` *(strPtr+2)='Z'; ``` Compiler does not give any errors but when I execute , code hangs computer. Where is...
Because when you declare something like ``` char * strPtr="Hello World"; ``` it's actually aconst char *so you can't modify it. You can change your code to ``` char * strPtr= strdup("Hello World"); //free it after ``` or ``` char strPtr[30] = {0}; strncpy(strPtr, "Hello World", 11); ``` and your code will be wo...
I have a function A that has achar *parameter. InA(), I usesizeofto calculate the size of buf , but I got 8 in i686 machine and 4 in armel machine. why is not it 128? The snippet is as below: ``` void A(char *p) { printf("sizeof p is %d\n", sizeof(p)); } int main(void) { char buf[128]; printf("sizeof b...
Inmain()function,bufis an array, sosizeof bufgives the size of this array:sizeof(char[128])(128 bytes). That's because an array is notconvertedto a pointer when used as operand ofsizeofoperator.InA()function,pis a pointer, sosizeof pgives the size of this pointer:sizeof(char *)(8 bytes on your implementation).
I want to read a file forever how can I go to the beginning of the fileHere is my code ``` FILE* inp_file=fopen("Input_file.bin","rb"); uint8* buffer; buffer=(uint8*)malloc(nSize); uint32 nSize =1000; while(1) { while(! feof (inp_file)) { memset (buffer,'0',nSize); fread (buf...
Take a look tofseekandSEEK_SET Also note that ``` uint8* buffer; buffer=(uint8*)malloc(nSize); uint32 nSize =1000; ``` should be ``` uint8* buffer; uint32 nSize =1000; buffer=(uint8*)malloc(nSize); ```
I need to split a char array into CSV's. Actually we can do the reverse of it usingstrtok()like: ``` #include <stdio.h> #include <string.h> int main () { char str[] ="This,a,sample,string."; char * pch; printf ("Splitting string \"%s\" into tokens:\n",str); pch = strtok (str,","); while (pch != NULL) { prin...
Just iterate over the string until you hit the end-of-string'\0'character. Or use the length of the data in the array (which may be smaller than the array size) and use a simpleforloop.
I am trying to understand scanset in C. I want to input string that consist of letter A-Z ,a-z and can have spaces between it. Example : if input is :ABCD abcd 123 then output should be :ABCD abcd. I tried to do this by :scanf("%[A-ZA-Z^\n]",c), wherecis char array but it doesn't read space. Please suggest a way...
You can't have the inversion (^) in the middle like that, it has to be the first character in the set, if used. You can of course just include a space in the set: ``` scanf("%[A-Za-z ]", c); ``` should work.
Is ``` *(ary[3]+8) ``` and ``` ary[3][8] ``` are the same ? If yes, please explain how ? ary[3] returns the address of first element or the value in ary[3][0] ? ary is a two dimensional array. Thanks in advance.
Yes a[i]is same as*(a+i) ary[i][j]is same as*( *(ary+i)+j))
``` char myArray[6]="Hello"; //declaring and initializing char array printf("\n%s", myArray); //prints Hello myArray="World"; //Compiler says"Error expression must a modifiable lvalue ``` Why can't I change myArray later? I did not declare it as const modifier.
When you writechar myArray[6]="Hello";you are allocating 6chars on the stack (including a null-terminator). Yes you can change individual elements; e.g. myArray[4] = '\0' will transform your string to "Hell" (as far as the C library string functions are concerned), but you can't redefine the array itself as that woul...
I am trying to show user a text file after an operation completed in a c program using winapi but I want the file to be opened using notepad (or the default text processor application). how do I do this (opening a text file using window's default application) using winapi?
ShellExecute()is what you are looking for, eg: ``` #include <shellapi.h> ShellExecute(NULL, NULL, "C:\\path\\to\\myfile.txt", NULL, NULL, SW_SHOWNORMAL); ```
i know that \x is hexadecimal representation of ASCII literal ``` printf("%c",'\x41'); // A printf("%c",'\X41'); // 1 ``` why? reference:http://c.comsci.us/etymology/literals.html(see most bottom table)
This is not standard, so results will vary. Given that\Xis not a valid control sequence, your particular compiler is choosing the last character in the single-quotes and using that. So, if you did:'\X12345'you would probably get5. There is nothing special about\X. If you take that out of your dodgey character lite...
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.Closed10 years ago.Improve this question I was wondering why there is sqrt() function in C/c++ as we can achieve the same us...
I ran a test for you to check the performance ofsqrt(x)andpow(x,0.5) 1. ``` for(int i=0;i<100000000;i++) pow(double(i),0.5); ``` 2. ``` for(int i=0;i<100000000;i++) sqrt(double(i)); ``` 1st one took around 20 seconds where as 2nd one took around 2 seconds on my computer. So performance is way better. As ...
When I read thePHP source code written in C, I can't find themain()method; could somebody help me?
Themain()functions in PHP are defined within the SAPI, as they are specific to the mode that PHP is being run in. For instance, for the command-line SAPI, it is defined insapi/cli/php_cli.c; for the CGI/FastCGI SAPI, it is defined insapi/cgi/cgi_main.c. Some other SAPIs, such as theapache2SAPI, do not define amain()f...
I there any way to check that 32 bit netmask is valid or not using bitwise operator? I have to check from msb side that '1' are in continuous stream or not. eg 11111111.0.0.0 (255.0.0.0)is valid but 11111101.0.0.0 (253.0.0.0) is not.
First thing to do is to check for the netmask being non zero (a nasty edge case). Given this is ok, you need to take the bitwise inverse. ``` uint32_t y = ~x; ``` Then add one ``` uint32_t z = y + 1; ``` Then ifxwas a proper netmask, there will be at most 1 bit set in this. To test that, simply andzwithz - 1, whi...
Was there any site that compares the current C11 standard conformance/support between implementation/compilers? (gcc, clang, intel, open64, pelles)
To my knowledge there is no general site (this is a good time to start one :). However, most projects maintain their own list: http://clang.llvm.org/cxx_status.html(clang)http://clang.llvm.org/compatibility.html#c http://gcc.gnu.org/wiki/C11Status(gcc)
This question already has answers here:How do I concatenate const/literal strings in C?(17 answers)Closed8 years ago. I'm new to the C language and Loadrunner. How do I do a string concatenation in C. Pseudo code: ``` String second = "sec"; String fouth = "four"; System.out.println("First string" + second +"Third"...
If you are sure that target string can accommodate, you can usesnprintf, ``` #define SIZE 1024 char target[ SIZE ]; // .. .. snprintf( target, sizeof( target ), "%s%s%s", str1, str2, str3 ); ``` For your case, ``` snprintf( target, sizeof( target ), "%s%s%s%s", "First string", second, "Third", fourth ); ``` Of co...
For example if we are traversaling a rather big tree by following function, it is possible that we get stack overflow. ``` void inorder(node* n) { if(n == null) return; inorder(n->l); n->print(); inorder(n->r); } ``` How to add a condition or something into the function to prevent such overflow from happeni...
consider iteration over recursion , if that is really a concern. http://en.wikipedia.org/wiki/Tree_traversal see the psedo code there for iteration iterativeInorder iterativePreorder iterativePostorder Basdically use your own list as stack data structure in a while loop , You can effectively replace function recu...
This question already has answers here:C - What is this syntax about? <<(6 answers)Closed10 years ago. I am wondering to know What is the meaning of operator<<in ``` #define x (10 * (1<<12)); ```
It's thebitshift operator.<<isshift left,>>isshift right.1 << 12means shift the value (the int '1') 12 bits to the left. '1' is00000000 00000000 00000000 00000001in binary, if it's a 32 bit integer. To shift it left 12 places, changes it to:00000000 00000000 00010000 00000000 If you were to shift5 << 8, '5' is101in ...
I am not an iOS expert. I have a basic question, Is it possible to access/call any Objective C methods/properties from UI webview? In other words what would happen if i keep some objective C code in a HTML page and load it in UIwebview of an iOS hybrid app? Will the code execute?
No - the code will not execute. What you're describing is an "injection" and, if it were possible, could wreak havoc in an app. Something I've done in the past is create an app with a UIWebView container (somewhat like you're describing) then pass back a response that my code can programmatically look for and handle....
I there any way to check that 32 bit netmask is valid or not using bitwise operator? I have to check from msb side that '1' are in continuous stream or not. eg 11111111.0.0.0 (255.0.0.0)is valid but 11111101.0.0.0 (253.0.0.0) is not.
First thing to do is to check for the netmask being non zero (a nasty edge case). Given this is ok, you need to take the bitwise inverse. ``` uint32_t y = ~x; ``` Then add one ``` uint32_t z = y + 1; ``` Then ifxwas a proper netmask, there will be at most 1 bit set in this. To test that, simply andzwithz - 1, whi...
Was there any site that compares the current C11 standard conformance/support between implementation/compilers? (gcc, clang, intel, open64, pelles)
To my knowledge there is no general site (this is a good time to start one :). However, most projects maintain their own list: http://clang.llvm.org/cxx_status.html(clang)http://clang.llvm.org/compatibility.html#c http://gcc.gnu.org/wiki/C11Status(gcc)
This question already has answers here:How do I concatenate const/literal strings in C?(17 answers)Closed8 years ago. I'm new to the C language and Loadrunner. How do I do a string concatenation in C. Pseudo code: ``` String second = "sec"; String fouth = "four"; System.out.println("First string" + second +"Third"...
If you are sure that target string can accommodate, you can usesnprintf, ``` #define SIZE 1024 char target[ SIZE ]; // .. .. snprintf( target, sizeof( target ), "%s%s%s", str1, str2, str3 ); ``` For your case, ``` snprintf( target, sizeof( target ), "%s%s%s%s", "First string", second, "Third", fourth ); ``` Of co...
For example if we are traversaling a rather big tree by following function, it is possible that we get stack overflow. ``` void inorder(node* n) { if(n == null) return; inorder(n->l); n->print(); inorder(n->r); } ``` How to add a condition or something into the function to prevent such overflow from happeni...
consider iteration over recursion , if that is really a concern. http://en.wikipedia.org/wiki/Tree_traversal see the psedo code there for iteration iterativeInorder iterativePreorder iterativePostorder Basdically use your own list as stack data structure in a while loop , You can effectively replace function recu...
This question already has answers here:C - What is this syntax about? <<(6 answers)Closed10 years ago. I am wondering to know What is the meaning of operator<<in ``` #define x (10 * (1<<12)); ```
It's thebitshift operator.<<isshift left,>>isshift right.1 << 12means shift the value (the int '1') 12 bits to the left. '1' is00000000 00000000 00000000 00000001in binary, if it's a 32 bit integer. To shift it left 12 places, changes it to:00000000 00000000 00010000 00000000 If you were to shift5 << 8, '5' is101in ...
I am not an iOS expert. I have a basic question, Is it possible to access/call any Objective C methods/properties from UI webview? In other words what would happen if i keep some objective C code in a HTML page and load it in UIwebview of an iOS hybrid app? Will the code execute?
No - the code will not execute. What you're describing is an "injection" and, if it were possible, could wreak havoc in an app. Something I've done in the past is create an app with a UIWebView container (somewhat like you're describing) then pass back a response that my code can programmatically look for and handle....
I have changed Makefile of a project and now when I make it, it returns:- ERROR: "make[2]: *** No rule to make target ../libvmi/driver/.deps/xen.Po. Stop. " How does Makefile create.Pofiles and how can I disable creating it for a certain file like../libvmi/driver/.deps/xen.c?
.Pofiles are used as part of automake's dependency tracking. They are usually created byconfig.statusas empty files, which get overwritten by actual dependencies when the compiler is invoked. (automake's approach is to do dependency generation as a side-effect of compilation.) I've found that runningmake -k(-kis shor...
A program that I'm trying to decode includes the following line: ``` #define nn(sp) ((sp)->nn) ``` From the context (not shown), I'm pretty sure that 'sp' is a pointer to a struct which contains 'nn' as one of its variables. In the expression "((sp)->nn)", does the inner set of parentheses serve any conceivable p...
``` #define nn(sp) ((sp)->nn) ``` The inner parentheses are required. If you pass a pointer likep + 10or*ptonnmacro, you would get some troubles without the inner parentheses as->has higher precedence than+and unary*. The outer parentheses are not required here as the expression involves a postfix operation and no...
Inside main, i have the following procedure to get numbers from a file: ``` FILE *f = fopen("numbers.txt", "r"); if(f != NULL) { char line[BUFFER_SIZE]; while(fgets(line, sizeof(line), f) != NULL) { char *start = line; int field; int n; while(sscanf(start, "%d", &field, &n) == ...
``` sscanf(start, "%d", &field, &n) ``` You have too many arguments for your function call.
I have problem. Im compiling following c-file ``` #include <stdio.h> #include <GLUT/glut.h> int main() { return 0; } ``` commands: ``` clang -framework GLUT main.c clang -F/System/Library/Frameworks/GLUT.framework/ main.c clang -F/System/Library/Frameworks/GLUT.framework/GLUT main.c ``` and i get error: ``` fat...
Looks like you for some reason doesn't have GLUT framework on your machine. I have no errors compiling your example on my machine (10.8.4). Take a look atthis how-tofor some additional info EditDon't use custom compilers packages. Install Command Line Tools to use compiler in terminal or run it viaxcrun
This question already has answers here:What is the difference between exit and return?(5 answers)Closed8 years ago. Is there any difference betweenreturn 0andexit (0)when using in a function? If yes, When should I usereturn 0orexit (0)in a function?
returnexits from the function whileexitexits from the program. Inmainfunction executingreturn 0;statement or callingexit(0)function will call the registeredatexithandlers and will cause program termination.
Consider the following C code: ``` #include <stdio.h> int main(int argc, char* argv[]) { const long double ld = 0.12345678901234567890123456789012345L; printf("%lu %.36Lf\n", sizeof(ld), ld); return 0; } ``` Compiled withgcc 4.8.1underUbuntu x64 13.04, it prints: ``` 16 0.123456789012345678901321800735...
Thelong doubleformat in your C implementation uses an Intel format with a one-bit sign, a 15-bit exponent, and a 64-bit significand (ten bytes total). The compiler allocates 16 bytes for it, which is wasteful but useful for some things such as alignment. However, the 64 bits provide only log10(264) digits of significa...
I have two C projects which use Makefiles. One provides a library which I want to use in the other project. To be more specific, the structure is as follows ``` . ├── hiredis │   ├── Makefile │   ├── hiredis.h │   └── ... ├── qemu │   ├── Makefile │   ├── source_code.c │   └── ... ``` Inside the qemu project - in s...
Ifhiredisandqemuare always in the same tree at fixed/know position, I would use a-I../hiredisCPP flag. For flexibility you can parameterise the position ofhiredis. But I would only do this when really needed; it's so relaxing to keep things simple. BTW, using Makefiles without IDE are great: full control and insigh...
this is the code which is working fine... ``` int main() { char c[]={'\t','\n','\0'}; int i; char *p,*str; str=c; p=&c[1]; printf("%d\n%d\n",*p,*str); system("pause"); return 0; } ``` My problem is why is itstr=c;and notstr=&c;(which gives errors) and itsp=&c[1];and notp=c[1]?
When you make an assignment, both sides of the assignment need to betype compatible. In certain scenarios name of an array decays as an pointer to its first element. Socreturns pointer to a char, i.echar *while&cgives address of an array, which is clearly not of the typechar *(type ofstrischar*), the type mismatch gi...
From Microchip sample code ``` PR2 = 2083u; /* Timer2 Period, 19.2 kHz */ ``` How does2083ucorrespond to 19.2 kHz, which is ``` 1 / 19.2E03 = 52.083u ``` They don't correspond at all. Mistake by Microchip?
``` PR2 = 2083U ``` makes TIMER2 trigger every 2083 CPU cycles. Calculating ``` 52.083 us / 2083 = 25 ns 1 / 25 ns = 40 MHz ``` we can conclude that the processor is probably running atFCY = 40 MHzin the example. The letteruinPR2 = 2038u;does not mean microseconds; it is a C language syntax that makes the integer ...
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed10 years ago. When I type my code like given below : ``` int a=10,b,c,d,e; c= a++; d = ++a; e = ++a; printf("value of c=%d, d =%d, e=%d",c,d,e); ``` it gives me an output likec =10,d= 12...
DeliciousUndefined Behaviour, the order of evaluation of the operands of+(and many others) is left to the implementation. So it's not even always36for the second case.
The following code is that I wrote to test my understanding of usingfor-loopinC, and using assignment statement insidefor-loopin particular. But here I am getting unexpected output. Why does it do not assign0to the first 10 element of thearray?And why does it do not print thearrayat all if I declare the array asarray[...
``` ((i < 10) || (array[i] = 0)) ``` The||is lazy, as long asi < 10, the expression willshort circuitand the assignment will not even be evaluated. The obvious way to change the loop would be to to; ``` for (i = 0; i < 10; ++i) array[i] = 0; ``` ...which is more readable and does exactly what you're trying to...
Is it possible to form a two way link between structs? I tried to achieve it like this: ``` typedef struct { int foo; b *b; } a; typedef struct { int bar; a *a; } b; ``` But the struct a does not know what b is because it's declared afterwards.
Try this, ``` typedef struct a a; typedef struct b b; struct a { int foo; b *b; } ; struct b { int bar; a *a; } ; ```
This question already has answers here:Find the sum of all the multiples of 3 or 5 below 1000(17 answers)Closed10 years ago. I tried this program many times, but I can't write answer. ``` #include<stdio.h> int main() { long unsigned int i,sum=0; clrscr(); for(i=0;i<=1000;i++) { if((i%5==0)||(...
``` if((i%5==0)||(i%3==0)) { sum=sum+1; } ``` should be ``` if((i%5==0)||(i%3==0)) { sum=sum+i; } ```
Calling the functionsum(int [], arr_size)in the statement ``` total = sum((int []){1,2,3,4,5}, 5); ``` aCompound Literal(int []){1,2,3,4,5}is passed as argument. It is clear that the length of array is determined by numbers of elements in literal(which is of-course5here). Then what is the need of passing5as another ...
Your functionsumis identical tosum(int *, size_t); the square brackets are just syntactic sugar. No arrays are passed at any point, and indeed youcannotpass arrays as function arguments in C. Thus there is no size information left in the "array" part of the function parameters, and the size must be passed separately.
I trying to put some string in to name using _snwprintf(); for open a file with its name but unfortunately all what i get in name is only first character of a string here is a code: ``` # include<stdio.h> #define LN L"\\SystemRoot\\System32\\Log.txt" void main (void) { wchar_t name[1024]; _snwprintf(name...
Right, you're treating a Unicode string as ANSI. In a little-endian system, the first two bytes is "\" followed by zero, which terminates the string. You want to say ``` wprintf(L"%s", name); ``` If you step through in the debugger, you will see that 'name' contains what you expect.
This question already has answers here:Check if two integers have the same sign(6 answers)macro definition in javascript(6 answers)Closed9 years ago. The following macro is to determine if two numbers have the same sign, is for 2's complement number representation. ``` #define SAME_SIGNS( a, b ) (((long) ((unsigned...
``` (a < 0 === b < 0) ``` or ``` (a * b > 0) // If one of a or b is 0, can't tell. ``` or ``` (a < 0 && b < 0 || a > 0 && b > 0) ``` true -> same, else different
Is the following syntax correct for returning a pointer from a function? ``` bmpfile_t* bmp_create_from_file(const char *filename, bmpfile_t *bmp) { FILE *fp; fp = fopen(filename, "r"); bmp_get_header_from_file(fp, bmp); bmp_get_dib_from_file(fp, bmp); bmp_get_pixels_from_file(fp, bmp); fclos...
bmpalready has typebmpfile_t *, which is what you want to return. So justreturn bmp. Edit: What you are currently trying to return,&bmp, is the address of abmpfile_t *, and hence has typebmpfile_t **, a pointer to a pointer. Furthermore, as others have pointed out,&bmpwould be the address ofbmp, which is a local stac...
Would some please tell me why this code leads to such an error? ``` unsigned char buffer; fread(&buffer,1,1,image_ptr); printf("%s ",buffer); ``` The image is 8-bit grayscale. Thank you.
%sis the format specifier to print a string, butbufferis not a string. That causes undefined behaviour. You want%cor maybe%uor%xdepending on what you want as output.
I need to pass this data to a function, but can't figure out the correct syntax for the receiving function. Example code ``` NPOI_SCAN_HEADER *h; int iBline; int baselineId; for (iBline = 0; iBline < h->iNumBlines; iBline++) { baselineId = addBaseline(h->pBase[iBline]); } int addBaseline(BASELINE *b) { ......
AspBaseis aBASELINE *,pBase[iBline]is going to be aBASELINE. So to get aBASELINE *, you need to take its address: ``` baselineId=addBaseline(&(h->pBase[iBline])); ``` Or just add the offset: ``` baselineId=addBaseline(h->pBase + iBline); ```
I can use display list + glsl? something like using vbo + glsl. if this can be, you can write an example.
Well in terms of OpenGL-2, yes you can use GLSL shaders on geometry drawn through a display list that was compiled from immediate mode calls. The question is: Why would you want to do this? OpenGL-3 removed display lists (good riddance). So don't expect it to work for any GLSL version beyond 1.2x.x