question
stringlengths
25
894
answer
stringlengths
4
863
I was wondering if there are any compilers that support a considerable amount of the new C11 standard. Looking for features like Generic Selection etc. Any suggestions?
Pelles C version 7.00 (Release Candidate is available now) http://www.smorgasbordet.com/pellesc/
Say I have this function: ``` int epic(int); ``` I know of these naming conventions, are these right? Do other very common ones exist? ``` long epicl (long); long long epicll (long long); unsigned int epicu (unsigned int); unsigned long epicul (unsigned long); unsigned long long epicull (u...
Sometimes, if the return type differs from the argument type(s), a prefix is used to indicate this. Consider for example the following (from C99): ``` double round(double x); float roundf(float x); long double roundl(long double x); long int lround(double x); long int lroundf(float x); long int lroundl(long double x...
As far as I know about data types in C/C++, while declaring a variable, we need to declare its data type, which tells the compiler to reserve the number of bytes in the memory accordingly. But in the case of pointers, we know that their size is constant (eg. 2 bytes in "Turbo Compiler"), irrespective of the data type...
The data type is needed whendereferencing the pointerso it knows how much data it should read. For example dereferencing acharpointer should read the next byte from the address it is pointing to while anintpointer should read 2 bytes.
I have a program that creates semaphore. But when i try to use SETALL, i get the error in errno as Numerical result out of range ``` if((temp_semid = semget(IPC_PRIVATE, 250, 0666 | IPC_CREAT)) != -1) { semun arg; ushort array[100]; memset(array,0, 100); arg.array = array; if(semctl(temp_semid, 0, SET...
This worked. ``` if((temp_semid = semget(IPC_PRIVATE, 250, 0666 | IPC_CREAT)) != -1) { semun arg; ushort array[100] = { 0 }; arg.array = array; if(semctl(temp_semid, 0, SETALL, arg) == -1){ std::cout << " failed to setall semaphore" << std::endl; std::cout << strerror(errno) << std::endl; brea...
I know I can read off /proc/[id]/maps but I'm not sure if the first entry is always the .text section.I would have to parse /proc/[id]/maps, is there an api I could call to get the data? edit- I see pmap just reads that same file. No worries. I'll just read off the first two integers.
Solved as per above. (these are extra characters to get past the padding.)
I have a question, if I wish to delete a node from linked list and I do this : Assume: Head points to first node. ``` deleteFirstNode(struct node * head) { struct node* temp=head;//this line temp->next=head->next->next; temp->data=head->next->data; free(head); head=temp; } ``` 1) will this delete ...
i would pass a double pointer and do something on these lines ``` deleteFirstNode(struct node ** head) { struct node* temp= *head; *head = temp->next; free(temp); } ```
I am trying to send the ping pkt. by writting a kernel module. when i checked whats being sent through tcpdump i saw somthing but it was not an icmp header.so decided to check whats in the headers transport_header and network_header(member of skb).how could i use printk command to do it(or any other).please see the fo...
This would be quite ugly, but readable: ``` unsigned int *p = skb->transport_header; for (i=0;i<sizeof(the header you want)/sizeof(int);i++) { printk("%08x", ntohl(p_i[i])); } printk("\n"); ```
I want to write a simple program that takes a moderately sized wav file (60 seconds or so) and cuts it into 1 second length segments of the same format (1.wav,2.wav,... etc) ... Is there a simple C++ or java library that could do this? I don't want to have to manipulate header information
Shell script wrapped around theffmpegcommand line utility. Also,sox. http://sox.sourceforge.net/
Does it actually read character by character or does it read some bytes into the kernel buffer and return to the user- character by character? Is it the same withfgets? Let me say I use glibc and a gcc compiler.
Almost right. A typical modern implementation that does have a user/kernel separation stores the bytesin a user buffer, not in a kernel buffer. Thus many calls tofgetcactually trigger few true system calls.
I am working with a standard library with many files. I would like to know where an often-used typedef struct is defined. I have its name, but that's it. Is there a way to "programmatically" tell where a givenstructis defined among a lot of files?
You didn't list an OS or an IDE but in Linux I have always usedgrep. I have yet to find an IDE that is good at tracking down typedefs especially since some are wrapped in macros.
I am using Scons to build my C project. I have an external linker file specified toldusing the-Xlinkerflag. My problem is that whenever I change my linker script pointed at by-Xlinker, Scons does not take the change into account: ``` scons: done reading SConscript files. scons: Building targets ... scons: `.' is up t...
``` env = Environment() env['LINKFLAGS']+=' -T linkerscript.lds ' Depends(program, 'linkerscript.lds') ``` Reference Also for explicit dependencies,check here
As a learning technique, i'm suppose to make my own copy of the following string function in ``` char * mystrcpy(char *a, char *b); // string copy. destroys a but not b. // identical to strcpy in <string.h> // running time O(mystrlen(b)) ``` I've come with this ``` char * mystrcpy(char *a, char *b){ a = b; return ...
accessing a specific char [in indexi] in string is done usinga[i], just like an array. [remember that in C, a string is actually an array ofchars]. You should iterate the strings until you "see" a'\0'char - which indicate the end of string. Yes, comparing to chars withoperator<is comparing them by their ascii value ...
I have lots and lots of C preprocessor#definestatements, which make my C programming much easier. However, when debugging with GDB, the preprocessor "labels" are not accounted for in the symbols list. Is there are way to have GDB recognise the#defined labels?
You can try compiling with g3, as describedhere. ``` gcc -gdwarf-2 -g3 ``` We pass the -gdwarf-2 and -g3 flags to ensure the compiler includes information about preprocessor macros in the debugging information. Or you can try-ggdb.
I am trying to make two .exe files in c where first one store some data in memory and save data´s pointer to .txt. and second one read pointer from .txt and display them. first one:fw = fopen("pointer.txt", "w");fprintf(fw, "%p", &data);fclose(fw); second one:fr = fopen("pointer.txt", "r");fscanf(fr, "%p", &pointer)...
Processes don't operate on actual memory, but virtual memory allocated to them by the system. So0x01111fromP1and0x01111fromP2don't point to the same sector of your RAM. Ergo, no, you need to use IPC I guess.
I'm trying to build a simple c application using gcc on aix ``` gcc -I. -c hello.c -o hello.o gcc -o helloWorld hello.o -L helloHelper.so -ldl ``` I get the following errors ``` ld 0711-317 ERROR: Undefined symbol: .PrintHello ``` PrintHello is a method in the library helloHelper. I can build the application in w...
The option-Lis for indicating directories where to search for libraries. To link a dynamic library directly, just put it in the linker command: ``` gcc -o helloWorld hello.o helloHelper.so -ldl ``` Other option would be to use-lhelloHelperbut then the library should be calledlibhelloHelper.so.
This program below moves the last (junior) and the penultimate bytes variable i type int. I'm trying to understand why the programmer wrote this ``` i = (i & LEADING_TWO_BYTES_MASK) | ((i & PENULTIMATE_BYTE_MASK) >> 8) | ((i & LAST_BYTE_MASK) << 8); ``` Can anyone explain to me in plain English whats going on in th...
Since you asked for plain english: He swaps the first and second bytes of an integer.
I was using the following code which actually gets me the contents in the registers (eax, ebx, ecx) whenever a open system call is called. Now after a lot of struggle I understood what the values signify from thisQuestion.ebx contains the pointer to filename. But when I try to access it I was getting a segmentation fa...
Every process has its own address space. An address obtained from another process will not be valid in yours. One way to read memory in the other process would be tousePTRACE_PEEKDATA. On Linux, another way would be to open/proc/<pid>/mem, seek to the address, and read from it like a file.
I've recently started playing around with ncurses. As far as I understand, C doesn't support passing by reference. However, there are some functions that seem to exhibit such a behavior: callinggetmaxyx(stdscr, maxRow, maxCol);assigns the the number of rows and number of columns tomaxRowandmaxColrespectively.getyxse...
This is not a direct function call, but a macro, take a lookhere: All of these interfaces are macros. A "&" is not necessary before the variables y and x. For example: ``` #define getmaxyx(w, y, x) (y) = getmaxy(w), (x) = getmaxx(w) ```
I wonder, why such function as:-memset-memmov-memchr-memcpy Exist in string.h header file, but not in stdlib.h file, where there are other standard memory functions as dynamic memory allocation: malloc, calloc, realloc, free. Maybe it would be better to unite them in one header? What do you think about it? I don't u...
Because actuallystring.his defined as a standard header that declares functions that treat array of characters and not only strings. Functions likememcpyandmemsettake arguments that are treated as pointers to the first element of an object of type array of characters. (C99, 7.21.1p1) The header < string.h > declares ...
I am new in C programming Here i want to detect USB is inserted or not in Linux I want to detect this things on my embedded linux device. which have customized linux. So i want to detect the block of USB where i have to mount this block. likesda,sdb or sdc. I want to o this thing in C programming for linux. Here i ...
Set up a hotplug event handler: You will get a hotplug block event when a block device appears or goes away, which you can use to mount/umount and run your handler scripts and apps.
I am learning C and attempting a crude implementation of a linked list in C. Long story short I have a struct containing only a void pointer(element) and another pointer to the next node.(code to follow) My question is, when passing the head node and some other node into a new function, is there any way to ensure th...
No -- you generally want to avoid a design like this, but if you really can't avoid it, you typically need to put a enum in the node to tell you the type of data it contains.
I recently did an assignment using bit masking and shifting to manipulate a 4 byte int. I got to wondering if it was possible to set a char pointer to the start of the int variable and then step through the int as if it was a 1 byte char by using the char pointer. Is there a way to do this or something similar? I t...
Of course you can, this code shows the behavior: ``` #include <stdio.h> int main() { int value = 1234567; char *pt = (char*) &value; printf("first char: %p, second char: %p\n", pt, pt+1); } ``` This outputs: ``` first char: 0x7fff5fbff448, second char: 0x7fff5fbff449 ``` As you can see difference is just 1...
In the process of porting a C project from Linux to Windows Have installed MinGW Have compiled my shared library using a Makefile This produceslibExample.so Now I'm trying to link this shared library to a test harness so I can see if everything is working as expected In the harness Makefile I specify the location...
You need to fix the make file so shared libraries are generated with a.dllextension. If I had to guess, I'd say that while renaming the generated file is enough to make the linker happy, the loader still expects the.soextension because that's the name that was compiled in...
I was thinking how to get the absolute value of an integer without usingifstatement norabs(). At first I was using shift bits left (<<), trying to get negative sign out of the range, then shift bits right back to where it be, but unfortunately it doesn't work for me. Please let me know why it isn't working and other a...
FromBit Twiddling Hacks: ``` int v; // we want to find the absolute value of v unsigned int r; // the result goes here int const mask = v >> sizeof(int) * CHAR_BIT - 1; r = (v + mask) ^ mask; ```
In C, when you escape a character, other than the built-in special characters, it's ASCII code remains unchanged: \+ is the same as +. I'm writing a regular expressions' engine and wonder how one could distinguish \+ and + for example.
The usual solution is that the regex engine expects to see\+, so if the regex is coming from a string literal, then the programmer will have to write\\+. Oddly enough, this approach is even used in some languages that have built-in/standard regex support, socouldoffer special regex syntax. In theory, an alternative a...
I create table in SQLite without checking every time whether it exists. ``` sqlite3_stmt* create_stmt = NULL; if (sqlite3_prepare_v2(db, "CREATE TABLE mytable (sif INTEGER PRIMARY KEY, name VARCHAR, description VARCHAR);", -1, &create_stmt, NULL) == SQLITE_OK) { sqlite3_step(create_stmt); sqlite3_finalize(cre...
I'm not sure if you are still looking for an answer but if the table already exists thensqlite3_finalizereturns non zero (not SQLITE_OK) value.
I want to run the following code, but its not working: ``` int main () { execlp("ssh user@192.168.170.155", "ssh user@192.168.170.155", NULL); return 0; } ``` But if I replace ssh with any other command(say ls) its working fine. Thanks, Yuvi
You can't pass it multiple commands and be done with it. You also can't pass it commands and arguments in the same string. The best you can do: ``` execlp("ssh", "ssh", "user@192.168.170.155", NULL); ```
Generally we say that a float has precision of 6 digits after the decimal point. But if we store a large number of the order of 10^30 we won't get 6 digits after the decimal point. So is it correct to say that floats have a precision of 6 digits after the decimal point?
"6 digits after the decimal point" is nonesnse, and your example is a good demonstration of this. Thisis an exact specification of thefloatdata type. The precision of thefloatis24bits. There are 23 bits denoting the fraction after the binary point, plus there's also an "implicit leading bit", according to the online...
I tried to run this code: ``` #define ROW_CNT 8; #define COLUMN_CNT 24; #define FIRST_COLUMN 2; unsigned int volume[ROW_CNT][COLUMN_CNT][ROW_CNT]; ``` but I get the following errors: expected identifier or '(' before ']' token Why is that?
Take off the semicolons on your #defines. The #define directives are handled by thepreprocessing stageof compilation, which is all about text substitution. So, whenever the preprocessor performs text substitution, your program becomes ``` unsigned int volume[8;][24;][2;]; ``` which isn't valid C.
This question already has answers here:What is the behavior of integer division?(6 answers)Closed2 years ago. This behaves as wanted: ``` double t = r[1][0] * .5; ``` But this doesn't: ``` double t = ((1/2)*r[1][0]); ``` ris a 2-D Vector. Just thought of a possibility. Is it because (1/2) is considered anintand(...
Is it because (1/2) is considered an int and (1/2) == 0? Yes, both of those literals are of typeint, therefore the result will be of typeint, and that result is 0. Instead, make one of those literals afloatordoubleand you'll end up with the floating point result of0.5, ie: double t = ((1.0/2)*r[1][0]); Because1.0i...
I am using OpenCV 2.3.1 to develop Delaunay triangulation code on NetBeans 6.9 on Ubuntu 11.04. I have included all of the libraries that I could find in the link list but get the following error messages when I try to link. ``` build/Debug/GNU-Linux-x86/_ext/1942517469/TwoDTriangulation.o: In function `cvCreateSubd...
Those symbols are defined inlibopencv_imgproc.so, which means that if you were compiling the app through cmd-line withg++you would have to add the-lopencv_imgprocflag.
I am using Qt/C++ for long time now, I am supposed to develop an application the will run on mobile phones (MIDP 1.0, and MIDP 2.0). I don't program with J2ME and learning it will consume so much time. So I was wondering is there any way that makes me develop such applications using Qt or at worst case any C/C++ frame...
No, MIDP is a Java standard only, there is no way to run native C/C++ code on top of that virtual machine. The phones run the Java virtual machine for a reason; bugs aside the programs run in a sandbox and cannot cause security problems with the phone itself.
I'm trying to change this to print to the terminal screen instead of a file. So I'm trying to print to stdout. ``` char buf; int s, n; char filename[LINELEN]; char *recfile = "recfile.txt"; FILE *finp; fflush(NULL); while(buf != EOF) { fflush(finp); if (read(s, &buf, 1) < 0) { printf("\...
Shouldn't it befputc(buf, stdout);?
How does a program/application know that the data in a memory address is of a certain data type. For instance, suppose there isint a;and suppose variableais stored in address0x100. Where is the the information stored that says it is of typeint?
In languages like C the information is always "stored"in the way you interpret the data. Some niceness is added by the compiler which to some extent understands the types of your variables and tries to prevent operations which don't make sense. For instance, suppose you have the bits:0xFFFFFFFF. If you interpret them...
I am attempting to identify the ether type of a packet that I am receiving. The ether type ID is 608 and has no corresponding definition in Ethertype.h(libpcap 1.2.1). The majority of the packets received have an either type of 8 which again has no corresponding definition in Ethertype.h. Does anyone have any ideas of...
What is the return value ofpcap_datalink()on thepcap_ton which you're capturing? If it's notDLT_EN10MB(which has the value 1), your packets aren't Ethernet packets, and you shouldn't parse them as Ethernet packets. If it isDLT_EN10MB, then is that hex 608 or decimal 608? If it's decimal 608, it's a length field rat...
How do I get the size of a pointer in C usingsizeof? I want to malloc some memory to store a pointer (not the value being pointed to).
Given an arbitrary type (I've chosencharhere, but that is for sake of concrete example): ``` char *p; ``` You can use either of these expressions: ``` sizeof(p) sizeof(char *) ``` Leading to amalloc()call such as: ``` char **ppc = malloc(sizeof(char *)); char **ppc = malloc(sizeof(p)); char **ppc = malloc(sizeof(...
I'm not friendly with C# programming, so I don't know what can be replaced for below C# function(method?) in C language: ``` public string ToAscii(byte[] data) { System.Text.ASCIIEncoding decoder = new System.Text.ASCIIEncoding(); return decoder.GetString(data, 0, data.Length); } ``` Does anyone have a good ...
Usestrcpy: ``` char *newString = malloc(strlen(input) + 1); strcpy(newString, input); // don't forget to free 'newString'! ```
Inthis example codeit deals with framebuffers before setting up the context. I've read the man pages of the functions, but I still don't understand exactly what's going on. So my question is,what exactly is a framebuffer in GLX and how significant is configuring it?
A framebuffer is an area of memory that holds a displayable image. You need one when creating an OpenGL context so that OpenGL has a place to store the image it renders.
The<cstdint>(<stdint.h>) header defines several integral types and their names follow this pattern:intN_t, whereNis the number of bits, not bytes. Given that a byte is not strictly defined as being 8 bits in length, why aren't these types defined as, for example,int1_tinstead ofint8_t? Wouldn't that be more appropria...
On machines that don't have exactly those sizes the types are not defined. That is, if you machine doesn't have an 8-bit byte thenint8_twould not be available. You would still however have the least versions available, such asint_least16_t. The reason one suspects is that if you want a precise size you usually want a...
struct hostent (under both windows and unices) that's used for example with gethostbyname() et al. keeps the dotted addresses using a pointer to signedchar. What's the benefit of this when it's known in advance that addresses can and mostly do contain numbers > 127, and that they're ultimately represented unsigned? I...
Probably it is just historical baggage - just like the functions using it. Nowadays, it is recommended to usegetaddrinfo()andgetnameinfo()in order to be protocol-independent.gethostbyname()is obsolete, just like its counterpartgethostbyaddr().
I'd like to automatically start a C application when i power up my Ubuntu. I know that i can use app start from system menu in order to choose what application has to start after the login. The problem is that i do not need to use the X server, so i do not want to log in my desktop. I just want to autostart my C pr...
Yeah, that document looks good. It talks about what I was going to say, use init scripts.
In most of the explanations in the book the author insists of using **list passing instead of *list, however as per my understanding I feel there is nothing wrong in *list. Please someone explain me in detail if i am wrong. For example, to delete head of a linked list, the author says the below code is wrong. ``` ...
In your first example: ``` head = temp; ``` Does nothing outside the function, it only sets the local variableheadtotempinside the function. Whatever variable the caller passed in will remain unchanged. The author is correct, you need to use pointers or (better) references (if you're using C++).
I need to check if a C string is a valid integer. I tried both ``` int num=atoi(str); ``` and ``` int res=sscanf(str, "%d", &num); ``` But sending the string"8 -9 10"in both of the lines returned simply 8, without indicating the invalidity of this string. Can anyone suggest an alternative?
Have a look at strtol(), it can tell you about invalid parts of the string by pointer return. And beware of enthusiastic example code.. see the man page for comprehensive error-handling.
I am trying to understand the following code: ``` #include<stdio.h> #include<stdlib.h> #include<sys/io.h> #define baseport 0x378 int main() { int b; if(ioperm(baseport,3,1)) { perror("ioperm"); exit(1); } outb(0,baseport); usleep(1000000); printf("\n the status: %x,\n",i...
The result of doing inb(0x378) is hardware-dependent. Some chips return the value you have written previously with outb, and some other chips just return garbage. In any case, it isnotthe port to read bytes from a potentially connected device.
While solving exercises from the K&R C book, I stumbled upon the exercise 2.1. At first I got asUINT_MAXas-1, but then I used the%uplaceholder, but now its giving me the same number asULONG_MAX. In the book in Appendix B, they say thatUINT_MAXshould be65535andULONG_MAXshould be4294967295, but when running the exerci...
First of all, the right way to print anunsigned longis not%ubut%lu. Second, the standard saysthe minimumvalue ofUINT_MAXis 65535. It can be (and usually is) larger. 5.2.4.2.1 Sizes of integer typesTheir implementation-defined values shall beequal or greater in magnitude(absolute value) to those shown, with the same ...
I was trying the following example of I/O ports fromhere. ``` #include<stdio.h> #include<unistd.h> #include<asm/io.h> #define baseport 0x378 int main() { if(ioperm(baseport,3,1)) { perror("ioperm"); exit(1); } outb(0,baseport); exit(0); } ``` I'm usinggcc -o port ports.c(the above code) which was...
This might well depend on your implementation,iopermis not standard. On Linux with a modernglibc, you'll need<sys/io.h>, and your code is also missing<stdlib.h>(forexit).
Before Linux kernel 2.6, super_operations (include/linux/fs.h) have bothread_inodeandwrite_inodefunctions. But newer kernel does not haveread_inodeany more, then when and how does the VFS read in inode information from specific file system implementation? What is the new course of inode related processing in VFS? Do ...
The answer is practically in thecommit log. Edit: See the immediate parent commits of that one for how the practical transformation looks in the file systems.
I'd like to automatically start a C application when i power up my Ubuntu. I know that i can use app start from system menu in order to choose what application has to start after the login. The problem is that i do not need to use the X server, so i do not want to log in my desktop. I just want to autostart my C pr...
Yeah, that document looks good. It talks about what I was going to say, use init scripts.
In most of the explanations in the book the author insists of using **list passing instead of *list, however as per my understanding I feel there is nothing wrong in *list. Please someone explain me in detail if i am wrong. For example, to delete head of a linked list, the author says the below code is wrong. ``` ...
In your first example: ``` head = temp; ``` Does nothing outside the function, it only sets the local variableheadtotempinside the function. Whatever variable the caller passed in will remain unchanged. The author is correct, you need to use pointers or (better) references (if you're using C++).
I need to check if a C string is a valid integer. I tried both ``` int num=atoi(str); ``` and ``` int res=sscanf(str, "%d", &num); ``` But sending the string"8 -9 10"in both of the lines returned simply 8, without indicating the invalidity of this string. Can anyone suggest an alternative?
Have a look at strtol(), it can tell you about invalid parts of the string by pointer return. And beware of enthusiastic example code.. see the man page for comprehensive error-handling.
I am trying to understand the following code: ``` #include<stdio.h> #include<stdlib.h> #include<sys/io.h> #define baseport 0x378 int main() { int b; if(ioperm(baseport,3,1)) { perror("ioperm"); exit(1); } outb(0,baseport); usleep(1000000); printf("\n the status: %x,\n",i...
The result of doing inb(0x378) is hardware-dependent. Some chips return the value you have written previously with outb, and some other chips just return garbage. In any case, it isnotthe port to read bytes from a potentially connected device.
While solving exercises from the K&R C book, I stumbled upon the exercise 2.1. At first I got asUINT_MAXas-1, but then I used the%uplaceholder, but now its giving me the same number asULONG_MAX. In the book in Appendix B, they say thatUINT_MAXshould be65535andULONG_MAXshould be4294967295, but when running the exerci...
First of all, the right way to print anunsigned longis not%ubut%lu. Second, the standard saysthe minimumvalue ofUINT_MAXis 65535. It can be (and usually is) larger. 5.2.4.2.1 Sizes of integer typesTheir implementation-defined values shall beequal or greater in magnitude(absolute value) to those shown, with the same ...
I was trying the following example of I/O ports fromhere. ``` #include<stdio.h> #include<unistd.h> #include<asm/io.h> #define baseport 0x378 int main() { if(ioperm(baseport,3,1)) { perror("ioperm"); exit(1); } outb(0,baseport); exit(0); } ``` I'm usinggcc -o port ports.c(the above code) which was...
This might well depend on your implementation,iopermis not standard. On Linux with a modernglibc, you'll need<sys/io.h>, and your code is also missing<stdlib.h>(forexit).
I need to check if a C string is a valid integer. I tried both ``` int num=atoi(str); ``` and ``` int res=sscanf(str, "%d", &num); ``` But sending the string"8 -9 10"in both of the lines returned simply 8, without indicating the invalidity of this string. Can anyone suggest an alternative?
Have a look at strtol(), it can tell you about invalid parts of the string by pointer return. And beware of enthusiastic example code.. see the man page for comprehensive error-handling.
I am trying to understand the following code: ``` #include<stdio.h> #include<stdlib.h> #include<sys/io.h> #define baseport 0x378 int main() { int b; if(ioperm(baseport,3,1)) { perror("ioperm"); exit(1); } outb(0,baseport); usleep(1000000); printf("\n the status: %x,\n",i...
The result of doing inb(0x378) is hardware-dependent. Some chips return the value you have written previously with outb, and some other chips just return garbage. In any case, it isnotthe port to read bytes from a potentially connected device.
While solving exercises from the K&R C book, I stumbled upon the exercise 2.1. At first I got asUINT_MAXas-1, but then I used the%uplaceholder, but now its giving me the same number asULONG_MAX. In the book in Appendix B, they say thatUINT_MAXshould be65535andULONG_MAXshould be4294967295, but when running the exerci...
First of all, the right way to print anunsigned longis not%ubut%lu. Second, the standard saysthe minimumvalue ofUINT_MAXis 65535. It can be (and usually is) larger. 5.2.4.2.1 Sizes of integer typesTheir implementation-defined values shall beequal or greater in magnitude(absolute value) to those shown, with the same ...
I was trying the following example of I/O ports fromhere. ``` #include<stdio.h> #include<unistd.h> #include<asm/io.h> #define baseport 0x378 int main() { if(ioperm(baseport,3,1)) { perror("ioperm"); exit(1); } outb(0,baseport); exit(0); } ``` I'm usinggcc -o port ports.c(the above code) which was...
This might well depend on your implementation,iopermis not standard. On Linux with a modernglibc, you'll need<sys/io.h>, and your code is also missing<stdlib.h>(forexit).
Before Linux kernel 2.6, super_operations (include/linux/fs.h) have bothread_inodeandwrite_inodefunctions. But newer kernel does not haveread_inodeany more, then when and how does the VFS read in inode information from specific file system implementation? What is the new course of inode related processing in VFS? Do ...
The answer is practically in thecommit log. Edit: See the immediate parent commits of that one for how the practical transformation looks in the file systems.
I am a beginner trying to write a C program in Visual Studio 2010. I have created a new project and have copied my code into the empty .cpp page that appeared. The build is unsuccessful and when I try to debug, I get the following error message: Unable to start program "c:\users---\visual studio 2010\Projects\Homewor...
The build must be successful in order to create the exe file so you can start your application and debug. Check for compile errors and solve them before building your project.
Two of the libraries I am including share the same definition of a macro in each of their respective .h files. ``` #define MAX <some value> //first definition of MAX in a file #define MAX <some other value> //second definition of MAX in a *different* file ``` and in compilation I get ``` .../httpd.h:43:1: war...
The only bad part about this situation is dependencies onMAXin your code, if any. If you don't have any, adding an#undef MAXbetween the two#includes is probably the fastest fix. If youdohave dependencies onMAXyou might need to figure out which one (I guess it's the last :-) and do something appropriate.
This question already has answers here:Closed11 years ago. Possible Duplicate:invalid conversion fromvoid*&#39; tochar*' when using malloc? I'm trying to allocate a matrix dinamically on the memmory using pointers, but I keep receiving the error messages: |122|error: invalid conversion from 'void*' to 'int**'||124|...
You are compiling your program with a C++ compiler. You have two choices: Don't do that. Use a C compiler.Cast the return value frommalloc().
Is there a way to generate a number number between two limits without using the sran and rand functionWhat it is that i have a while (1) (super loop) which calls a function every 10 ms seconds. in the function a for loop is used to create a delay, but, everytime the function is access the delay should be different but...
Try bellow hope this will answer your question. ``` #include<stdio.h> #include <stdlib.h> int main() { int iMaxRand =100,ii=0 ; while( ii < 100) { printf("Random Number is:%d\n", rand() % iMaxRand); ii++; } printf("\n"); } ```
I am trying to make 32 bit library on a 64 bit Ubuntu box. I am creating .so as follows gcc - shared -Wl,-soname,libtest.so *.o I am getting /usr/bin/ld : relocation R_X86_64_PC32 against symbol "set_bright' cann't be used when making shared object;recompile with -fPIC. Already I tried compiling with -fPIC. It did...
I believe you get that error if there you're calling a function declared as hidden, e.g. ``` int set_hidden(void) __attribute__((visibility("hidden"))); ``` and it's not defined in the same shared object. To solve it you have to also link the object file containing the definition ofset_hidden, or remove the call to...
``` int main() { int my array[3][3] = 10, 23, 42, 1, 654, 0, 40652, 22, 0 }; printf("%d\n", my_array[3][3]); return 0; } ``` I am not able to get the array to print.. Any ideas why? I am a beginning programmer so any words of advice are appreciated.
What you are doing is printing the value in the array at spot [3][3], which is invalid for a 3by3 array, you need to loop over all the spots and print them. ``` for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { printf("%d ", array[i][j]); } printf("\n"); } ``` This will print it in the fo...
A typical C program would be compiled, assembled, linked and loaded. I know that Java works with the JVM and produces byte code. Would it be possible to connect both "object files" using the linker? For example, a C program and a C++ program can be used together by playing with the linker and linking both object files...
You can't directly link compiled C code with compiled Java code. You can call compiled C or C++ code from Java usingJava Native Interface (JNI): The Java Native Interface (JNI) enables the integration of code written in the Java programming language with code written in other languages such as C and C++. It allows p...
In windows programming, how can we find out the number of partitions and the name of each partition on the hard drive?
You can use theDeviceIoControlfunction with theIOCTL_DISK_GET_DRIVE_LAYOUT_EXcontol code to get a list of partitions.
I have a C app that generates very large binary files, each about 30GB. After writing each file, computing an MD5 checksum of it takes a while, (a couple of minutes per file, approximately.) How would I go about computing the MD5 checksum of the file as it is being written to disk? I figure by doing this I would at l...
This is certainly possible to do. Essentially, you initialise an MD5 calculation before you start writing. Then, whenever you write some data to disk, also pass that to the MD5 update function. After writing all the data, you call a final MD5 function to compute the final digest. If you don't have any MD5 code handy,...
I am a beginner trying to write a C program in Visual Studio 2010. I have created a new project and have copied my code into the empty .cpp page that appeared. The build is unsuccessful and when I try to debug, I get the following error message: Unable to start program "c:\users---\visual studio 2010\Projects\Homewor...
The build must be successful in order to create the exe file so you can start your application and debug. Check for compile errors and solve them before building your project.
Two of the libraries I am including share the same definition of a macro in each of their respective .h files. ``` #define MAX <some value> //first definition of MAX in a file #define MAX <some other value> //second definition of MAX in a *different* file ``` and in compilation I get ``` .../httpd.h:43:1: war...
The only bad part about this situation is dependencies onMAXin your code, if any. If you don't have any, adding an#undef MAXbetween the two#includes is probably the fastest fix. If youdohave dependencies onMAXyou might need to figure out which one (I guess it's the last :-) and do something appropriate.
This question already has answers here:Closed11 years ago. Possible Duplicate:invalid conversion fromvoid*&#39; tochar*' when using malloc? I'm trying to allocate a matrix dinamically on the memmory using pointers, but I keep receiving the error messages: |122|error: invalid conversion from 'void*' to 'int**'||124|...
You are compiling your program with a C++ compiler. You have two choices: Don't do that. Use a C compiler.Cast the return value frommalloc().
Is there a way to generate a number number between two limits without using the sran and rand functionWhat it is that i have a while (1) (super loop) which calls a function every 10 ms seconds. in the function a for loop is used to create a delay, but, everytime the function is access the delay should be different but...
Try bellow hope this will answer your question. ``` #include<stdio.h> #include <stdlib.h> int main() { int iMaxRand =100,ii=0 ; while( ii < 100) { printf("Random Number is:%d\n", rand() % iMaxRand); ii++; } printf("\n"); } ```
I am trying to make 32 bit library on a 64 bit Ubuntu box. I am creating .so as follows gcc - shared -Wl,-soname,libtest.so *.o I am getting /usr/bin/ld : relocation R_X86_64_PC32 against symbol "set_bright' cann't be used when making shared object;recompile with -fPIC. Already I tried compiling with -fPIC. It did...
I believe you get that error if there you're calling a function declared as hidden, e.g. ``` int set_hidden(void) __attribute__((visibility("hidden"))); ``` and it's not defined in the same shared object. To solve it you have to also link the object file containing the definition ofset_hidden, or remove the call to...
``` int main() { int my array[3][3] = 10, 23, 42, 1, 654, 0, 40652, 22, 0 }; printf("%d\n", my_array[3][3]); return 0; } ``` I am not able to get the array to print.. Any ideas why? I am a beginning programmer so any words of advice are appreciated.
What you are doing is printing the value in the array at spot [3][3], which is invalid for a 3by3 array, you need to loop over all the spots and print them. ``` for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { printf("%d ", array[i][j]); } printf("\n"); } ``` This will print it in the fo...
A typical C program would be compiled, assembled, linked and loaded. I know that Java works with the JVM and produces byte code. Would it be possible to connect both "object files" using the linker? For example, a C program and a C++ program can be used together by playing with the linker and linking both object files...
You can't directly link compiled C code with compiled Java code. You can call compiled C or C++ code from Java usingJava Native Interface (JNI): The Java Native Interface (JNI) enables the integration of code written in the Java programming language with code written in other languages such as C and C++. It allows p...
In windows programming, how can we find out the number of partitions and the name of each partition on the hard drive?
You can use theDeviceIoControlfunction with theIOCTL_DISK_GET_DRIVE_LAYOUT_EXcontol code to get a list of partitions.
Purpose: to receive UDP unicast packets sent to a single port in two different processes. System: Linux, Language: C I am able to bind two sockets in two different processes to the same port using SO_REUSEADDR. But, as expected, the packets are received in only one(the one bound later). Is it possible to receive pa...
It is not possible with sockets API, and tcpdump picks packets right from network interface, before any TCP/IP processing. Your only chance is to receive packets in one process and resend them to another one.
I am proceeding to make a code for handling multiple clients in socket programming but i am not having idea for even the algorithm. I dont know how to proceed. Can anyone help me with the algorithm ? Thanks in Advance
I would download the Apache code - It achieves this and seems to be a reasonable algorithm.
I'm trying to regexp match a C function, e.g. ``` func(blah blah); ``` The match can include newlines. I've tried: ``` func([.+]); ``` which didn't do newlines, and: ``` func([...]); func([^...]); ``` neither of which seemed to do anything. I guess I'm looking for the part of a regexp that will matchany number/...
You could tryfunc[[:space:]]*([^)]*). Nested parens in calls will confuse it though.
I can' figure out what is the advantage of using ``` #define CRANDOM() (random() / 2.33); ``` instead of ``` float CRANDOM() { return random() / 2.33; } ```
By using a#define macroyou are forcing the body of the macro to be insertedinline. When using a function there will1be a function call (and therefor a jump to the address of the function (among other things)), which will slow down performance somewhat. The former will most often be faster, even though the size of th...
If my string contains: ``` a="abd\\aa\[1\]\\" ``` and if I try to write it to a file usingfputsandfprintf, it writes the following to the file: ``` "abd\aa[1]\" ``` I want"abd\\aa\[1\]\\"to be written to the file. How can I accomplish this?
You have to escape your\, like so: ``` printf("abd\\a[1]\\"); ``` Or elseprintfwill print\awhich is theBELcharacter.
I'm reading gzip compressed files using zlib. Then you open a file using ``` gzFile gzopen(const char *filepath, const char *mode); ``` How do you handle Unicode file paths that are stored asconst wchar_t*on Windows? On UNIX-like platforms you can just convert the file path to UTF-8 and call gzopen(), but that will...
The next version of zlib will include this function where_WIN32is #defined: gzFile gzopen_w(const wchar_t *path, char *mode); It works exactly likegzopen(), except it uses_wopen()instead ofopen(). I purposely did not duplicate the second argument of_wfopen(), and as a result I did not call it_wgzopen()to avoid poss...
When using plain C in iPhone development, does the compiler place the variables declared asregisterin a CPU register?
The only way to know for sure is to look at the documentation for the compiler and if that doesn't describe whatregisterdoes then it could do anything (within the parameters defined by the standard).
The following code prints-10 ``` int x = 10; -x; cout << -x << endl; // printf("%d\n", -x); ``` both in C and C++ compilers(gcc 4.1.2). I was expecting a compiler error for the second line. May be it is something fundamental, but I do not understand the behavior. Could someone please explain? Thanks
Statements can be expressions. Such statements discard result of the expression, and evaluate the expression for its side effects. -x;computes the negation ofxand discards the result. For more information read[stmt.expr]in the C++ standard.
Has anyone got an emacs regexp handy to do the following generic replacement? ``` (*ptr_to_struct).member_var to ptr_to_struct->member_var ``` where ptr_to_struct is any pointer to struct and member_var is any member variable
You can try to substitute(\*\([a-zA-Z_][a-zA-Z_0-9]*\))\.\([a-zA-Z_][a-zA-Z_0-9]*\)with\1->\2, where: [a-zA-Z_][a-zA-Z_0-9]*catches the C identifier \(...\)record a match for substitution You can play with regular expression in Emacs using the integrated regexp builder:M-xre-builder.
There are some data types which are present in C but not available in Java. I have listed some of them and written their substitute in Java. Please suggest if i have done it correctly or some changes should be made: unsigned char -> short unsigned short -> int unsigned char *x -> short[] x unsigned short *x -> int...
Forunsigned charyou should use Java'schar, which is also unsigned. The others are OK inasmuch as they are injective (assuming commonly used sizes in C), i.e. they will preserve values, though the matter is rather more complicated with pointers/arrays.
Assume I have an array which holds some struct defined as follows: static struct s x[10] Is each element in the array initialized or are they all empty slots? In another words, what happens if I do: ``` struct s { struct s *next; }; struct s a; a.next = &x[0]; x[0].next = &x[1]; ``` Woulda's next point tox[0]...
Yes, this would work just fine. Sounds like you're thinking about Java arrays. In C, if you declare an array of some type, the actual objects are in the array, not just (uninitialized) references to objects.
For example, an input would be 2095 and I want 20 as an output. Thanks.
You can always scan 2 characters into an int ``` scanf("%2d", &num); ``` or if you already have the number ``` while (num >= 100) num /= 10; ``` This will give you the first 2 digits in number form.
I assume a kernel panic or something equivalently catastrophic could occur, but otherwise is it possible for a send or recv on a NETLINK socket to error out?
Given that the point of anAF_NETLINKsocket is to communicate with the kernel, it's certainly possiblein theoryfor asendcall to fail, as the kernel will inspect the data being handed to it and can decide that said data are nonsense and reject thesend(with any errno it likes). More practically, since you supply the dat...
I'm a little confused about how C reads a file. If I use fscanf to read a file (with multiple lines) and put it into an array[0]. Can I use an if statement to check for\ncharacter and then let it continue to read the second line into array[1]? or will it repeat to read from the start of the file?
Functions like these will always read from your current position (you can obtain this usingftell()for example). After reading, the current position is always updated/moved (except for a few functions stating the opposite). To change the position yourself, you can usefseek(). Side note: You shouldn't usefscanf()as the ...
I am a little new to C programming. I was writing a C program which has 3 integers to handle. I had all of them inside an array and suddenly I had a thought of why should I not use a structure. My question here is when is the best time to use a structure and when to use an array. And is there any memory usage differe...
An array is best when you want to loop through the values (which, essentially, means they're strongly related). Otherwise a structure allows you to give them meaningful names and avoids the need to document that array, e.g. myVar[1] is the name of the company and myVar[0] is its phone number, etc. as opposed to compan...
Using non-blocking (20 ms cycle) TCP connection in linux, I got a problem: when I close socket from the server side [close(sd) or shutdown(sd,2);close(sd)], the client poll() receives no POLLHUP event.when server is killed from shell, POLLHUP is received. How can I inform client in a cycle or two?
A TCP disconnect is signalled with POLLIN, and a read() will return 0 in the case of a graceful shutdown, or -1 and an appropriate error (errno being anything but EINTR/EWOULDBLOCK). There are platforms where it might be signaled with POLLHUP, so you might want to handle that case too.
I've got problem with this peace of code, it should change lower case letters into upper case, and turn multiple spaces into one space. So what it does wrong, it somehow cuts off the first letter like when i write "abcdefg" it givess me on the output "BCDEFG". ``` main(){ int z=0,b; while ( (b = getchar()...
It seems to generate all the letters for me... have you tried tracing it, to find out what it is doing at each step with the characters you entered?
stdint.hdefines integer types with specified width. When should we use those types, for example,uint32_tinstead ofunsigned int? Is it because we can obtain desired types without considering the underlying machine?
When you need to communicate with other systems and you want to be sure of the length of the data. For example: you save your number to disk. How much long is it on disk? With anunsigned intthe response is "it depends on the compiler, the OS...". Withuint32_tit is 32 bits (4 bytes on "standard" architectures).
I am new to Linux. I made this program for printing uptime and ideal time of my Linux machine. But everytime i run this, it shows idealtime = 0. Can i ever get idealtime=0 ? ``` #include<stdio.h> int main() { int a,b; FILE *fp; fp=fopen("/proc/uptime","r"); fscanf(fp,"%d%d",&a,&b); printf("\n\nUptime =%d \nIdea...
It's because the values are not integers. Try this: ``` float a, b; FILE *fp = fopen("/proc/uptime", "r"); fscanf(fp, "%f %f", &a, &b); printf("Uptime = %d\nIdealtime = %d\n", (int) a, (int) b); ```
I want to write a method called print array that has 2 parameters seen below. I want to, most likely using a for loop, iterate through the array of characters and pass each character to the output text file to be printed on that file on the same line. so if the array has a, b, c, d, e, f, g. in the file I want it to ...
Try this: ``` void printArray(char * array, FILE * fout, int MAX_CHAR) { int i; fout = fopen("file.txt","a+"); /* open the file in append mode */ for (i=0; i<MAX_CHAR; i++) fprintf(file,"%c",*(array+i)); /* write */ fclose(file); /* close the file pointer */ ...
open/read/write are low-level I/O functions, and if speed is of my first concern, how to choose between open/read/write and fopen/fread/fwrite?
The higher level functions provide you with ease of usage also, functions likefopen()provides you with in-built I/O buffering unlikeopen(). The I/O buffering ensuresfopen()is much faster thanopen(). Apart from the above distinction If you have just file descriptor, you should use read, write etc, While If you have aF...
Is there is a more efficient way to remove accents from string without make an big array with the characters to replace? For example: ``` removeaccents("áèfoo") ``` Output: ``` aefoo ``` In the ASCII table there no accents, I have no idea how to do this. Thanks in advance. :)
Sounds like you're looking forunac(). From the man page: unacis a C library that removes accents from characters, regardless of the character set (ISO-8859-15, ISO-CELTIC, KOI8-RU...) as long asiconv(3)is able to convert it into UTF-16 (Unicode). I couldn't find the download page (I think it's meant to b...
I am trying todisplay a compile-time message in GCC, via ``` #pragma message "hello world" ``` But when I compile with-Wallit gives the warning ``` warning: ignoring #pragma message ``` I'm using GCC 4.2.1 on Mac OS X 10.6.8 (Snow Leopard). Why isn't it displaying the message? How can I make it display the messag...
If you read thecorrect documentation, you'll find that#pragma messageisn't supported in GCC 4.2.1.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. What are the differences between pu...
Clean Cis a term coined in Harbison & Steele book (C: A Reference Manual, Prentice Hall). A program is said to be written in Clean C if it can be compiled by a standard C compiler and a standard C++ compiler; and its execution would not produce different observable behavior from the two compilers (the issues of optimi...
I have been using the alarm() system call and an alarm handler in my c program. Recently I decided that I wanted to set the alarm for a time less than a second, so I passed it 0.5, and discovered that the alarm() function accepts an unsigned int. Is it possible to set an alarm for less than a second?
Use theualarm(usecs, interval)method instead.