question
stringlengths
25
894
answer
stringlengths
4
863
I have an int array and I need to find the number of elements in it. I know it has something to do with sizeof but I'm not sure how to use it exactly. example ``` int data2[]={a,b,c,d}; ```
With an array you can do: ``` int numElements = sizeof(data) / sizeof(data[0]); ``` But this only works with arrays, and won't work if you've passed the array to a function: at that point the array decays to a pointer, and sosizeofwill return the size of the pointer. You'll see this wrapped up in a macro: ``` #def...
In my computer science program we've been taught to work with child processes and forks and pipes and file descriptors etc etc in C, but we've never done comparable stuff in C++. Do you use the same libraries, or does C++ have some (hopefully simplified) systems libraries of its own?
The types of things you have described are actually system specific rather then C specific. If you look around you might be able to find some wrappers for them, but they are not part of the C++ standard (nor the C standard). As an example, there's no reason to use file descriptors in standard C. That's what the file ...
I am looking for a way to know how much time will my C program use, preferably before I run it, but if this cannot be known before, then after it has ended. Is there a way?
After, yes. On most (all?) UNIX-y systems, you can use this: ``` time ./myprog ``` Before, no, because the program could depend on external input.The halting problemmight also be an obstacle to finding the amount of time a program would take to execute beforehand.
I need to write a program in pureC. I wish to fill an array with user inputted floats and my function at the moment looks like this: ``` int fillWithCustom(float *array, int size) { float customNumber; for (i = 0; i < size; i++) for (j = 0; j < size; j++) { printf("\n Enter [%d...
Don;t usescanf()for user input. It was written to be used with formatted data. User input and formatted data are as different as night from day. Usefgets()andstrtod().
i'm reading the source code ofhttp-parserand came across some if statements with empty blocks. here's an example (source) ``` int dontcall_message_begin_cb (http_parser *p) { if (p) { } // gcc fprintf(stderr, "\n\n*** on_message_begin() called on paused parser ***\n\n"); abort(); } ``` the comment merely menti...
My guess is someone trying to suppress the "unused parameter" warning. The canonical way to do this is(void)p;, but I'm guessing the author of the code didn't know about that.
I have an input string of the form ``` char *s = "one.two three" ``` and I want to separate it into 3 string variables. I'm doing ``` sscanf(s, "%s.%s %s", one, two, three); ``` but it's reading in "one.two" as the string for variable one. How do I handle the "." and the whitespace with sscanf?
The%sspecifier only stops for a space. Try something like: ``` sscanf(s, "%[^.].%s %s", one, two, three); ``` Interestingly, it's likely impossible to produce an acceptable input for"%s.%s %s"since%sonly stops for a space yet a.must immediately follow it.
I compiled the same program (not library) with different compilation flags, in CMake with Clang with CMAKE_C_FLAGS = -Wl,-export-dynamicwith CMAKE_EXE_LINKER_FLAGS = -export-dynamic But I noticed that the second way doesn't seem to work. I can't find the exported symbols. I'm so surprised that only the 1st way works...
Provide same options for second variant. set(CMAKE_EXE_LINKER_FLAGS "-Wl,-export-dynamic") Because compiler and linker the same in your case.
I am using the above code to increment a counter using 2 threads, which independently take the mut lock and increment counter. I am facing a deadlock after the threads enter this function. ``` pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; void *increment_counter(void *counter_addr) { int max = MAX_COUNTER_VA...
You're trying to lock the mutexmaxtimes, then incrementcounterand release it once. Try: ``` for(iter=0;iter< max ;iter++) { // LOCK pthread_mutex_lock(&mut); counter++; // UNLOCK pthread_mutex_unlock(&mut); } return NULL; ```
I would like to run something like: ``` grep TEXT file.txt ``` If TEXT exists in file.txt then add a compilation flag. Here is the pseudocode- ``` if (grep TEXT file.txt == line exists) CFLAGS += -DFOO ``` I would like this to happen in Makefile. I have tried $(shell command) but it did not work so I am a bit...
Please insert a line like the following. So it may work well. ``` CFLAGS += $(shell /bin/grep -q pattern /path/to/file >/dev/null 2>&1 && echo "-DFOO" || echo "-UFOO") ``` If the text exists in the file, it evaluates to : ``` CFLAGS += -DFOO ``` else if text does NOT exist in the file, it evaluates to : ``` CFLAG...
``` unsigned char Mid; if( (data[2]) == 0x9A){ Mid = data[5]; if( (Mid == 1) || (Mid == 2) || (Mid == 3) ) return(Mid); ``` The code above gives: warning: comparison is always false due to limited range of data type error as I expected. It's ok if I type ``` if( (unsigned char)data[2] == 0x9A){ ...
When casting the value to unsigned char, you are doing an explicit type conversion.When you mask the value with0xFF, animplicit type conversiontakes place. You have the signed chardata[2]and0xFFas operands to the bitwise AND operator. Because one of the operands (0xFF) cannot fit inside a signed char, both operands a...
I have two strings as below Str1: 1234\099 Str2: 123499 If I calculate MD5 on these string using unsigned char *MD5(const unsigned char *d, unsigned long n, unsigned char *md); Will the function MD5 calculate the hash for first 4 bytes of Str1 or would it take the complete string "1234\099". Will...
That all depends on what value you pass for thenparameter. If you usestrlen()to calculaten, then theMD5()function will process data up to, but not including, the null (because you told it to, in effect). If you pass in the correct length forn(I assume that's7forStr1), thenMD5()will include all the data in the hash, ...
Can we dynamically allocate 2D array without using any for loop or while loops? i there any direct command or function in c c++?
Without using a loop you will have one restriction in ISO c++ i.e. size of one dimension has to be determined at compile time. Then this allocation can be done in a single statement as follows: ``` #define COLUMN_SIZE 10 // this has to be determined at compile time int main() { int (* arr)[COLUMN_SIZE]; int r...
On my Linux machine when i run ``` uname -v ``` it gives me ``` #83-Ubuntu SMP Wed Jan 4 11:12:07 UTC 2012 ``` Now i am building my custom kernel and i need to show some flag/text info about build in this string .. i want something like if some config are on then addBUILD-XYZin that string ``` #83-Ubuntu SMP W...
The variable CONFIG_LOCALVERSION (inside your kernel .config file) let you set a custom string that will be appended to the kernel release number, thus shown when using 'uname'. Is that what you want?
I did a sample code in pro*C language to fetch data from a table. TableEmp_tablecontain two fields:Emp_NameandEmpId. From SQL-Plus I added 3 records and through Pro*C code, added another 3 records. ``` EXEC SQL SELECT Emp_Name INTO :ename From Emp_table where EmpId=1; ``` I'm unable to get theenamefrom the records...
It looks like you have not executed commit after insertion of records using SQL*Plus. Can you confirm on this?
Newbie to sqlite3. Correct me if my understand is wrong?. sqlite3_open ( filename, &dbConnection) -> ``` 1) This API creates an database [ie: filename], if it does not exists, and sets the context to dbConnection. 2) If the database exists already it just sets the context to dbConnection. ``` Both the case (1) & ...
U can use create table if not exist syntax for that.
How are the specifiers%pand%Fpworking in the following code? ``` void main() { int i=85; printf("%p %Fp",i,i); getch(); } ``` I am getting the o/p as0000000000000055 0000000000000055
If this is what you are asking, %p and %Fp print out a pointer, specifically the address to which the pointer refers, and since it is printing out a part of your computer's architecture, it does so in Hexadecimal. In C, you can cast between a pointer and an int, since a pointer is just a 32-bit or 64-bit number (depe...
This is elementary, but my googling just doesn't cut it. I know I have to do something else to shift the values of an array one by one, but the below coding gives me the same values for items[k] to items[infinity] all equaling items[k]. What I don't understand is how to preserve the original k+1 value while I copy the...
You can as well use memmove, that handles overlap of regions. ``` memmove(&items[k+1], &items[k], (numItems-k-1)*sizeof(double)); items[k] = value; ```
In C, I do: ``` char* buffer=p->content; // p is a struct type and content is a char* printf("buffer:%s\n",buffer); ``` My output is this: ``` @uffer: �@��^��0z ``` I don't quite know why I get �@��^��0z, but I suspect is has to do with me incrementing mypointer incorrectly. My main question is: Why is my "...
The garbage data you are printing coincidentally contains a line printer control character known as carriage return, which your display device is interpreting as a command to move the cursor to the beginning of the line. Then if a @ character occurs, it overwrites the first character of your output.
Let's say I have a struct called Thing. If I want to have an array of "Thing", yet it doesn't have a fixed size (dynamic), how do I go about allocating space for it? Do I initially malloc space for the array itself, and then have to realloc space every time I add an element to it? For example: ``` struct Thing{ c...
You'll probably want to use thedynamic arraystrategy: keep track of how many items are in it and the current capacity, then any time it fills up, double the capacity. You get amortized linear time and the random access of an array.
So here are some macros I have created: ``` #define MODULE_NAME moduleName #define MODULE_STRUCT MODULE_NAME ## _struct #define MODULE_FUNCTION(name) MODULE_NAME ## _ ## name ``` After those definitions, I would like the following expansions to happen: ``` MODULE_STRUCT --> moduleName_struct MODULE_FUNCTION(fun...
In C the operands of the token pasting operator##are not expanded. You need a second level of indirection to get the expansion. ``` #define CAT(x, y) CAT_(x, y) #define CAT_(x, y) x ## y ```
I have the following struct in C. ``` struct a { long state; long uid; long w, x, y, z, xx, yy, zz, xxx, yyy, zzz; char comm[64]; }; ``` Then I do amallocas follows. ``` buf = malloc (100 * sizeof(struct a)); ``` But when I try to access the individual structs as follows, I get a seg fault. ``` fo...
if buf is a pointer to a struct a, the pointer math should be: ``` tmp = buf + i; ```
i have a code like this: ``` int i = 123; char myString[100]; strcpy(myString, "my text"); ``` and how i want to add the 123 after "my text". how to do this in c/c++? at the endmyStringsould bemy test123
In C++: ``` std::stringstream ss; ss << "my text" << i; std::string resultingString = ss.str(); ``` There's no such thing as C/C++.
Say I want a very simple makefile that includes libraries to link (lets say-lm) ``` CFLAGS=-Wall -g LIBS=-lm ``` How do I get$(LIBS)to the right part of the command without having to manually construct the command inside the makefile and breaking a bunch of the implicit rules? I couldn't find anything in the manual...
Following thelinkyou gave, there's theLDFLAGS: ``` LDFLAGS Extra flags to give to compilers when they are supposed to invoke the linker, ‘ld’. ```
This question already has answers here:Closed10 years ago. Possible Duplicate:In C, what is the correct syntax for declaring pointers? I am fighting with the c language. Pointers are new to me, and I think I am getting closer and closer to understanding them. I have though one questions. What is the difference bet...
There is no difference in those declarations, but there is a difference between the following two declarations: ``` int* p, p2; // declares a pointer to int and a regular int ``` and: ``` int *p, *p2; // declares two pointers to int ``` that might be hidden by your example. So I prefer the second declaration.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen...
The return value ofprintfis the number of characters printed. The innerprintfis called first. Equivalent to: ``` int rc = printf("earth"); printf("%d", rc); ```
The following code gives me the output as 'd': ``` void main() { short int a=5; printf("%d"+1,a); getch(); } ``` How doesprintf()actually work?
printfdoes not "see" the format specifier because you are passing a pointer to"%d"plus one. This is equivalent to passing"d"by itself: ``` printf("d", a); ``` will printdand ignorea. This is not specific toprintf, pointer arithmetic works like that with allcharpointers, including pointers obtained from string litera...
I'm new to C, and I'm trying to make a string of variable length, like this: ``` int main(int argc, char *argv[]) { if (argc > 1) { char filename[] = argv[1]; } else { char filename[] = "temp.txt"; } printf("%s", filename); } ``` Of course, that doesn't work because the scope of t...
This is one way: ``` char* filename = "this is a different one"; if (boolean) filename = "this is a file name"; printf("%s", filename); ```
I'm changing a socket connection in a script to a non-blocking connection. In a tutorial I found the lines: ``` x=fcntl(s,F_GETFL,0); // Get socket flags fcntl(s,F_SETFL,x | O_NONBLOCK); // Add non-blocking flag ``` So I added them after I create my socket and before the connect statement. And it's no...
Check return value ofconnect(2)- you should be getting-1, andEINPROGRESSinerrno(3). Then add socket file descriptor to a poll set, and wait on it withselect(2)orpoll(2). This way you can have multiple connection attempts going on at the same time (that's how e.g. browsers do it) and be able to have tighter timeouts.
let's say I have 2 processes and I have a variable I want to pass from the first one to the second one. I know I can declare a global variable and pass it by reference among differents functions, but I don't know if it is possible to pass a variable among different processes. I heard that each process is assigned its...
I don't know if it is possible to pass a variable among different processes. No, it is not possible, at least not in the classical sense of passing a variable. You have many options, though: inter-process communication can be done through shared memory (sometimes implemented through memory-mapped files), named pipes,...
``` #include <stdio.h> int main(void) { char s[] = {'a','b','c','\n','c','\0'}; char *p; p=&s[3]; printf("%d\t",++*p++); printf("%d",*p); return 0; } ``` output: 11 99Please explain the output. Why there is an increment in the address?
The only thing I see that could possibly be confusing is ``` ++*p++ ``` Postincrement has higher precedence than the dereference operator, so fully parenthesized it looks like ``` ++(*(p++)) ``` Which postincrementsp, dereferences the original value ofpto get achar, then preincrements the value of thechar, and the...
I have come across a code which goes like : ``` #include <stdio.h> int main(void) { int a[5] = { 1, 2, 3, 4, 5}; int *ptr = (int*)(&a + 1); int *ptr2 = (int*) &a; ptr2 +=1 ; printf("%d %d %d \n", *(a + 1),*(ptr - 1) ,*ptr2 ); return 0; } ``` The pointer arithmetic does it for me except this line : ``` int *p...
The size ofais "5ints". So&a + 1refers to the first memory locationpastall ofa, since the pointer arithmetic is done in units of the size ofa.
I've got anunsignedand would like to convert that to anuint64_t(and back if possible). How do I do that? If possible, I would like to avoid depending on undefined behaviour. Thanks!
The conversion to unsigned integer types from any integer types is completely defined by the standard (section 6.3.1.3, paragraph 2). If the value can be represented in the target type, it is preserved, otherwise the value is reduced modulo2^WIDTH, whereWIDTHis the width (number of value bits) of the target type.
How can I flush the input buffer without putting a newline character in scanf()? Because my proffessor doesn't like it. I tried fflush(); but it didn't work. ``` #include <stdio.h> #include <conio.h> int CountUpper(char S[],int n) { int i,cntr = 0; for(i = 0; i < n; i++) if(S[i] >= 'A' && S[i] <= 'Z')...
fflushis defined only for output streams andfflush(stdin)invokesundefined behaviour. You can look into this to discard inputs in buffer:what can I use to flush input?
``` int16_t s; uint32_t ui = s; ``` Is the result of converting aint16_tvalue to auint32_tvalue compiler dependent? If not, what's the rule?
The results are well-defined; non-negative values stay the same, and negative values are reduced modulo 2^32. But the situations whereexactsized types likeint16_tanduint32_tare needed are quite rare. There's really no need for anything other thanintandunsigned longhere: those types haveat leastas many bits asint16_tan...
I get that using negative indexes is just pure luck. But out of curiousity I tried this. I know you can declare array[0]; just like malloc(0); is legal. But how come I can store a value in array[0]? ``` #include <stdio.h> #include <conio.h> int main(void) { int i; int array[0]; array[0] = 5; print...
Such a0sized array is a constraint violation in standard C, you compiler should not let you get away with this without giving you a diagnostic. If it doesn't tell you something then, that must be an extension that your compiler vendor has added to its C dialect. Don't rely on such extensions. Regardless whether or n...
In GDB, given a variable that points to a struct,printwill display the raw pointer value andxwill display the raw bytes pointed to. Is there any way to display the data pointed to as that struct, i.e. a list of fields and their values?
``` print *variable ``` If you do that it will display the value of that variable in GDB.You also have an option to display the struct with indentation and new lines: ``` $1 = { next = 0x0, flags = { sweet = 1, sour = 1 }, meat = 0x54 "Pork" } ``` For that you need to set the pretty print: ``` set ...
Im new to Pro*C coding. is there any difference between VARCHAR and char? can i select a VARCHAR data into an character array? will there be any side effects?
TheVARCHARis a special type added by the Pro*C pre-compiler, it doesn't exist in the base C language. However, in C you can access aVARCHARvariable as a structure if I'm not mistaken.
I am looking to know if it is possible to read from a serial port at 100 baud rate. As pertermio.hthere is no provision to set 100 as baud rate. I am working in Linux. The communicating device on the other end is sending data at 100 baud rate and it is fixed. I would like to know if my baud rate is set to 110, would i...
You're actually in luck. 100 baud is low enough that you can compute a divisor that will do it (1,152) with typical 16450-compatible serial ports (which is pretty much what everything is) and linuxsupports custom divisorswith thespd_custparameter tosetserial.
I need to store boolean information for around 10000 variables. First I thought of using a bool array arr[10000] but it takes 40000 bytes. But I need to store this information in a memory efficient way. Maybe using bit manipulation? Also another thing that I need to store it globally and allocate it dynamically also. ...
You could do: ``` vals = new char[(len+7)/8]; // To access vals[i/8] & 1 << (i % 8) // To set vals[i/8] |= 1 << (i % 8); // To clear vals[i/8] &= ~(char)(1 << (i % 8)); ``` Though to be the fastest, you should use whatever the word size is sized chunks. So on a 32-bit computer: ``` vals = new uint32_t[(len+31)/32];...
This question already has answers here:Closed10 years ago. Possible Duplicate:Negative array indexes in C? How come this compiles, and runs as intended? I'm confused. I was just curious what would happen and to my surprise. It worked. ``` #include <stdio.h> #include <conio.h> int main(void) { int i; int arr...
It worked because you're unlucky. It's undefined what should happen. ``` array[x] ``` is equivalent to ``` *(array+x) ``` so you're basically dereferencing a pointer that'sxpositions afterarray. In your case,xis negative, so you're accessing memory before the array. It's not guaranteed to work. The fact that it c...
Why i am getting the different values of i. ``` #include <stdio.h> void pri(int,int); int main() { float a=3.14; int i=99; pri(a,i); getch(); } void pri(int a,int i) { printf("a=%f i=%d\n",a,i); printf("i=%d a=%f\n",i,a); } ```
You declaredaas an int, but you are using%fso it should be declared as a float: ``` void pri(float a, int i) { printf("a=%f i=%d\n", a, i); printf("i=%d a=%f\n", i, a); } ``` If you have an incorrect type you get undefined behaviour. The specification forprintfreads (7.19.6.1 paragraph 9): If a conversion s...
I am using the CS50 appliance from Harvard and trying to make a character lowercase. I am trying to use thetolower()function but when I try to use it I get the messageimplicit declaration of function 'tolower' is invalid in C99. Anyone care to elaborate on why I would be getting this message. I have includedstdio.has ...
To usetolowerin C99, use#include <ctype.h> It is not an I/O function and it doesn't operate on strings (it operates on characters), so it's not instdioorstring.
``` float abc = 145606035; NSLog(@"%f", abc); NSLog(@"%d", abc); First NSLog = 145606032.000000 //this is wrong, please look at the last digit. Second NSLog = 536870912 //this is wrong too! ``` Why the answer so weird? Does it make sense? The 'abc' not even exceed the Integer maximum number, how come the number is ...
The reason is because it interprets the binary representation of abc as an integer. Decimal numbers and integers in binary representation are completely different and to get the correct output you should cast abc to an int(int)abc The first output is off because of the precision of floating point numbers. A float has...
I'm trying to read individual characters from a string constant passed into a function and put them into an array. The end result i want is an a string array that is the same string as the string constant. This is my code: ``` for(int i = 0; i < string_length; i++) { sscanf(string, "%c", &array[i]); } ``` When s...
sscanf cannot remember your index positioning and automatically increment pointers. So, effectively, it ends up reading the first character each time you call it in the loop. Try as below ``` sscanf(string+i, "%c", &array[i]); ``` Additional Note:You can as well use strcpy or memcpy to copy the string into a charac...
I get that using negative indexes is just pure luck. But out of curiousity I tried this. I know you can declare array[0]; just like malloc(0); is legal. But how come I can store a value in array[0]? ``` #include <stdio.h> #include <conio.h> int main(void) { int i; int array[0]; array[0] = 5; print...
Such a0sized array is a constraint violation in standard C, you compiler should not let you get away with this without giving you a diagnostic. If it doesn't tell you something then, that must be an extension that your compiler vendor has added to its C dialect. Don't rely on such extensions. Regardless whether or n...
In GDB, given a variable that points to a struct,printwill display the raw pointer value andxwill display the raw bytes pointed to. Is there any way to display the data pointed to as that struct, i.e. a list of fields and their values?
``` print *variable ``` If you do that it will display the value of that variable in GDB.You also have an option to display the struct with indentation and new lines: ``` $1 = { next = 0x0, flags = { sweet = 1, sour = 1 }, meat = 0x54 "Pork" } ``` For that you need to set the pretty print: ``` set ...
Im new to Pro*C coding. is there any difference between VARCHAR and char? can i select a VARCHAR data into an character array? will there be any side effects?
TheVARCHARis a special type added by the Pro*C pre-compiler, it doesn't exist in the base C language. However, in C you can access aVARCHARvariable as a structure if I'm not mistaken.
I am looking to know if it is possible to read from a serial port at 100 baud rate. As pertermio.hthere is no provision to set 100 as baud rate. I am working in Linux. The communicating device on the other end is sending data at 100 baud rate and it is fixed. I would like to know if my baud rate is set to 110, would i...
You're actually in luck. 100 baud is low enough that you can compute a divisor that will do it (1,152) with typical 16450-compatible serial ports (which is pretty much what everything is) and linuxsupports custom divisorswith thespd_custparameter tosetserial.
I need to store boolean information for around 10000 variables. First I thought of using a bool array arr[10000] but it takes 40000 bytes. But I need to store this information in a memory efficient way. Maybe using bit manipulation? Also another thing that I need to store it globally and allocate it dynamically also. ...
You could do: ``` vals = new char[(len+7)/8]; // To access vals[i/8] & 1 << (i % 8) // To set vals[i/8] |= 1 << (i % 8); // To clear vals[i/8] &= ~(char)(1 << (i % 8)); ``` Though to be the fastest, you should use whatever the word size is sized chunks. So on a 32-bit computer: ``` vals = new uint32_t[(len+31)/32];...
This question already has answers here:Closed10 years ago. Possible Duplicate:Negative array indexes in C? How come this compiles, and runs as intended? I'm confused. I was just curious what would happen and to my surprise. It worked. ``` #include <stdio.h> #include <conio.h> int main(void) { int i; int arr...
It worked because you're unlucky. It's undefined what should happen. ``` array[x] ``` is equivalent to ``` *(array+x) ``` so you're basically dereferencing a pointer that'sxpositions afterarray. In your case,xis negative, so you're accessing memory before the array. It's not guaranteed to work. The fact that it c...
Why i am getting the different values of i. ``` #include <stdio.h> void pri(int,int); int main() { float a=3.14; int i=99; pri(a,i); getch(); } void pri(int a,int i) { printf("a=%f i=%d\n",a,i); printf("i=%d a=%f\n",i,a); } ```
You declaredaas an int, but you are using%fso it should be declared as a float: ``` void pri(float a, int i) { printf("a=%f i=%d\n", a, i); printf("i=%d a=%f\n", i, a); } ``` If you have an incorrect type you get undefined behaviour. The specification forprintfreads (7.19.6.1 paragraph 9): If a conversion s...
I am using the CS50 appliance from Harvard and trying to make a character lowercase. I am trying to use thetolower()function but when I try to use it I get the messageimplicit declaration of function 'tolower' is invalid in C99. Anyone care to elaborate on why I would be getting this message. I have includedstdio.has ...
To usetolowerin C99, use#include <ctype.h> It is not an I/O function and it doesn't operate on strings (it operates on characters), so it's not instdioorstring.
``` float abc = 145606035; NSLog(@"%f", abc); NSLog(@"%d", abc); First NSLog = 145606032.000000 //this is wrong, please look at the last digit. Second NSLog = 536870912 //this is wrong too! ``` Why the answer so weird? Does it make sense? The 'abc' not even exceed the Integer maximum number, how come the number is ...
The reason is because it interprets the binary representation of abc as an integer. Decimal numbers and integers in binary representation are completely different and to get the correct output you should cast abc to an int(int)abc The first output is off because of the precision of floating point numbers. A float has...
I'm trying to read individual characters from a string constant passed into a function and put them into an array. The end result i want is an a string array that is the same string as the string constant. This is my code: ``` for(int i = 0; i < string_length; i++) { sscanf(string, "%c", &array[i]); } ``` When s...
sscanf cannot remember your index positioning and automatically increment pointers. So, effectively, it ends up reading the first character each time you call it in the loop. Try as below ``` sscanf(string+i, "%c", &array[i]); ``` Additional Note:You can as well use strcpy or memcpy to copy the string into a charac...
I'm working in GDB on S390x I have a function that essentially does this: ``` Item *getItemFromRef( PrimaryDataStructure pds, size_t ref ) { Item *returnValue = NULL; SecondaryDataStructure sds = getSecondaryFromPrimary(pds, ref) if (sds) { returnValue = getItemFromRefSecondary(sds, ref); } ...
I took another look at the symbols today and discovered that two different dynamic libraries were importing the same function symbol and that the break point was being set to the wrong version of the function.
I'm trying toexecvea process that reads from stdin. I want to prepare stdin with some data so it can execute successfully. How can I do that?
You will need to fork the execve call into a child process and then create a pipe from the parent process to the child's stdin. Take a look at this link for a detailed example on how to use pipes:http://tldp.org/LDP/lpg/node11.html
How do I get the contents from one character buffer into another? For instance I have ``` char buffer[SMALLVALUE]; char new_buffer[BIGGERVALUE]; ``` I'd like to copy the contents ofbufferintonew_buffer. What's the shortest way to do this?
``` #include <string.h> memcpy(new_buffer, buffer, sizeof buffer); ```
I always asked my self this question, Why printf() in C was designed to accept any number of parameters, isn't that Overloading? if yes how does a pure structured language contains an Object oriented language concept like Method overloading?
isn't that Overloading? No, there is no overloading in C. It is called a"variadic function". And no, despite its appearance in C++ and absence from C, method overloading is not an object-oriented concept. It is featured prominently in rather old programming languages, such as Prolog, that are not object-oriented.
Is this code right for writing a character array (referenced by a char pointer) to a file? ``` const char* charBuf; FILE *outputFile = fopen("output", "a"); fprintf(outputFile, "%s\n", *charBuf); fclose(outputFile); ``` Assumebufpoints to some character array.
File mode needs a quote: ``` File *outputFile = fopen("output", "a"); ``` unless you have a c-stringadefined with the mode. Assuming you have stored some value intocharBuf, you have to use the string in fprintf.*charBufrefers to the first character in that string. ``` fprintf(outputFile, "%s\n", charBuf); ``` You...
I'm experimenting withIntel Integrated Performance Primitives (IPP), and I'm curious about the "right way" to do 2D convolution in IPP. According to the Intel IPP documentation,ippiConvFull(documentation) andippiConvValid(documentation) are deprecated. However I don't see any other 2D convolution routines in IPP. I ...
You can useippiFilterinstead. It is not marked as deprecated and operates in 2D.
Let's take an array of bit-masked status bytes: ``` char status[10]; ``` Now, let's say we want to pull the 3rd bit out of each status byte and put them into an int, where the LSB of the int is status[0] bit 3, next is status[1] bit 3, etc. ``` int foobits = 0; for( i = 0; i < 10; i++ ) { foobits |= (( status[i...
You could do this ``` int foobits = 0; for( i = 0; i < 10; i++ ) { foobits |= (status[i] & 0x04) << i; } foobits >>= 2; ``` but why bother? "Premature optimization is the root of all evil." -- Donald Knuth
I am trying to make a configure.ac + Makefile.in files I have. Everything is ok till at make: Here I have: ``` usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 9 has invalid symbol index 2 /usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 10 has i...
Problem solved.I've replacedAM_CFLAGSwithFILE_NAME_CFLAGS.
Working on my assignment, more details inanother question. If I use ``` arr[(i * 16) % arrLen] *= 2; // seg fault ``` vs ``` arr[i % arrLen] *= 2; // OK! ``` Why?Full sourcesee line 31. Why? I modulus the array length so it should be OK?
i * 16can overflow into the negative range of signed integers. When you take modulo of a negative integer, you can get a negative remainder and that'll make your array subscript negative and result in an access outside of the array's allocated memory and sometimes a crash.
What does this line of code mean? ``` #define NAME ((LPCSTR) 5) ``` If I define a variable,NAME *tmp, then use it like this: ``` ((LPCSTR) 5) *tmp; ``` What does that code do? Note:LPCSTRistypedef __nullterminated CONST CHAR *LPCSTR
That's a simple cast, it converts 5 to a character pointer (__nullterminated CONST CHAR *) That's probably undefined behaviour by the standard, but sometimes used in real life. To address specific physical addresses on your machine - for example the kernel has to do this to configure cards, onbard chips, etc...To se...
I'd like to assign a specific value to a variable when my code is compiling (for C and C++): For example having : ``` //test.c int main() { int x = MYTRICK ; (edit: changed __MYTRICK__ to MYTRICK to follow advices in comment) printf ("%d\n", x); return 0; } ``` beeing able to do something like: ``` gcc -...
Use-Doption: ``` gcc -DMYTRICK=44 test.c -o test ``` And useMYTRICKmacro in your program and not__MYTRICK__. Names beginning with__are reserved by the implementation.
if i call sigaction at the beginning of my code, ``` sigaction(SIGPIPE, &pipe_act, NULL); ``` if i receive sigpipe, after the execution of pipe_act the handler installed remains pipe_Act, or the default handler is automatically set for sigpipe?
It depends on whether or not your flags (pipe_act->sa_flags) includeSA_RESETHAND. If yes, then the signal handler is a "one-shot" and gets removed after having been called (i.e. the handler is reset to the default handler), but if not, then the handler remains in place until you change it manually.
What does this line of code mean? ``` #define NAME ((LPCSTR) 5) ``` If I define a variable,NAME *tmp, then use it like this: ``` ((LPCSTR) 5) *tmp; ``` What does that code do? Note:LPCSTRistypedef __nullterminated CONST CHAR *LPCSTR
That's a simple cast, it converts 5 to a character pointer (__nullterminated CONST CHAR *) That's probably undefined behaviour by the standard, but sometimes used in real life. To address specific physical addresses on your machine - for example the kernel has to do this to configure cards, onbard chips, etc...To se...
I'd like to assign a specific value to a variable when my code is compiling (for C and C++): For example having : ``` //test.c int main() { int x = MYTRICK ; (edit: changed __MYTRICK__ to MYTRICK to follow advices in comment) printf ("%d\n", x); return 0; } ``` beeing able to do something like: ``` gcc -...
Use-Doption: ``` gcc -DMYTRICK=44 test.c -o test ``` And useMYTRICKmacro in your program and not__MYTRICK__. Names beginning with__are reserved by the implementation.
if i call sigaction at the beginning of my code, ``` sigaction(SIGPIPE, &pipe_act, NULL); ``` if i receive sigpipe, after the execution of pipe_act the handler installed remains pipe_Act, or the default handler is automatically set for sigpipe?
It depends on whether or not your flags (pipe_act->sa_flags) includeSA_RESETHAND. If yes, then the signal handler is a "one-shot" and gets removed after having been called (i.e. the handler is reset to the default handler), but if not, then the handler remains in place until you change it manually.
``` if (ch == '\\') { escape_ch = '\\\\'; } ``` The compiler is not happy with 4 backslashes but I need to be able to make'\\'as one character. C reads'\\'as one backslash. So I tried'\\\\'as two backslashes and it's not working. I need this in order to implement my program.
A character in C can only be one character, therefore you can't put two backslashes in. If you explain what you want we might be able to better help you. You can do tokenization using strstr by doing: ``` tok1 = str; tok2 = strstr(str, "\\\\"); *tok2 = '\0'; tok2 += 2; ```
I am now porting an single-threaded library to support multi-threads, and I need the whole list of functions that use local static or global variables. Any information is appreciated.
Check the manual page for each function you use ... the non-thread-safe ones will be identified as such, and the manual page will mention a thread safe version when there is one (e.g.,readdir_r). You could extract the list by running a script over the man pages. Edit: Although my answer has been accepted, I fear that...
It's a textbook C code ``` void strcpy_new(char *s, char *t) { while ((*s = *t) != '\0') { s++; t++; } } int main(int argc, const char * argv[]) { char *s = "this is line a"; char *t = "this is line b"; printf("%s", s); strcpy_new(s, t); printf("%s", s); return 0; } `...
The reason you get EXEC_BAD_ACCESS is because those string literals"this is line a"and"this is line b"are stored in read-only memory. Attempting to write to it (*s = *t) is undefined behavior and you are receiving a crash because of it. To remedy this code you should allocate some memory forsso that it is large enoug...
I'm studying networking in C/C++ so sockets. For example I'm now using firefox and I can load both 10KB pages and 30MB pages. So I assume that all the data I get from web server is written into some buffer.. but is that buffer fixed size or maybe based on Content-size?
The data is actually flowing from buffer to buffer to buffer and eventually winding up in memory. The server reads from disk through a disk buffer and writes into a TCP network buffer which its kernel empties into a network interface buffer. The data travels over the network from buffer to buffer as it crosses various...
Here is the thing,1024 = 0x400, and I assume its binary representation (little endian) is\\x00\\x4\\x00\\x00. And I try to do something like this, ``` int main() { const char *str = "\\x00\\x4\\x00\\x00"; const int *p = (const int *)str; printf("%d\n", *p); } ``` But why the above code can't give me1024?...
Because you escaped\. Unescape them: ``` const char *str = "\x00\x4\x00\x00"; ```
hello I've got text file with lines format ``` 1|few ewf ew fewfew ``` I need to parse it but I don't know how can I drop whitespaces tail from second value I don't know. Here is mysegmentation faulttry so far ``` char* token1; char* token2; char* search = "|"; char* search2 = " "; // double space because string ...
Take a gander at thedeblankfunction. Here's a link:http://www.mathworks.com/help/matlab/ref/deblank.html
I would like to input 2 unsigned char variables:a and b. If use a(0) for bit 0 in a, I would like to swap a(6) to a(1) with b(6) to b(1). Finally I wish to get 2 new unsigned char_type variables:a1 and b1 with required bits swapped. I would love to know that is there method to address this issue in C language? An fur...
I'd be inclined to use xor masking: ``` mask = 0x3e; // 0b00111110 diff = (a & mask) ^ (b & mask); a1 = a ^ diff; b1 = b ^ diff; ```
Is there any easy way to implement concurrency in udp servers. In TCP we have a connection which can be used to distinguish clients which is not the case in UDP. So is there any other way in which a client can be uniquely identified from another which is trying to connect to the server so that the server can fork a pr...
You will need to look at the sockaddr struct that you pass a pointer of to recvfrom after recvfrom returns. That will tell you where the data's coming from.
If I allocate memory for achar a[256], initialise each element to a different value and pass this to some function: ``` int subFunc(a); ``` how does the stack frame ofsubFunclook? Does the stack frame contain all the 256 bytes in it or just a pointer to the address ofa(4 bytes). If a pointer, then how does it acce...
The C language doesn't require a stack based machine. That said, it's likely that on stack based machines a block scope array is allocated on the stack. You can't pass an array to a function in C. The language specifies thatsubFunc(a)receives a pointer to the first element ofa. This is exemplified by the fact that th...
Is it possible to have in C something like: ``` #define MACRO_EX 333 #define MACRO_EX(X,Y) ((X) < (Y) ? : (X) : (Y)) ``` Can they coexist?
TheC standardsays (ISO/IEC 9899:1999, §6.10.3, 2): An identifier currently defined as an object-like macro shall not be redefined by another #define preprocessing directive unless the second definition is an object-like macro definition and the two replacement lists are identical. Likewise, an identifier currentl...
I downloaded this sample:https://developer.apple.com/library/ios/#samplecode/Touches/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007435If I start the sample app everything is working fine. I made my own app and copied most of the code into it. There is a method called adjustAnchorPointForGestureRecognizer: But i...
Did you import theQuartzCoreframework into your project? Maybe that's why it can find theCALayerclass This error is thrown by XCode when it can't find a definition forCALayer. You should add the framework to your project and add#import <QuartzCore/QuartzCore.h>to wherever you are using the class
I need to implement concurrent matrix multiplication in C using multiple processes. I understand that because each process has its own private address space, I will have to use some form of interprocess communication (IPC). I did some looking around and couldn't find many implementations that didn't use threads. I was...
The most efficient way of concurrently processing matrix multiplications would be shared memory. In this way, you don't have to serialize your matrix through a pipe/message and you can directly apply your multiplications on your shared memory space.
Can anybody tell how to write a program which when compiled withgccprintsc, and withg++printsc++?
``` #ifdef __cplusplus printf("c++\n"); #else printf("c\n"); #endif ``` You may run into issues if your file extension isn't right.
I have a program that has two separate sections: one of them should be executed when the network interface is wireless LAN and the other one when it's a wired LAN connection. How can I know that inside of my program? What function should I use to get that information?
If your device name isNETDEVICE, a check of the existence of the/sys/class/net/NETDEVICE/wirelessdirectory is a predicate you can use. This is a Linux-only approach, though, and it assumes that/sysis mounted, which is almost always the normal case. It's also easier to employ this method from scripts, rather than deali...
What is the order of evaluation in C in the case ofx<<y>>z? Is it(x<<y)>>z, because of the Left to Right associativity ? EDITNeed to know what the standards tell about it, and not guess what's going on by inspection for a particular compiler.
Yes,>>and<<are left associative and of the same precedence, sox << y >> zis equivalent to(x << y) >> z.
I'm sure this question is answered elsewhere, but I cannot find it on Google or SO, so here goes. In C/C++, I want to convert a relative time in format dd-hh:mm:ss provided by ``` ps -o etime ``` to an absolute UTC formatted date. This doesn't seem like it should be very hard. Supposing I have already got a functi...
UseBoost::Date_Timelibraries.
moin-moin, I need the MS Visual C (6.0) equivalent for the functions "DosEnterCritSec()" and "DosExitCritSec()", which garantees, that no two threads are executing the enclosed code at the same time. Can anybody please point me into the right direction? Thanks a lot, Peter
EnterCriticalSection() / LeaveCriticalSection() http://msdn.microsoft.com/en-us/library/windows/desktop/ms682608(v=vs.85).aspx
I want to read data from a string. The string is like this: ``` "123 35 123 0 0 0 817 0 0 0 0" ``` there are a few numbers and spaces which is uncertain in the string. I want to read the third number. How to read data?
Usesscanf(). It will skip whitespace. ``` int a, b, c; if( sscanf(string, "%d %d %d", &a, &b, &c) == 3) printf("the third number is %d\n", c); ``` You can also use%*to suppress assignment of the two first numbers: ``` int a; if( sscanf(string, "%*d %*d %d", &a) == 1) printf("the third number is %d\n", a); ``` ...
I've come across this a few times recently: ``` if ((flags & PERFORM_DELETION_CONCURRENTLY) == PERFORM_DELETION_CONCURRENTLY) ... ``` What's the reason for the extra comparison? Why not this? ``` if (flags & PERFORM_DELETION_CONCURRENTLY) ... ``` My guess is that it's a leftover habit to silence warnings fro...
There is also the possibility that in the mask there is more than one bit set. In that case, the two comparisons have different semantics.
I have a simple makefile that compiles ap.cfile to an executable usinggccon Linux. Thep.cfile depends on aa.hfile. My makefile looks like this: ``` //makefile CC = gcc build: p.c a.h $(CC) -o out p.c clean: rm -f *.exe rebuild: clean build ```
Your makefile doesn't produce the files it promises to produce, namelybuild,cleanandrebuild. Since these targets are not files they should be marked asphony targets: ``` .PHONY: build clean rebuild ``` buildtarget should be: ``` build : out out : p.c a.h $(CC) -o $@ p.c ```
I'm observing an program and want to kill it, if it is for some time in the state "wait:executive". Here is a screenshot of the Process Explorer: How can I get that state by code?Or could maybe tell me somebody what that state exactly mean? This will may help me to find the right query to solve my problem.
It is not state of program but it's state of thread.One process can have many threads. You can callWaitForSingleObjectto determine some states. Also you can instantiate WMI using COM and selectingWin32_Thread class. Here is some example. More info here :How to determine that a win32 thread is either in Wait or Joi...
``` if((sem_init(sem, 1, 1)) == 1) perror("error initiating sem"); ``` If I include this line of code my program simply starts and exits. I just started learning how to use semaphores. I'm using cygwin and when this line is commented out the printf's ABOVE this print to console but when include this, nothing happens....
I figured out what was wrong. I was using data(struct) = shmat() before I was assigning any memory to data. That for some reason was stopping my 'printf' from working.
This question already has answers here:Closed10 years ago. Possible Duplicate:How to check for equals? (0 == i) or (i == 0)Is there a difference between i==0 and 0==i? I have seen many a times that people use theif(condition)asif(0==x)instead ofif(x==0). It is said to be a good practice but can someone explain why s...
The fact that it decreases readability is purely subjective. (I feel the same way though, but that's because I've been dealing withx==0more than the other way around, so I got used to it). It's done to prevent accidental assignment: ``` if(0=x) ``` will yield a compiler error, ``` if(x=0) ``` won't.
i need to manage a COM printer port by Tomcat webserver. I tried a lot of java solutions, for example RxTx library but i had a lot of troubles: when i switch off the printer the jvm crashed!! Now i would like to use an jvm external library linked by JNA, so i need aC or C++ library with raw methods to read and write t...
UseBoost Asio! Its guaranteed to be fully portable. Its also very reliable. I've actually used it in my own application (SMS sender through gsm devices using AT commands). Please also see:Access the serial port in a platform-independant way
i have a file hello.txt and a pointer *i pointing to the file, i have opened the file using c open(*i) function. i want to get the size of file using getpagesize(2) to read the content of the file and further write that content to a destination file. so getting the size of the file i required to now how big is the fil...
If you are using theopensystem function to open the file, you should look into thefstatfunction to get the size: ``` int fd = open(...); struct stat st; fstat(fd, &st); printf("File size: %ld bytes\n", st.st_size); ```
``` char ch[2]; ch[0] = 'h'; ch[1] = '\0'; ``` or can i just do ``` char ch[1]; ch[0] = 'h'; ``` in which '\0' would already be implied? The reason why i'm doing it this way is because my program has a loop in it in which i would constantly be changing this character and concatenating it to a longer string.
Assigning justch[0]will not assign zero to thech[1]. You can initialize both characters in the array with a string literal in a single line, like this: ``` char ch[2] = "h"; ``` This will put'h'intoch[0], and a terminating zero intoch[1].
I need to store random numbers between 500 and 600 to an array using a pointer and then print out those numbers. I get a segmentation error...core dump, I don't really understand what that means. The error happens after the printf statement ("%15d\n", aPtr[i]); ``` int main(){ int size; int j, i; int te...
i <= size;should bei < size; If you have an array of 50 items, the valid indices are [0,49].
I'm learning iOS but have an issue extracting data from a multidimensionalNSMutableArray, I've looked at various solutions but have not yet found one.. I have anNSMutableArraylike ``` { "service_0" = { "name" = "name1"; "description" = "description1"; }; "service_2" = { "name" = "name2"; "descripti...
Assuming that is an array of dictionaries, unlike in the question... ``` NSArray *newArray = [oldArray valueForKeypath:@"name"]; ``` You can make it mutable usingmutableCopy, if you wish.
I need to create an array that's size is determined by user input, and then has pointers to said array. All the array will hold is random numbers between 500-600. I can't seem to use malloc correctly. I am still new to C, so help is appreciated. ``` int main(){ int size; printf("Enter size of array"); ...
You only need: ``` int *aptr = malloc(sizeof(int) * size); ``` and then you can access it just like an array. ``` aptr[0] = 123; ```
I'm new to C and I'm wondering what the difference is between these two: ``` char* name; struct book *abook; ``` I know the struct constructs a book, but with the char how come the*is place before the variable name?
TYPE * variableName, TYPE* variableName and TYPE *variableName are all syntactically the same. It's a matter of notation how you use them. Personally I prefer the last form. It's simply because the star operator works on the token to the right of it. In a declaration like ``` TYPE* foo, bar; ``` only foo is a point...
I am very new to C and I am wondering if this is allowed and if so, how do I do it correctly? This code gives me tons of compiler errors. I am trying to create a structure with 3 character arrays (initialized to null characters'\0') and initialize one of these structs with the nameS. ``` struct Structure{ char ...
No. That is not allowed. Types (yourstruct Structureis a type) in C have no value. What has values are objects. You can create an object of a struture type and initialize all of it,recursively if needed, to 0 with what I call theuniversal zero initializer. ``` struct Structure { char array1[3]; char array2[...