question
stringlengths
24
425
answer
stringlengths
5
405
Say I have a pointer to a struct which has an array field called arr: p Isp->arr[i]equal to: (p->arr)[i](which is what I was going for) or p->(arr[i])(which is an error)
->operator has same precedence as[]operator.But it will be evaluated from left to right. So ``` p -> arr[i] ``` is equivalent to ``` (p -> arr)[i] ```
How do I create aarray containing multiple pointersin C? e.g.If you have a data-set of sizenwhich you want to split intotchunks. So if you want to access an element in the range0-(n/t), you would need to access the array index and go to the corresponding pointer index.
This will work forintdata ``` int *arr_of_ptr[t]; for(int i = 0; i < t; i++) arr_of_ptr[i] = malloc(sizeof(int) * n/t); ```
I want to make variable null in C in dev C. This code isn't work ``` char a = '5'; a = ''; ``` I don't know why this is not work. And I want to make characterabe empty. The error message is "[Error] empty character constant"
It depends what you mean by empty.. '\0' means the value 0 (NUL).
I want to make variable null in C in dev C. This code isn't work ``` char a = '5'; a = ''; ``` I don't know why this is not work. And I want to make characterabe empty. The error message is "[Error] empty character constant"
It depends what you mean by empty.. '\0' means the value 0 (NUL).
``` //function to copy string t to string s using pointers void strcpy(char *s,char *t) { while((*s++=*t++)!='\0'); return; } ``` i am confused how is the expression *s++==*t++ evaluated.I know associativity of increament operator is higher than assignment operator.
*s++=*t++ is basically ``` *s = *t; s++; t++; ```
``` //function to copy string t to string s using pointers void strcpy(char *s,char *t) { while((*s++=*t++)!='\0'); return; } ``` i am confused how is the expression *s++==*t++ evaluated.I know associativity of increament operator is higher than assignment operator.
*s++=*t++ is basically ``` *s = *t; s++; t++; ```
This may seem to be a dumb question but I don't really have a good understanding offork()other than knowing that this is about multi-threading. Child process is like a thread. If a task needs to be processed viafork(), how to correctly assign tasks to parent process and child process?
Check the return value offork. The child process will receive the value of0. The parent will receive the value of the process id of the child.
This may seem to be a dumb question but I don't really have a good understanding offork()other than knowing that this is about multi-threading. Child process is like a thread. If a task needs to be processed viafork(), how to correctly assign tasks to parent process and child process?
Check the return value offork. The child process will receive the value of0. The parent will receive the value of the process id of the child.
If I do ``` sum2=(((p/2)%m)*((p+1)%m))%m; sum2=(sum2 * (p%m))%m; ``` I get the right answer but if I do ``` sum2=((p%m)*(((p/2)%m)*((p+1)%m))%m)%m; ``` I get the wrong answer. What is the reason? All variables are of unsigned long long integer type and m<=10000000. PS:Question updated because of typo.
sum2=((p%m)*((((p/2)%m)*((p+1)%m))%m))%m;This should work for you.There was a problem with parentheses.
How would I go about making an enum into a string using a case such as enum {Ace,....King} face; to a case that would convert it to say "Ace" rather than a 0 or 1.
``` char const* faceToString(face f) { switch (f) { case Ace: return "Ace"; case Two: return "Two"; ... case King: return "King" } } ```
Every Ruby object is of typeVALUEin C. How do I print it in a readable way? Any other tips concerning debugging of Ruby C extensions are welcome.
You can callpon Ruby objects with the C functionrb_p. For example: ``` VALUE empty_array = rb_ary_new(); rb_p(empty_array); // prints out "[]" ```
In C, on any micro controller when we initialize a float variable to 0 ``` float var = 0.0f; ``` Is 'var' exactly equal to zero or does it depend on the min & max float resolution of the processor?
Happily, zero is actually zero no matter what: IEEE-754 (the usual standard for floats) sets aside the all-zeroes bit pattern as meaning identically zero.
It´s possible using Macros in ironPython? I have a dll with macros in C and I would like access it from IronPython. Any ideas? Thank you.
You can't access C macros from a DLL - they're handled by the C preprocessor, so they never reach the compiler and thus can't part of the DLL. You can access functions exported from the DLL in IronPython using the standard Pythonctypesmodule.
It´s possible using Macros in ironPython? I have a dll with macros in C and I would like access it from IronPython. Any ideas? Thank you.
You can't access C macros from a DLL - they're handled by the C preprocessor, so they never reach the compiler and thus can't part of the DLL. You can access functions exported from the DLL in IronPython using the standard Pythonctypesmodule.
I just wrote a code in c ``` #include <stdio.h> int main() { int a=0; option1: a++=5; option2: ++a=5; printf("%d\n",a); return 0; } ``` but it doesnt compiled with error ``` lvalue required as left operand of assignment ``` why its an error? thanks!
Because, like your compiler says,a++is not anlvalue, it's arvalue. You will find more information aboutlvalueandrvaluehere.
For example: ``` void func1(){ int i = 123; func2(&i); } void func2(int *a){ *a = 456; } ``` Whenfunc1callingfunc2, a pointer to local variable is passed tofunc2-- the pointer is pointed to the stack. Is this safe for the rules of C? Thanks.
The scope ofiisfunc1and it outlives the call tofunc2. So it is perfectly safe.
``` void cleanup( command_t* p_cmd ){ } ``` Basically i need to find a way to free up space that has beenmallocin C. I am new to c and working on a basic shell.
1) free (p_cmd); 2) p_cmd = NULL; E.g.: ``` void cleanup( command_t* p_cmd ) { if( p_cmd ) { free (p_cmd); p_cmd = NULL; } } ```
``` void cleanup( command_t* p_cmd ){ } ``` Basically i need to find a way to free up space that has beenmallocin C. I am new to c and working on a basic shell.
1) free (p_cmd); 2) p_cmd = NULL; E.g.: ``` void cleanup( command_t* p_cmd ) { if( p_cmd ) { free (p_cmd); p_cmd = NULL; } } ```
I've been told it is possible, but it seems every time I try I continuously get an error saying "No symbol tables have been loaded." Have I been tricked, or is it in fact possible?
Assuming the address of the variable is0x7fffffffe51cand its type isint, here is how you do it in GDB: ``` (gdb) set {int}0x7fffffffe51c = 11 (gdb) p *0x7fffffffe51c $5 = 11 ``` To find local variables, refer to "How to read local variables with gdb?".
I have to get which exe use my dll at the moment. How to accomplish it from dll?
DLLs are Windows shared object files, I assume you use C with the windows SDK and windows.h is available for you to include. In that case, use the GetModuleFileName() function. Use 0 as the module handle and you'll get the executable name. ``` wchar_t buffer[MAX_PATH]; GetModuleFileName(0, buffer, MAX_PATH); ```
I've been told it is possible, but it seems every time I try I continuously get an error saying "No symbol tables have been loaded." Have I been tricked, or is it in fact possible?
Assuming the address of the variable is0x7fffffffe51cand its type isint, here is how you do it in GDB: ``` (gdb) set {int}0x7fffffffe51c = 11 (gdb) p *0x7fffffffe51c $5 = 11 ``` To find local variables, refer to "How to read local variables with gdb?".
I have to get which exe use my dll at the moment. How to accomplish it from dll?
DLLs are Windows shared object files, I assume you use C with the windows SDK and windows.h is available for you to include. In that case, use the GetModuleFileName() function. Use 0 as the module handle and you'll get the executable name. ``` wchar_t buffer[MAX_PATH]; GetModuleFileName(0, buffer, MAX_PATH); ```
I have to get which exe use my dll at the moment. How to accomplish it from dll?
DLLs are Windows shared object files, I assume you use C with the windows SDK and windows.h is available for you to include. In that case, use the GetModuleFileName() function. Use 0 as the module handle and you'll get the executable name. ``` wchar_t buffer[MAX_PATH]; GetModuleFileName(0, buffer, MAX_PATH); ```
What is this use of the colon called? The following code is taken from the bookLearn Core Audio. ``` int main(int argc, const char * argv[]) { //... cleanup: AudioQueueDispose(queue, true); AudioFileClose(player.playbackFile); return 0; } ```
That's a label. It's used along with agotostatement to control the flow of your program. goto and Labeled Statements (C)
i was studying EOF character in c and came across a program : ``` #include <stdio.h> main() { int c= 0; while((c = getchar())!=EOF) putchar(c); } ``` its all good it is giving proper o/p but how do i come out of the loop by entering a EOF character which i entered and it did nothing.
To stimulateEOFinstdin, If you are on windows or DOS press CTRL+ZOr if you are running linux or some other OS, press CTRL+D
I have my structure set up like this ``` struct judges { char surname[20]; int id; struct judges *wsk; } ``` How can I get random number from given IDs? Like for example, I add 3 judges with IDs 3, 7, and 253, is there a way to get random number only from these ones?
Pick a random item from an array of these structures and read its ID.
i was studying EOF character in c and came across a program : ``` #include <stdio.h> main() { int c= 0; while((c = getchar())!=EOF) putchar(c); } ``` its all good it is giving proper o/p but how do i come out of the loop by entering a EOF character which i entered and it did nothing.
To stimulateEOFinstdin, If you are on windows or DOS press CTRL+ZOr if you are running linux or some other OS, press CTRL+D
I have a very small amount of code: ``` int test = strcmp("Websecurity", "easily"); printf("%d\n", test); ``` The result is -1. Why? Clearly 'W' is greater than 'e'?
Capital letters come before lowercase letters in ASCII, and so'W' < 'e'.
When reading through some example codes for DMAs from Xilinx, I came across this piece of code: ``` value = (value + 1) & 0xFF ``` where value is an uint8_t. What is the point of the& 0xFF? Why not simply writevalue = value + 1?
My guess is that this code was intended to work correctly even ifvalueisnota 1-byte (8-bit) type. The bitmask0xFFmakes sure that only the last byte of the value is kept.
When reading through some example codes for DMAs from Xilinx, I came across this piece of code: ``` value = (value + 1) & 0xFF ``` where value is an uint8_t. What is the point of the& 0xFF? Why not simply writevalue = value + 1?
My guess is that this code was intended to work correctly even ifvalueisnota 1-byte (8-bit) type. The bitmask0xFFmakes sure that only the last byte of the value is kept.
I was debugging something since last two days and it seems on my linux m/c accept is returning me a socket ID of zero. ``` fd = accept(unix_domain_socket, (struct sockaddr *) &new_connection, &new_conn_length); ``` I see that fd is returning 0 -- Is this valid? Is 0 a valid socket fd number?
Yes. -1 means that it failed, but 0 is valid. Usually file descriptor zero is occupied by the standard input, though.
I have a project that be make all in terminal, in C and i am using ccpcheck file by file but i would like to used for check all files how a um project . I try used command with parameters : cppcheck --enable=all *.c ,in the folder but show me less errors than check file by file. There are better method for to do this ? if you can help me
try: ``` cppcheck --enable=all . ``` that scans all source files in current folder and in all subfolders
How would one go about using the pointer parameter if given a function like this: ``` int testFunction(int *){ } ``` I understand that a pointer is being passed as the parameter, but how do I use that pointer given that there is no variable name after the pointer?
You should name the argument. See this link for atutorial
Given a size of buffer, I need to count how many new lines I have read using fread(). How to do that?
Count the number of newline characters (usually\n) in the buffer.
For library functions I useman <function>to find which header file I need to include. But for types likesize_t,uint32_t, etc. themanapproach doesn't work. Is there any command to find the header file required?
Another possible solution is to search locally using grep. Something likegrep -r 'typedef\s.*\suint32_t;' /usr/includeshould work for you.
I want to print an error string with variables. ``` printf("Hi, %s", name); perror-something("Error no: %d", number); ``` How do I add variables toperror?
You can use the combination of strerror and the fprintf. Consider, ``` fprintf(stderr,"%s:Error NO:%d\n",strerror(errno),number); ```
I want to print an error string with variables. ``` printf("Hi, %s", name); perror-something("Error no: %d", number); ``` How do I add variables toperror?
You can use the combination of strerror and the fprintf. Consider, ``` fprintf(stderr,"%s:Error NO:%d\n",strerror(errno),number); ```
The following statements in C: ``` iONE >>= iShift; iONE &= 0xffefffff; iONE |= (((((long)(*temp & 0x7f) - 65) << 2) + iShift + 1023) << 20) | (iTWO & 0x80000000); ``` Is there something likeshr=,And=andOr=in Delphi. Is there more appropriate way than literal porting, especially the third statement.
Those are basically two operations combined.x >>= ymeansx = x >> y.The same applies for&=and|=.And for the Delphi part:And,Or, andRight Shift.
How structs in C are saved in the memory? Why sometimes the struct length in the memory is bigger than expected?
That's calleddata structure alignment. Although not a perfect duplicate, you can find a good explanation of this in C atStructure padding and packing
``` short i = 1; fwrite(&i, sizeof(i), 1, file); fwrite(&i, sizeof(i), 1, file); ``` Is that proper? I want to write the sameitwice.
There's nothing wrong with it; just remember to check the return value.
While readinf MuPDF comes across the source code line ``` x = !x; ``` Want to know what does the above code do? While compilation is also gives error as ``` assuming signed overflow does not occur when simplifying condition to constant [-Werror=strict-overflow ] ```
!xwill evaluate to either0or1, depending on the value ofx. Ifxis0, it evaluates to1.Otherwise, it evaluates to0.
How structs in C are saved in the memory? Why sometimes the struct length in the memory is bigger than expected?
That's calleddata structure alignment. Although not a perfect duplicate, you can find a good explanation of this in C atStructure padding and packing
I'm writing a C program and am exceeding the recursion limit via a segmentation fault. Is there any way to increase the program's recursion limit (perhaps via increasing the stack size), either via an option to GCC or via a command-line option? The program is running on Ubunutu.
You can change the stack size withulimiton Linux, for example: ``` ulimit -s unlimited ``` On Windows with Visual Studio, use/Foption.
If you are reading lines from a terminal in canonical mode, is there any way to tell the difference between a line terminated with EOL (Enter) and EOF (Ctrl-D)? My understanding is that both will return the number of bytes read from read().
For EOL on an empty line, the byte count will be 1, for the newline. For EOF on an empty line, the byte count will be 0, for 'there was no more data'.
If you are reading lines from a terminal in canonical mode, is there any way to tell the difference between a line terminated with EOL (Enter) and EOF (Ctrl-D)? My understanding is that both will return the number of bytes read from read().
For EOL on an empty line, the byte count will be 1, for the newline. For EOF on an empty line, the byte count will be 0, for 'there was no more data'.
Inthe tutorialfor erl_driver there seems to be no indication to where does the firstErlDrvPortobject comes from. Say I want to wrap libusb-1.0 to use it from erlang. There is no place in the API described byErlDrvEntryfor any index methods. How does one find a port to open?
Normally you obtain the first port using theerlang:open_port/2function, usage of which is shown in the code example in section 6.2 ofthe tutorialyou linked to in your question.
``` #include<stdio.h> main() { int c; c=getchar(); while(c!=EOF) { putchar(c); c=getchar(); } } ``` Why this code is resulting in an infinite loop. It is from D.Ritchie's book.
It results in an infinite loop becauseEOFis not a character that can be entered via keyboard. Take a look at this:EOF in Windows command prompt doesn't terminate input stream
In C, suppose I have an unsigned char A which can be either 0 or 1. I would like to find a bitwise logical operator that will convert A to !A. Note: I am using this code on a GPU, where bitwise operators are very cheap compared to logical operators. i.e. XOR is much cheaper than !
If by 'not' you mean send 1 to 0 and 0 to 1. you can use the XOR operator^to do that. If character is called c, you can writec = c ^ 1;.
I came across a problem where _dl_resolve_conflicts was crashing. After a bit of search found it linked error while resolving pre-linked elfs. Can anyone throw some insight.
If you know in advance that some combination of object files will be referenced by a program, then pre-linking will fix up any references between that set of object files. The linker will still need to fix up references between your program and the object files.
As the title, is it possible to initialize a pointer in a struct to point to the first element of an array that is also in the same struct? ``` struct foo { int barr[12]; int* barr_itt; }; struct foo f = {{0}, /*.?.*/} ```
Yes, use the name of the variable ``` struct foo f = {{0}, f.barr} ; ```
I would like to increase the maximum pipe size in linux. I am not talking about F_SETPIPE_SZ... but it seems there is 1MB limit to the pipe size(depends on the linux version I guess) Can anyone let me know how I can increase the max limit?
Changing the value in /proc/sys/fs/pipe-max-size, seems to do the trick :)... Thanks Joachim for your pointer in the right direction. My current linux has the max value as 1048576
Im using semaphore.h, what is happening if 5 child processes waiting onsem_waitwhile another child process unlocking the semaphoresem_post? Are they all going to be unlocked?
No, only one will be unblocked. RTFM. sem_wait sem_post If many processes are block, then one will be chosen to be unblocked, which one is up to OS. Scheduler will choose one.
How can I print an array without changing line? I have this array. I want to print its element in one single line, for example(a b c d). ``` char word[20][20]; for (j = 0; j < 10; j++) { puts(word[j]); } ```
putsplacees a\nafter writingchararray to standard output. Useprintf("%s", word[j])instead.
I'm trying to create my own data type of string, could anyone tell me what I'm doing wrong with typedef and initialization. ``` #include<stdio.h> #include<conio.h> typedef char string[10]; int main(){ string myName; myName = "Tayyab"; printf("This is %s", myName); getch(); } ```
You cannot assign to an array but you can initialize it: ``` string myName = "Tayyab"; ```
In C++ if you want to input a string and store it in a char array from index 1 you can do something like this: ``` ifstream f("data.in"); char a[100]; f.get(a+1,90); ``` Is there any way you can do this in C (like using fscanf)? Doing this: ``` fscanf(f,"%s",&a+1); ``` or this: ``` fscanf(f,"%s",&(a+1)); ``` doesn't work.
Yes there is, this way ``` fscanf(f,"%90s",a+1); ```
We have an array:int p[100].Whyp[i]is equivalent to*(p+i)and not*(p+i*sizeof(int))?
Why p[i] is equivalent to*(p+i)and not*(p+i*sizeof(int))? Because*(p+i)is also the same as*((int *) ((char *) p + i * sizeof (int))). When you add an integerito a pointer, the pointer is moveditimes the size of the pointed object.
We have an array:int p[100].Whyp[i]is equivalent to*(p+i)and not*(p+i*sizeof(int))?
Why p[i] is equivalent to*(p+i)and not*(p+i*sizeof(int))? Because*(p+i)is also the same as*((int *) ((char *) p + i * sizeof (int))). When you add an integerito a pointer, the pointer is moveditimes the size of the pointed object.
``` #include <stdio.h> int main() { char string[]="Programming Language"; printf(string); printf("\n%s",string); return 0; } ``` Output Programming LanguageProgramming Language Why is the output same?
Whenprintfparses the format string it prints the characters that are not format specifiers as they are. So when it parses"Programming Language"it just echoes each character.
Which are variable by " Uint "? is that there are " Uint8 ", " Uint16 ", etc ... But what are they ? Now I have some time using C ++ but I have never needed to use these variables and cause me curious. Thanks in advance.
uintis not a standard type. On some systemuintistypedefed as ``` typedef unsigned int uint ; ```
Is there a way to make getopt() or getopt_long() recognise double character option? example:./a.out -my argumentwhere my is single command.
You can usegetopt_long_only, which will try to process options as long ones even if there is only one-sign before them. This function is GNU extension, as well asgetopt_long.
I'm trying to change the ECN mark in the tcp header of a specific packet in NS-2 but could not find the way. Is there anyone who can give me a hand? Thanks a lot!
I found it in ns2.35/tcp/tcp-full.cc , line 874. Below is the code that marks ECN(or we can say ECE here). ``` if (ecn_ && ect_ && recent_ce_ ) { // This is needed here for the ACK in a SYN, SYN/ACK, ACK // sequence. pflags |= TH_ECE; } ```
Is there a way to make getopt() or getopt_long() recognise double character option? example:./a.out -my argumentwhere my is single command.
You can usegetopt_long_only, which will try to process options as long ones even if there is only one-sign before them. This function is GNU extension, as well asgetopt_long.
I'm trying to change the ECN mark in the tcp header of a specific packet in NS-2 but could not find the way. Is there anyone who can give me a hand? Thanks a lot!
I found it in ns2.35/tcp/tcp-full.cc , line 874. Below is the code that marks ECN(or we can say ECE here). ``` if (ecn_ && ect_ && recent_ce_ ) { // This is needed here for the ACK in a SYN, SYN/ACK, ACK // sequence. pflags |= TH_ECE; } ```
While generating c/c++ symbol table , when adding a new variable or a function name with its values to symbol table what is the key of that entry? name of the variable or address of the variable? Then how it detect multiple declaraions for that variable according to the symbol table?
The key is the name, of course. The linker never looks for address. Duplicated symbols are symbols with external linkage and the same name, so it is easy to check.
I want to know how can I do something like this in a C program. ``` if wget -q www.someurl.com; then echo OK; else echo Not there; fi ```
From the parent dofork().Inside the child created by 1. doexec*().From the parent or a signal handler listening toSIGCHLDdowait(&status).Finally useWEXITSTATUS(status)to get the equivalent tor=$?from your script.
While generating c/c++ symbol table , when adding a new variable or a function name with its values to symbol table what is the key of that entry? name of the variable or address of the variable? Then how it detect multiple declaraions for that variable according to the symbol table?
The key is the name, of course. The linker never looks for address. Duplicated symbols are symbols with external linkage and the same name, so it is easy to check.
I use thecodeblock. when the code is: ``` printf("%.1f", 1); ``` The program can run,and the output is0.0. I want to know why. `
Change it to: ``` printf("%.1f", 1.0); ``` fconversion specifier requires an argument of typedoublebut you are passing anintvalue (1is of typeint). Passing an argument of the wrong type toprintfinvokes undefined behavior.
I have one thread calling recvfrom() and another thread calling setsockopt() to add/leave multicast membership. Is that thread safe or both functions need to be called from the same thread?
These are both system calls, not library functions, so it is safe to call them from different threads. Whether a join/leave will affect a concurrentrecvfrom()that has already started is a moot question.
Is it fine to use sizeof operator with "snprintf" ? for example ``` char cstring[20]; snprintf(cstring,sizeof(cstring),"%s","somestring......"); ```
Yes, it's fine, the specific case you posted is good except that you don't check the return value, so you won't know if the string was truncated.
I'm working on a micro controller with a serial terminal and I want to be able to backspace characters, I'm already handling it in the input buffer, but I don't know what to send through serial to delete it from the terminal emulator, sending \b only moves the cursor back. ¿Anyone knows how to handle this in VT100?
FromHans Passant'scomment: Use "\b \b" instead. –
I'm working on a micro controller with a serial terminal and I want to be able to backspace characters, I'm already handling it in the input buffer, but I don't know what to send through serial to delete it from the terminal emulator, sending \b only moves the cursor back. ¿Anyone knows how to handle this in VT100?
FromHans Passant'scomment: Use "\b \b" instead. –
Is there a function that prints the graphical representation of a control character in C? For example "NULL" for 0, "DEL" for 127 and so on. thanks
There is no standard function for this, but you can easily create your own array/string mapping them. Or you could simply add a constant to map them into the unicode range for pictorial representations of the ASCII control characters.
After compiling a project USING AMILIE SDK RTX4140_... by RTX how to deploy the hex file in the RTX dev kit[Board]. dev kit device imagehttp://www.rtx.dk/RTX41xx_Development_Kit-4020.aspx
we can use the RTX41xx_Platform_Firmware_Update_Pack to deploy hex file.
After compiling a project USING AMILIE SDK RTX4140_... by RTX how to deploy the hex file in the RTX dev kit[Board]. dev kit device imagehttp://www.rtx.dk/RTX41xx_Development_Kit-4020.aspx
we can use the RTX41xx_Platform_Firmware_Update_Pack to deploy hex file.
I came across this for loop what it is this use for ``` if(__builtin_popcount(mask) % 2 == K % 2) // Do somethings ``` What the__builtin_popcountfunction do ?
Have you tried googling for it?Here'sthe first hit and the answer: — Built-in Function: int __builtin_popcount (unsigned int x)Returns the number of 1-bits in x.
I came across this for loop what it is this use for ``` if(__builtin_popcount(mask) % 2 == K % 2) // Do somethings ``` What the__builtin_popcountfunction do ?
Have you tried googling for it?Here'sthe first hit and the answer: — Built-in Function: int __builtin_popcount (unsigned int x)Returns the number of 1-bits in x.
I came across this for loop what it is this use for ``` if(__builtin_popcount(mask) % 2 == K % 2) // Do somethings ``` What the__builtin_popcountfunction do ?
Have you tried googling for it?Here'sthe first hit and the answer: — Built-in Function: int __builtin_popcount (unsigned int x)Returns the number of 1-bits in x.
I have a ios application which has some C files. I would like it to printed in the console. I would like to log messages and print the value of an unsigned int inside the C file in the console. NSLog and printf doesn't work, is there a way to do this ? Or is there any work around ?
This works for OS X apps. It might work for iOS also. ``` #include <syslog.h> syslog(LOG_WARNING, "Log me to console"); ```
I'm checking a code written a long time ago. I don't know what's the meaning of~symbol before the hexadecimal number. It's like: ``` a = b & ~0xff; ``` Other parts of the code are like below, without the~symbol: ``` a = (b & 0xff00) >> 8; ```
The~operator is the bitwise NOT, it inverts the bits of a binary number.
I have a small problem. I have numbers from 00000001 to 99999999, and they have to be divided into 000 00001 and 999 99999, respectively, and put them in different variables. Who knows elegant solution for this?
Use division to get the first part and modulus to get the second part: ``` void splitter(int number) { printf("First part: %i", number / 100000); printf("Second part: %i", number % 100000); } ```
Very basic question (I am a total noob in C...) I have a piece of code written: ``` if(!_a[_item[i]] || _b[_item[i]]) ``` Does this mean the next line should be run if: item[i] isnot present in a or in b or does it mean it should be run if: item[i] isnot present in aoris present in b? Thanks
It meansitem[i]is not present inaor is present inb
I'm writing a program in C using Code::Blocks 13.12 on Windows 8 (the C compiler is mingw32-gcc). I would like to use the "getline" function but it seems to be missing from the stdio.h. Is there any way to get it except for writing own implementation?
getlineis a POSIX function, and Windows isn't POSIX, so it doesn't have some POSIX C functions available. You'll need to roll your own. Or use one thathas already been written.
I was wondering if there is a shorthand way to initialise a 2D or 3D array in C similar to the following syntax: ``` int array[1024] = {[0 ... 1023] = 5}; ```
The initialization you use isn't standard C, it's aGCC extension (Designated Initializers). To initialize a 3d array, use: ``` int array[10][10][10] = {[0 ... 9] [0 ... 9] [0 ... 9] = 42}; ``` Demo.
I can't understand what the following code is doing ons: ``` if(!s--) ``` sis anint
Actually, it's misleading. You are testing issis different from 0 (withif (!s)). And then, afterward, whatever the result is, you're decreasing it. So, it's two different operations. It could be written this way : ``` if (!s) { s--; //... } else { s--; } ```
I was wondering if there is a shorthand way to initialise a 2D or 3D array in C similar to the following syntax: ``` int array[1024] = {[0 ... 1023] = 5}; ```
The initialization you use isn't standard C, it's aGCC extension (Designated Initializers). To initialize a 3d array, use: ``` int array[10][10][10] = {[0 ... 9] [0 ... 9] [0 ... 9] = 42}; ``` Demo.
I can't understand what the following code is doing ons: ``` if(!s--) ``` sis anint
Actually, it's misleading. You are testing issis different from 0 (withif (!s)). And then, afterward, whatever the result is, you're decreasing it. So, it's two different operations. It could be written this way : ``` if (!s) { s--; //... } else { s--; } ```
I upgraded to Yosemite, and now all my compilers (from the command line—gcc and icc) are giving me errors like: cannot open source file “ctype.h" Does anyone know how to fix this? Do I need to reinstall the compilers?
OK, not sure what’s going on here, but after updating to Xcode 6.1.1 and installing the associated command line tools, icc seems like it can now find the system headers. Now having a separate issue with gcc, will post separately…
When I execute the following code on Linux, the output is 32. Why is that so? ``` #include <stdio.h> #define m 10+2 int main() { int i; i = m * m; printf("%d", i); return 0; } ```
Macro expansion doesn't heed the surrounding syntax, soi=m*mgets expanded intoi=10+2*10+2, rather thani=(10+2)*(10+2). This why one should always parenthesize macro definitions and arguments: ``` #define m (10+2) ```
I upgraded to Yosemite, and now all my compilers (from the command line—gcc and icc) are giving me errors like: cannot open source file “ctype.h" Does anyone know how to fix this? Do I need to reinstall the compilers?
OK, not sure what’s going on here, but after updating to Xcode 6.1.1 and installing the associated command line tools, icc seems like it can now find the system headers. Now having a separate issue with gcc, will post separately…
``` unsigned char x=0; //int num is some random integer x=num; ``` How to get 2 least significant bytes?
Since you want the two least significant bytes, you will need two unsigned chars to hold the two bytes since unsigned char is just a byte in length. ``` unsigned char x, y; x = 0x00FF & num; // Get the first least significant byte. y = (0xFF00 & num) >> 8; // Gets the second least significant byte and store it in the char. ```
``` unsigned char x=0; //int num is some random integer x=num; ``` How to get 2 least significant bytes?
Since you want the two least significant bytes, you will need two unsigned chars to hold the two bytes since unsigned char is just a byte in length. ``` unsigned char x, y; x = 0x00FF & num; // Get the first least significant byte. y = (0xFF00 & num) >> 8; // Gets the second least significant byte and store it in the char. ```
Say I have these binary numbers: 0011100000000and ``` 0000111000000 ``` How would I go about checking to see if these binary numbers have a 1 in the same bit?
Yes, as punned by Martin, you want AND. (0011100000000 & 0000111000000) will result in 0000100000000 Also read up on OR (|) and XOR (^)
Considering the following: ``` #define SIZE 5 /* ... */ int oxen[SIZE] = {5,3,2,8}; int yaks[SIZE]; yaks[SIZE] = oxen [SIZE]; /* -->Out of range */ ``` Can someone explain why its out of range?
Arrays indices in C start at 0, so youroxenandyaksarrays range from0toSIZE-1. You're outside the allowed boundaries, as the compiler rightly warns you about.
The C system() call runs a program and forwards both stdout and stderr of the command that is run to the stdout and stderr streams of the calling program. Is it possible to redirect stdout from the command inside the system() call to the stderr stream of the calling program?
Just append1>&2to the command executed in your system call: Example: ``` system("ls 1>&2"); ``` will executelsand redirect stdout (1) to stderr (2).
Kindly help me with this error: error: storage class specified for 'interrupt_save_disabled'#define TX_INTERRUPT_SAVE_AREA register unsigned int interrupt_save_disabled; This is a header file in which it is used: ``` #if defined (WIN32) || defined (LINUX) #define register #endif TX_INTERRUPT_SAVE_AREA ```
You can't haveregisteron a global variable. Remove the specifier.
Kindly help me with this error: error: storage class specified for 'interrupt_save_disabled'#define TX_INTERRUPT_SAVE_AREA register unsigned int interrupt_save_disabled; This is a header file in which it is used: ``` #if defined (WIN32) || defined (LINUX) #define register #endif TX_INTERRUPT_SAVE_AREA ```
You can't haveregisteron a global variable. Remove the specifier.
I found in the doc the function :gtk_entry_set_input_purpose()to set the input-method of a gtkentry, but when using it, gcc didn't recognize it, it gives me this error ``` implicit declaration of function ‘gtk_entry_set_input_purpose’ [-Wimplicit-function-declaration] undefined reference to `gtk_entry_set_input_purpose' ``` where is the problem?
i think it was a linking problem , compiled successfully with windows after linking all libs ,
I have managed to configure, compile, and install some C source code into a Linux machine. Now I know that my library (saymylib.so) is available at/usr/local/bin I would like to write my C program with a main in it, that will access one of the methods inmylib.sothat returns a struct defined in there. Can somebody help me with this?
Something like this should give you the result: ``` gcc -o prog prog.o -L/usr/local/bin -mylib ```
I am trying to use C API to connect my C code to my SQL. I was wondering if anyone has any good beginner resources so I can get up to speed. All I am trying to do is just store data in tables I made in SQL. If it helps I am using MySQL on my Mac. Thank you!
You can find a good MySQL tutorial here:MySQL C API programming tutorial Here is the official documentation: 20.6.6 C API Function Overview20.6.3 Example C API Client Programs
``` static void fubar(int a) { void (*b) (int) = fubar; // <--- static int c; } ``` http://cdecl.org/says syntax error. My guess is that b is a pointer to a function returning int. Is this correct?
There has to be some return type, ``` void (*b) (int) = fubar; ``` or ``` int (*b) (int) = fubar; ``` Then itbwould be, pointer to function which returnvoid/intand takesintas parameter.