question
stringlengths
25
894
answer
stringlengths
4
863
I've encountered a warning that I don't really understand. The warning is generated by comparing what I consider to be one unsigned with another unsigned. Here is the source: ``` #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <assert.h> int main() { uint8_t *arr = malloc(8); assert(arr)...
I had the same problem and I worked around it by using an intermediate variable: ``` uint8_t check = ~arr[2]; if (arr[3] != check) ```
I was just reading the classic K&R and encountered the following syntax: ``` printf("%.*s",max,s); ``` What is the meaning of"."here?When I don't apply a"."here,then whole string is printed,but when we don't apply a".",atmost max characters are printed.I will be really thankful if anyone could explain this.
In%.*s, the.*limits the number of bytes that will be written. If this were written with a numeral included, such as%.34s, then the numeral would be the limit. When an asterisk is used, the limit is taken from the corresponding argument toprintf. From C 2011 (N1570) 7.21.6.1 4, describing conversion specifications for...
This question already has answers here:Can a local variable's memory be accessed outside its scope?(21 answers)Closed10 years ago. How to return a local character array from one function ``` char* testfunction() { char array[] = "Hello World"; return array; } char main() { char* array = testfunction(); printf(" ...
You are returning a pointer which points to a local variable, whentestfunction()returnsarrayin main() becomes dangling pointer. usestd::stringinstead ``` #include <string> #include <iostream> std::string testfunction() { std::string str("Hello World"); return str; } int main() { std::cout << testfuncti...
Can someone explain the output of this program - ``` #include<stdio.h> #include<conio.h> #define FUDGE(k) k+3.14159 #define PR(a) printf(#a" = %d\t ",(int)(a)) #define PRINT(a) PR(a);putchar('\n') int main() { int x=2; PRINT(x*FUDGE(2)); printf(\n); PR(x*FUDGE(2)); return 0; } ``` OUTPUT - ...
The#operator is strange. It works before expanding the parameter. So when callingPR(x*FUDGE(2)),#is applied tox*FUDGE(2)beforeFUDGEis expanded.However, inPRINT(x*FUDGE(2)),FUDGEis expanded before passing it on toPR. WhenPRapplies#to it, it has already been expanded.
I have the following code to read an argument from the command line. If the string is in this form hw:1,0 I want to break. ``` gboolean parse_one_option (gint opt, const gchar * arg, GError ** err) { switch (opt) { case DEVICE: if (!strncmp(arg, "hw:", 3) && isdigit(arg[3]) && arg[4] == ',' && isdigit...
You need to#include <ctype.h>for this function/macro to be available.
typedef int (xxx)(int yyy);seems to define a function pointer namedxxxwhich points to a function with a integer parameteryyy. But I can't understand that syntax...Could any one give a good explanation? I findtypedef int xxx(int yyy);still works. Any difference between them?
This defines a function type, not a function pointer type. The pattern withtypedefis that it modifies any declaration such that instead of declaring an object, it declares an alias to the type the object would have. This is perfectly valid: ``` typedef int (xxx)(int yyy); // Note, yyy is just an unused identifier. ...
The same thing asFind SQLite Column Names in Empty Tablewith the exception that I have a view that is part of an attached database. Because the database is attached thePRAGMA table_info( your_table_name );solution doesnt work. Furthermore, trying to parse the query string is also ridiculous because it is a view query....
PRAGMA AttachedDbName.table_info(your_table_name) Another technique: prepare a statement of the formselect * from your_table_name;, then usesqlite3_column_count,sqlite3_column_nameet al. You don't need to actually run the statement, just prepare it.
How can I pass achar*array as a parameter, without creating one and initializing it? This code works (creating an initializing one): ``` char *messages[] = {"Zero", "One", "Two", "Three"}; printf("%s", messages[1]); ``` But it wont work if you pass it like so: ``` #include <stdio.h> void printElement1(char *messa...
You're just missing the type for your compound literal. Change that line to: ``` printElement1((char *[]){"Zero", "One", "Two", "Three"}); ``` and it will work fine.
I wrote a script for downloading a hdf5 file using libcurl, but I cannot find way to open it in c, I don't want to store it in disk and H5Fopen it. Is there a way to do the H5Fopen work on the downloaded memory buffer? Thanks:)
It is called File Image and you need recent HDF5 to do that: http://www.hdfgroup.org/HDF5/doc/Advanced/FileImageOperations/HDF5FileImageOperations.pdf
externis a storage class in C. How exactly does it work? The output of the code given below is 20. How is this the output? ``` #include <stdio.h> int main() { extern int a; printf("%d", a); return 0; } int a=20; ```
It means three things: The variable hasexternal linkage, and is accessible from anywhere in the program;It hasstatic storage duration, so its lifetime is that of the program (more or less); andThe declaration is just a declaration, not a definition. The variable must also be defined somewhere (either without theexter...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do...
Linux alternative toconio.his ncurses library. To install it search for packages:libncurses,libncurses-dev.
I've encountered a warning that I don't really understand. The warning is generated by comparing what I consider to be one unsigned with another unsigned. Here is the source: ``` #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <assert.h> int main() { uint8_t *arr = malloc(8); assert(arr)...
I had the same problem and I worked around it by using an intermediate variable: ``` uint8_t check = ~arr[2]; if (arr[3] != check) ```
I was just reading the classic K&R and encountered the following syntax: ``` printf("%.*s",max,s); ``` What is the meaning of"."here?When I don't apply a"."here,then whole string is printed,but when we don't apply a".",atmost max characters are printed.I will be really thankful if anyone could explain this.
In%.*s, the.*limits the number of bytes that will be written. If this were written with a numeral included, such as%.34s, then the numeral would be the limit. When an asterisk is used, the limit is taken from the corresponding argument toprintf. From C 2011 (N1570) 7.21.6.1 4, describing conversion specifications for...
This question already has answers here:Can a local variable's memory be accessed outside its scope?(21 answers)Closed10 years ago. How to return a local character array from one function ``` char* testfunction() { char array[] = "Hello World"; return array; } char main() { char* array = testfunction(); printf(" ...
You are returning a pointer which points to a local variable, whentestfunction()returnsarrayin main() becomes dangling pointer. usestd::stringinstead ``` #include <string> #include <iostream> std::string testfunction() { std::string str("Hello World"); return str; } int main() { std::cout << testfuncti...
I am trying to execute the following clearcase command through a c program. ``` system("ct pwv"); ``` But I'm getting this error. :permission denied. would you please suggest some solution to this problem. Thanks.
Try withcleartool: ``` system("cleartool pwv"); ```
This question already has answers here:What does the comma operator , do?(8 answers)Closed10 years ago. ``` int main(void) { int a=0, b=20; char x=1, y=10; if(a,b,x,y) printf("bye"); return 0; } ``` How does "if" condition in the above code work work? Would the value of "y" be only considered by "if"?
Yes, the value of the comma operator is the right operand. Because none of the other operands have side effects, this boils down toif (y).
I have a few threads, waiting on the sameepoll_fdwithepoll_wait(). The descriptors within epoll set are setup in this way: ``` struct epoll_event event; event.events = EPOLLIN | EPOLLONESHOT; event.data.fd = fd; ``` The purpose ofEPOLLONESHOTis to guarantee, that each descriptor is handled only in one thread at the ...
Seems like disabled descriptors don't receiveEPOLLHUP.
I am creating a program that can make mysql transactions through C and html. I have this query stringquery = -id=103&-id=101&-id=102&-act=Delete Extracting "Delete" by sscanf isn't that hard, but I need help extracting the integers and putting them in an array of intid[]. The number of-identries can vary depending o...
You can usestrstrandatoito extract the numbers in a loop, like this: ``` char *query = "-id=103&-id=101&-id=102&-act=Delete"; char *ptr = strstr(query, "-id="); if (ptr) { ptr += 4; int n = atoi(ptr); printf("%d\n", n); for (;;) { ptr = strstr(ptr, "&-id="); if (!ptr) break; pt...
What would be the best way to kill all the processes of a parent but not the parent? Let's say I have an undetermined number of child processes that I've forked and on a given alarm, in my signal handler, I'd like to kill all my child processes but keep myself running for various reasons. As of now, I am using kill(-...
One way to accomplish this is to deliver some signal that can be caught (notSIGKILL). Then, install a signal handler that detects if the current process is the parent process or not, and calls_exit()if it is not the parent process. You could useSIGUSR1orSIGUSR2, or perhapsSIGQUIT. I've illustrated this techniquehere...
I am trying to do this inc: ``` scanf("%d",a+i); ``` whereais an array of size10. Andiis counter for loop. So is this possible?
Absolutely: ifais anint*or an arrayint a[10], andiis between 0 and 9, this expression is valid. Thea+iexpression is the pointer arithmetic equivalent of&a[i], which is also a valid expression to pass toscanf.
This question already has answers here:printf specify integer format string for float(7 answers)Closed10 years ago. ``` main() { float a=10; float c; float b=5.5; c=a+b; printf("%d",c); } ``` The output of the above code is zero.Why is that? I am sorry if that is some really simple C concept, I a...
You need to use%f(or%eor%g, depending on your preferred format) instead of%dfor floating-point numbers. Indeed, using%dfor non-integers is "undefined behaviour". ``` printf("%f", c); ``` Alternatively, if you're trying to round the floating-point to an integer, you must cast it first. ``` printf("%d", (int) c); ```...
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question i don't understand the modulo operation in the following paragraph:--- when overflow occurs during an oper...
Imagine a clock that has values with a range [0..11] (12 distinct values), when you say the time is 14:00 you can also say it is 2pm, which is 14 mod 12. The same happens when an integer overflows (65,536 mod 65,536 is 0). Whether the answer is semantically correct in your application depends on the application.
I want to update the static controll (simple program that draws text on the window) every X seconds... The problem is, I dont know which part of WndProc is updating every time (so I can put a timer on it).. I've tried using threads, the problem is, it gets inside the thread, but doesnt create the text (the CreateWin...
if you want to update static text in x seconds, why don't you just useSetTimer, there's a sample hereSetTimer, which send a window message to WndProc every x seconds.
Is ther a way to use the names of the struct-members for initial a const instance ``` typedef struct { int i1; int i2; int i3; } info_t; //- GCC const info_t info = { .i1 = 1, .i2 = 2 } //- VS const info_t info = {1,2,0); ``` the GCC allows this handy way but Visual Studio causes a error C2143 "Syn...
It's calleddesignated initializerwhich is introduced in C99. But Visual Studio doesn't have support for C99 right now, so, no, you can't do it in Visual Studio then, you have to stick to the C89 way: ``` const info_t info = {1,2,0); ``` However, according toMSDNandInfoqon the roadmap of Visual Studio, there will be...
Is there a way to get the number of columns achar arrayhas? It's declared like this:static const char *countries[][2] = { ... }; But I want to get it dynamically, so without typing '2' myself
No, you have to pass the size along with the array. There might exist system/compiler/library dependent ways, but it's not a good idea to rely on such functionalities. If you're using the C++ standard library, you'd better usestd::vector, which carries more metadata, such as thesize()you're interested in.
Does OMP ensure that the contents of an dynamic array is up-to-date and is visible to all threads after an OMP barrier?
Yes. A barrier causes all threads' view of all accessible memory to be made consistent; that is, it implicitly flushes the entire state of the program.
I have: ``` char buffer[512 + 12]; ``` And I'm trying to forcebufferto be 16 bytes alligned (meaning - zero it's last 4 bits). So I tried: ``` buffer = (char*)(((uint32_t)buffer +12)) & ~0xF); ``` But I'm gettingincompatible types in assignment I'm guessing this is because char[] and char* aren't the same type. H...
Well you need to add 15 bytes, not 12, and it should be: ``` char _buffer[512 + 15]; char * const buffer = (char*)(((uintptr_t)_buffer + 15)) & ~0xF); ``` Note that the original buffer address can not be modified so we call the unaligned buffer_bufferand initialise a const aligned pointer,buffer, at the first align...
How will this program get executed? ``` #include <stdio.h> void main() { char a = 0xAA; int b; b = (int) a; printf("%d\n", a); b = b >> 4; printf("%x", b); } ``` [Question] I have problem in statementb = (int)a. Can you give the binary representation ofbwhenais stored in it?
For the statementb = (int)a;, we are typecasting acharto anint. Assuming thatcharis implicitly signed (NB: not always true!) and thatintis 32 bits, then thecharvalue0xAAgets widened with sign extension, so0xAAbecomes0xFFFFFFAAwhich is equivalent to-86in decimal.
Here is a piece of code: ``` int* linenump; // ... other stuff printf("----\n"); linenump = malloc(sizeof(int)); printf("*****\n"); ``` The program only print out----then stopped, pop up a window says that the program has stopped, I paste the code in VS then build&run it, no errors, the program works fine. It's a c...
You probably have some heap corruption somewhere earlier in the program but this is not showing up until this point. Run your code undervalgrindto identify the real problem.
How can i compile the contents of the clipboard, i tried piping the contentspbpaste | gccbut it did not work it gave the errori686-apple-darwin11-llvm-gcc-4.2: no input filesI have heard that i can use temporary file with the commandmktempbut I could not get it to work.
Using-xc -will allow you to processstdin: ``` gcc -xc - ``` You can see a live examplehere.
im writing a program that checks to see if different types of brackets match or not in C, i'm new to C so i understand that a segmentation fault is related to memory but unsure what how to solve my issue? the expected output would be someone would input the test_string such as and that would be a success while doing ...
The problem with your code was very likely identified by your compiler's warnings: you should see a lot of them, telling you that you are passing acharto a function expecting achar*. Thestrcmpfunction expects C strings, not simplychar*, meaning that there should be a null terminator after the last character of the st...
Assume I call a functionvoid foo (char* fileName);with the following call ``` foo("file.txt"); ``` Is it ok to callfoo()with: ``` foo(strcat("file.txt",".binary")); ``` Will it cause any memory problems? As I understand the only problem I can face is a stack overflow, right?
The problem is, forstrcat, the first parameter will be used to store the result, so it must be large enough to contain the concatenated resulting string. In your example, the first parameter is a string literal, which can't be modified, not to say having enough space.
asxmlCleanupParser()from the very good libxml2 is not thread-safe, my question is (and I have no possibility to check it out), how much Memory (rough number) is lost toxmlParseFile()and -more importantly- is this memory loss cumulating over many calls toxPF()?
Despite the fact, thatmalloc()andfree()or whatever memory handling implementations are not necessarily thread safe in C < 11, there's always the problem of shared/global memory. File handles to the same file in different threads aren't that bad as long as they're read only. However, starting with libxml2 2.4.7, you m...
The output of the following program is 50 on gcc. How is it possible as x is constant variable and *p is x itself as p is a constant pointer pointing to value at x. Where as turbo c gives compiler error. Is it an undefined behaviour? please explain. ``` #include<stdio.h> int main() { const int x = 25; int *...
It is possible to change it but the behavior is undefined, as its mentioned in the standard! Its in c11 under 6.7.3 If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined. If an attempt is made to refer to an obj...
More of a matter of curiosity than anything. Basically I want to know if it's possible to declare multiple function pointers in a line, something like: ``` int a = 1, b = 2; ``` With function pointers? Without having to resort totypedef. I've triedvoid (*foo = NULL, *bar = NULL)(int). Unsurprisingly, this didn't...
Try as follows: ``` void (*a)(int), (*b)(int); void test(int n) { printf("%d\n", n); } int main() { a = NULL; a = test; a(1); b = test; b(2); return 0; } ``` EDIT: Another form is array of function pointers: ``` void (*fun[2])(int) = {NULL, NULL}; void test(int n) { printf("%d\n",...
Let's say I have a char pointer called string1 that points to the first character in the word "hahahaha". I want to create a char[] that contains the same string that string1 points to. How come this does not work? ``` char string2[] = string1; ```
"How come this does not work?" Because that's not how the C language was defined. You can create a copy usingstrdup()[Note thatstrdup()is not ANSI C] Refs: C string handlingstrdup() - what does it do in C?
Achar**always confuses me. The following code generates a segmentation fault. Explain please... ``` #include<stdio.h> #include<string.h> #include<stdlib.h> int main() { char** nameList; nameList = malloc(4*sizeof(char*)); nameList[0] = malloc(12); //not sure if needed but doesn't work either nameList...
AfternameList = malloc(4*sizeof(char*));you have: nameList[0] = trash nameList[1] = trash nameList[2] = trash nameList[3] = trash AfternameList[0] = "Hello ";you have nameList[0] = "Hello" nameList[1] = trash nameList[2] = trash nameList[3] = trash So when you dostrcat(nameList[1], "World");it's ...
I'm learningCand trying to write a very simple program. Here is my code: ``` #include <stdio.h> int[] getNumbers( int x, int y, int z ); int main() { int[] theNumbers = getNumbers(5,6,7); return 0; } int[] getNumbers( int x, int y, int z) { int[] numbers = { x, y, z }; return numbers; } ``` I can...
This is how you declare an array inC: ``` int a[SIZE]; ``` [The example you posted is howC#andjavadeclares arrays] Also, as others have noted, there are several issues with your posted code: You can't return an array inC(only a pointer to an array or struct)You should not return references to local variables (use ...
This question already has answers here:strcmp behaviour in 32-bit and 64-bit systems(3 answers)Closed10 years ago. So I have this (not the full code) char list[1000][10]; strcpy(list[0],"ab"); printf("%d\n",strcmp(list[0],"ab")); and the strcmp is returning 0. Can somebody explain why it's doing so? Thanks in ad...
Thestrcmpmethod will return 0 iflist[0]contains "ab" in this case. It returns: Returns an integral value indicating the relationship between the strings:A zero value indicates that both strings are equal.A value greater than zero indicates that the first character that does not match has a greater value in str1 than...
I am working on a communication medium between two computers. They are both on the same network. I know the remote ip of each device. I am trying to write a C program that acts as a server on one machine, and a client on the other. I am trying to make this connection using TCP protocol on port 311 from the client. I...
Usually you bind to the special ip address called INADDR_ANY. This allows your server to be available to incoming connections on any interface. This way you can connect to your server via localhost/loopback if you're on the same machine or via any of the external interfaces the server computer may have - regardless ...
I'm currently writing a little program but I keep getting this error when compiling error: empty character constant I realize it's because I'm trying to replace a valid char with empty spacec[i]=''but I have not been able to find another way to represent it.
You can usec[i]= '\0'or simplyc[i] = (char) 0. The null/empty char is simply a value of zero, but can also be represented as a character with an escaped zero.
What's the best way to scan a folder and be notified when a new file has been created. I'm using Windows XP and I need a solution in C++ or C. I need to send those files via HTTP to the server. Wondering what would be the best solution for this? open to using some third party library. Thank you for your help.
Use FindFirstChangeNotification function with FILE_NOTIFY_CHANGE_FILE_NAME as last argument. It will return you a handler which then you need to observe with WaitForSingleObject. This second function will wait for a specified amound of time or for a notification from a handler. If you would like to break it manualy,...
Can I use Goto to jump into other functions? for example ``` void x(){ printf("hello"); } void y(){ printf("hi"); } int main(){ /*assume that all var are declared */ scanf("%d",&input); if(input == 1) goto y(); else(input == 2) goto x(); } ```
You cannot usegototo branch into a different function; agotomay only branch within the current function. You would simplycallthe functionsx()andy().
I would like to check if I have openssl installed using C/C++ code. Is it even possible? I mean, is there a macro, or something which will be a portable way of doing this? Thanks
The following will work on Windows and Linux: ``` #ifdef WIN32 libHandle = LoadLibrary( libraryName ); #else libHandle = dlopen( libraryName, RTLD_LOCAL | RTLD_NOW ); #endif ```
In Java, it is required by the compiler to name your files<Classname>.java. In C, does it matter what the file name is?
No, the source files can in principle be called anything. However, the name should reflect the contents of the file for readability. Header files also don'thaveto be called the same as the corresponding source files; they justshould.
I would like to check if I have openssl installed using C/C++ code. Is it even possible? I mean, is there a macro, or something which will be a portable way of doing this? Thanks
The following will work on Windows and Linux: ``` #ifdef WIN32 libHandle = LoadLibrary( libraryName ); #else libHandle = dlopen( libraryName, RTLD_LOCAL | RTLD_NOW ); #endif ```
In Java, it is required by the compiler to name your files<Classname>.java. In C, does it matter what the file name is?
No, the source files can in principle be called anything. However, the name should reflect the contents of the file for readability. Header files also don'thaveto be called the same as the corresponding source files; they justshould.
I am writing some functions which will be called with file descriptor arguments in production code. During testing, how can 'inject' something which will let me confirm that the function makes the intended calls tolseek,writeand so on?
Since you're on Linux, you can simply define the functions you want to stub inside your test program. The linker will deem these functions as local, and ignore those that will be dynamically loaded.I used this successfully on Linux and Solaris with gcc. Make sure to store the parameters they are invoked with and not ...
``` qsort(words, size1, size2, compareWords); ``` inside compare words: ``` int compareWords(const void *ac, const void *bc) ``` this works: ``` char const *a = *(const char **)ac; ``` these don't (agets some garbage values): ``` char const *a = ac; char const *a = (const char *) ac; ``` what is the rationa...
Whenqsorting an array of T, your comparison function must convert itsconst void*pointers toconst T*, because T can't be taken by value. Ifwordsis an array ofchar*orchar const *, you have to convert the arguments tochar* const *orchar const * const *respectively, it's natural when said this way.
Hi I'm working on a project in c I have 3 IPs and every IP has a weight, I want to return the IP's according to its weights using the random function,,,, for example if we have 3 IP's : X with weight 6,Y with weight 4 and Z with weight 2, I want to return X in 50% of cases and Y in 33% of cases and Z in 17% of cases,...
Get a random between 0 and 1000000 for example. Then check, if it's smaller then 500000 then choose x, if its between 500000 and 830000 choose y and if its between 830000 and 1000000 choose z.
I came aroundthissimilar question. But the advantage I have is that i know that each string is 260 char long. Any hope? ``` int noOfStrings = sizeof(stringArray)/sizeof(stringArray[0]); ``` This doesn't work.
As it says. You cannot (unless it's a variable local to the function). Because of the way arrays are passed they degrade to pointers and all size information is lost (outside of the context of where the array was created because the compiler cannot make assumptions about it anymore). You must explicitly pass the size...
This question already has answers here:Segmentation fault with strcpy() [duplicate](7 answers)Closed10 years ago. ``` int main() { char *s="Hello"; *s="World"; printf("%s\n",s); } ``` Why does the above program result in a segmentation fault?
``` int main() { char *s="Hello"; // makes 's' point to a constant *s="World"; // modifies what 's' points to printf("%s\n",s); } ``` The first line of code makesspoint to a constant. The second line tries to modify whatspoints to. So you are trying to modify a constant, which you can't do because a ...
The following code gives me different outputs on different systems: ``` int fd = open(filename, O_RDWR | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO); byte_t data[] = { 0x00, 0x01, 0x02, 0x03, 0x0a, 0x0b 0x0c, 0x0d }; write(fd, data, sizeof(data)); ``` On the mac a 'hexdump' of the filename gives what I would expect ``` ...
It looks like the hexdump utility swaps the bytes. Please show the hexdump command you used in each platform. To confirm it, test with ``` byte_t data[] = { 'a', 'b', 'c', 'd', 'e' } ``` and compare the hexdump and cat(or type) outputs.
If someone is talking about solving a problem with the C programming language, and they say that dynamically created structures is the way to go, what are they likely to be referring to? Is there another name for this perhaps?
The assignment requires that you use dynamic memory allocation for your data structures. Your program may not use statically allocated memory, that is, for exampleint array[65536];. Instead all these needs to be allocated on demand using themalloc/calloc/realloc(and supposedly be freed using thefree).
As known: ``` ptr = malloc(size); ``` or in C++ ``` ptr = new Klass(); ``` will allocate size bytes on the heap. It is less efficient than on the stack. But after the allocation, when we access it: ``` foo(*ptr); ``` or ``` (*ptr)++; ``` Does it have the same performance as data on the stack, or still slower?...
The only way to definitively answer this question is to code up both versions and measure their performance under multiple scenarios (different allocation sizes, different optimiziation settings, etc). This sort of thing depends heavily on alotof different factors, such as optimization settings, how the operating sys...
This is my very first experience with the MPG123 library, and I'm a bit confused. I found a small example about using this library, with libao, but when i try to compile I got an error. This is the example code "Play local files":http://hzqtc.github.io/2012/05/play-mp3-with-libmpg123-and-libao.html I compile with:gc...
You have an old version of the mp123 library, according to the release notes it was added in 26.0.26https://github.com/gypified/libmpg123/blob/master/NEWS.libmpg123 26.0.26 - Added mpg123_encsize(). - Added flag MPG123_SKIP_ID3V2.
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed7 years ago. Here is a question I can not explain clearly. Which option is wrong and why? ``` (A) a += (a++); (B) a += (++a); (C) (a++) += a; (D) (++a) += (a++); ``` What is the di...
Which option is wrong and why? All of them are wrong, and that's because the first two invoke undefined behavior, and the last two don't compile. (And if they did, they would invoke UB as well.)
I need a global array of function pointers, and came up with this: ``` static int (*myArray[5])(); ``` if i am right, this is "a global array of pointers to functions returning int". Is that right? Or is it "an array of pointers to functions returning a static int". I just need a quick answer.
Should be made as simple as possible, but not simpler: ``` typedef int (*t_MyFunc)(); t_MyFunc g_MyFuncArray[5]; ``` Andg_MyFuncArraycan be static if you wish (butyou should notif you want a global variable): ``` static t_MyFunc g_MyFuncArray[5]; ``` In a header file you should write: ``` extern t_MyFunc g_MyFun...
I have a standalone application (client) and the server which is talking my own protocol. Now, I have to implement encryption so third parties can't see any customer's data. I thought about using OpenSSL, but OpenSSL is not designed to work with asynchronous sockets in Edge Triggered mode (server side is written in C ...
SSL/TLS has nothing to do with the way sockets are handled, I assume you were talking about OpenSSL. OpenSSL can be used with sockets in edge-triggered mode, see for example how libevent (bufferevent_openssl.c) or libcurl are using it. You have several options though, as PolarSSL, CyaSSL and GnuTLS all support async...
``` char c[] = {'a','b','c'}; int* p = &c[0]; printf("%i\n", sizeof(*p)); //Prints out 4 printf("%i\n", sizeof(*c)); //Prints out 1 ``` I am extremely confused about this section of code. Both p and c represent the address of the array c at the 0th index. But why does sizeof(*p) print out 4? Shouldn't it be 1?
Becausepis of typeint *, so*pis of typeint, which is apparently 4 bytes wide on your implementation. And use%zufor printingsize_t(whatsizeofyields) if you don't want your program to invoke undefined behavior.
Is there any situation where a complete type in a translation unit can become an incomplete type? The following statement in the footnote of theC11 standard(Section 6.2.5) prompted this question. A type may be incomplete or complete throughout an entire translation unit, or it may change states at different points wi...
A example of a complicated situation would be the following ``` extern double A[]; double* f(void) { extern double A[5]; enum { a = sizeof(A), }; //< A has complete type return A; } enum { b = sizeof(A), }; //< A has incomplete type: error double A[5]; enum { c = sizeof(A), }; //< A has complete type ```
I want to store some data as a matrix of integers. For simplicity let's say I want to store this data in an array of integers. After each app launch I want to fill my model using this array. So the question is How to store arrays of integer in sandbox? I don't want to write and rewrite data, maybe only once at first s...
Plists and NSCoding are used for the simple integers as well. However, you could just use the NSUserDefaults - that is the simples way: ``` [[NSUserDefaults standardUserDefaults] setObject:myArray forKey:@"AppData"]; ``` Makes it easy to retrieve later from anywhere as well.
I have some code that loops through a set a values and calls a function with each value. like yay... ``` for (int i=0; i<limit; i++) {booleanReturn |= doFunc(i);} ``` Just curious, there isn't a compiler that will short circuit that |= right (Not execute doFunc(i) because booleanReturn is already TRUE?) I am guess...
Operator|=is the compound ofoperator |notoperator ||. The former does not short-circuit. And no operator||=exists. So the answer to your question is negative.funcmustbe called if it has side effects. If it does not have side effects, then according to theas-if rulethe implementation is free to do anything as long as y...
I have an expression ofnlike(30 - n(n - 1)) / 2n. And I want search the possible n which will be my answer only when the result is an integer. Is there any way to decide whether the result of this expression is an integer or not. The only way that I can come up with is(in pseudo code ) : ``` for float n <- 1 to 100 ...
You can use%to compute the remainder. ``` int denom = 2 * n; int numer = 30 - n * (n - 1); if (denom) { if (numer % denom == 0) { then good to go } } else { /*...denominator is 0! */ } ```
When I create multiple threads from a process, then does each thread have its own stack, or is it that they share the stack of their parent process. What happens when a thread makes a system call? Do threads also maintain their own kernel stack like processes?
Yes threads have their own stacks and their own kernel stacks (e.g. linux). When a thread makes a system call, you trap into kernel mode (from user mode), you pass the arguments to the kernel, the arguments are checked, the kernel does w/e it needs to do (in the kernel stack), returns the final value back to the thre...
Currently i have this gtk2 code: ``` GList *input_devices = gdk_devices_list(); while(input_devices) { GdkDevice *device = (GdkDevice*)input_devices->data; for(int i = 0; i < gdk_device_get_n_axes(device); i++) { GdkDeviceAxis* axis = &device->axes[i]; printf("[%f .. %f]\n", axis->min, axis->max); } ...
The axis limit API accidentially ended up as private, upstream is aware of it and looks into making it publically available in GTK+ 3.10.
I have GCC running on my Ubuntu operating system. I wrote a small program in C and tried compiling it. Its output was ana.outfile like it would do on Windows. How can I make it put out a Linux executable?
a.outisthe executable (assuming you've done full compilation rather than just generation of object files but that's the most likely case). To run it, use (from a shell): ``` ./a.out ``` If you want to give it a different name, simply rename it, or better: ``` gcc -o actualname myprog.c ``` to get an executable cal...
This question already has answers here:C++ difference between 0 and 0.0(4 answers)C++: difference between 0. and 0.0?(5 answers)Closed10 years ago. I just saw this for the first time. The source code I'm looking at is in C ``` if( rate < 0.){ ... } else{ ... } ``` What happens ifrate=0?
0.is a literal of typedouble(and value zero). By contrast,0is a literal of typeint.
In my code I have a struct like this: ``` struct fileinfo { /* ... */ bool hashed; char hash[20]; } ``` Each function that processes astruct fileinfodoes only read the value ofhashif and only ifhashedis set. My program writes a couple of thesestruct fileinfo's into a temporary file to be used later on: ...
I usually justmemsetthe whole thing before using. ``` memset( &info, 0, sizeof(info) ); ```
I am trying to learn ncurses and was wondering if I can create my own custom colors. I am aware that by usinginit_color(), I can modify any pre-defined colors in the ncurses library. But, is there a way I can define a new color with custom RGB values?
init_color()is the only way to define new colors but the number of colors and color pairs available depends on the terminal you are using. Many terminals can support up to 256 colors but on most systems the default TERM value isxtermwhich only supports 8. xterm can be compiled with 256 color support and I think gnom...
I have done the following: Added the path to my include folder under Paths and Symbols->includes tabThe header file now appear in my project folder under includesThe #include files no longer give errors as the project can see the .h files that it needsAfter build I get the following error:fatal error: services.h: No ...
In Eclipse import a new make file project. Then link the appropriate libraries.
How do I constantly get user input (strings) until enter is pressed in C just likestringclass in C++? I don't know the input size so I can't declare a variable of fixed size or even I can't allocate memory dynamically usingmalloc()orcalloc(). Is there any way to implement this as a separate function?
As H2CO3 said, you should allocate a buffer withmalloc(), then resize it withrealloc()whenever it fills up. Like this: ``` size_t bufsize = 256; size_t buf_used = 0; int c; char *buf = malloc(bufsize); if (buf == NULL) { /* error handling here */ } while ((c = fgetc(stdin)) != EOF) { if (c == '\n') break; if (buf...
I am usingtwo mutexesin my C program, I want both of them to be of type: PTHREAD_MUTEX_ERRORCHECK Other properties of both mutexes to be set as default. Can I use a singlepthread_mutexattr_t mutexAttrib;with its "type" property set as above, to initialize both the mutexes? Is it safe?
Yes, it is safe. Thepthread_mutexattr_tattribute is only used at mutex creation time, and is not modified bypthread_mutex_init(), nor is it needed after initialization (ie. you can alsopthread_mutexattr_destroy()it later)
I am calling a shell script from a c program. I want this script to return multiple values which I want to store in a structure of my c program. For instance say 'a.c' calls 'a.sh', I want 'a.sh' to return the values to be stored in variables 'x' and 'y' which are a part of struct 's' in 'a.c'.
You cannot "return" values from a shell script, other than the single integer (often limited to 8 bits) of exit status that processes have (assuming a Unix-like system, now). What you typically do is interpret thestandard outputof the external program, which you can easily read into your C program by usingpopen()to r...
When I create multiple threads from a process, then does each thread have its own stack, or is it that they share the stack of their parent process. What happens when a thread makes a system call? Do threads also maintain their own kernel stack like processes?
Yes threads have their own stacks and their own kernel stacks (e.g. linux). When a thread makes a system call, you trap into kernel mode (from user mode), you pass the arguments to the kernel, the arguments are checked, the kernel does w/e it needs to do (in the kernel stack), returns the final value back to the thre...
Currently i have this gtk2 code: ``` GList *input_devices = gdk_devices_list(); while(input_devices) { GdkDevice *device = (GdkDevice*)input_devices->data; for(int i = 0; i < gdk_device_get_n_axes(device); i++) { GdkDeviceAxis* axis = &device->axes[i]; printf("[%f .. %f]\n", axis->min, axis->max); } ...
The axis limit API accidentially ended up as private, upstream is aware of it and looks into making it publically available in GTK+ 3.10.
I have GCC running on my Ubuntu operating system. I wrote a small program in C and tried compiling it. Its output was ana.outfile like it would do on Windows. How can I make it put out a Linux executable?
a.outisthe executable (assuming you've done full compilation rather than just generation of object files but that's the most likely case). To run it, use (from a shell): ``` ./a.out ``` If you want to give it a different name, simply rename it, or better: ``` gcc -o actualname myprog.c ``` to get an executable cal...
This question already has answers here:C++ difference between 0 and 0.0(4 answers)C++: difference between 0. and 0.0?(5 answers)Closed10 years ago. I just saw this for the first time. The source code I'm looking at is in C ``` if( rate < 0.){ ... } else{ ... } ``` What happens ifrate=0?
0.is a literal of typedouble(and value zero). By contrast,0is a literal of typeint.
In my code I have a struct like this: ``` struct fileinfo { /* ... */ bool hashed; char hash[20]; } ``` Each function that processes astruct fileinfodoes only read the value ofhashif and only ifhashedis set. My program writes a couple of thesestruct fileinfo's into a temporary file to be used later on: ...
I usually justmemsetthe whole thing before using. ``` memset( &info, 0, sizeof(info) ); ```
I am trying to learn ncurses and was wondering if I can create my own custom colors. I am aware that by usinginit_color(), I can modify any pre-defined colors in the ncurses library. But, is there a way I can define a new color with custom RGB values?
init_color()is the only way to define new colors but the number of colors and color pairs available depends on the terminal you are using. Many terminals can support up to 256 colors but on most systems the default TERM value isxtermwhich only supports 8. xterm can be compiled with 256 color support and I think gnom...
I have done the following: Added the path to my include folder under Paths and Symbols->includes tabThe header file now appear in my project folder under includesThe #include files no longer give errors as the project can see the .h files that it needsAfter build I get the following error:fatal error: services.h: No ...
In Eclipse import a new make file project. Then link the appropriate libraries.
How do I constantly get user input (strings) until enter is pressed in C just likestringclass in C++? I don't know the input size so I can't declare a variable of fixed size or even I can't allocate memory dynamically usingmalloc()orcalloc(). Is there any way to implement this as a separate function?
As H2CO3 said, you should allocate a buffer withmalloc(), then resize it withrealloc()whenever it fills up. Like this: ``` size_t bufsize = 256; size_t buf_used = 0; int c; char *buf = malloc(bufsize); if (buf == NULL) { /* error handling here */ } while ((c = fgetc(stdin)) != EOF) { if (c == '\n') break; if (buf...
I am usingtwo mutexesin my C program, I want both of them to be of type: PTHREAD_MUTEX_ERRORCHECK Other properties of both mutexes to be set as default. Can I use a singlepthread_mutexattr_t mutexAttrib;with its "type" property set as above, to initialize both the mutexes? Is it safe?
Yes, it is safe. Thepthread_mutexattr_tattribute is only used at mutex creation time, and is not modified bypthread_mutex_init(), nor is it needed after initialization (ie. you can alsopthread_mutexattr_destroy()it later)
I am calling a shell script from a c program. I want this script to return multiple values which I want to store in a structure of my c program. For instance say 'a.c' calls 'a.sh', I want 'a.sh' to return the values to be stored in variables 'x' and 'y' which are a part of struct 's' in 'a.c'.
You cannot "return" values from a shell script, other than the single integer (often limited to 8 bits) of exit status that processes have (assuming a Unix-like system, now). What you typically do is interpret thestandard outputof the external program, which you can easily read into your C program by usingpopen()to r...
I have an array of char but values is decimal representation of a character. example: ``` char bytes[4]={50,48,49,51} ``` how to convert this to get char array like this: ``` char bytes1[4]={2,0,1,3} ```
When you create your array you should use character literals: ``` char bytes[4] = {'2', '0', '1', '3'}; ``` These are stored in memory in the character encoding your compiler is using which converts the character to a number. If you want to get the decimal value represented by the character when read by a human (i....
I want to know what exactly will happened if I change the memory return fromgetenv I know this is not a good code. I knowsetenvby the way. Like: ``` char *new_path = "/home/user/dev/myTry1"; char *path = getenv("PATH");// assume there is : PATH=/home/user/dev/myTry //now *path = "/home/user/dev/myTry" memcpy(path...
No, you can't. From thedocumentation: Conforming applications are required not to modify environ directly, but to use only the functions described here to manipulate the process environment as an abstract object.
I'm developing a chess game in C just for practicing. At the beginning of the game, the user can type 4 things: ROW<whitespace>COL (i.e.2 2)'h' for help'q' to quit How can I use ascanfto expect 2 integers or 1 char?
Seems like it would be most sensible to read a whole line, and then decide what it contains. This will not include usingscanf, since it would consume the contentsstdinstream. Try something like this : ``` char input[128] = {0}; unsigned int row, col; if(fgets(input, sizeof(input), stdin)) { if(input[0] == 'h' &&...
This question already has answers here:Printing array elements(6 answers)Closed10 years ago. The expected output of the following C program is to print the elements in the array. But when actually run, it doesn't do so. ``` #include<stdio.h> #define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0])) int array[] ...
In the comparison ``` d <= (TOTAL_ELEMENTS-2) ``` TOTAL_ELEMENTShas typesize_tsodis converted to unsigned. For, say,sizeof(size_t)==4, this makes the test ``` 0xffffffff < 5 ``` which fails, causing the loop to exit. If you really want to start your loop counter from -1 ``` d <= (int)(TOTAL_ELEMENTS-2) ``` wou...
In C it is not normally possible to use'forprintfof a string. However, I have text which are full of double quote", and I need to escape all of them as ``` printf("This is \"test\" for another \"text\""); ``` Is it possible toprintfin a way without escaping". I mean using another character for wrapping the string.
Not recommended, but you can use a macro: ``` #include <stdio.h> #define S(x) #x int main() { printf(S(This "is" a string (with nesting)!\n)); } ``` This prints ``` This "is" a string (with nesting)! ``` Now the delimiters are balanced()characters. However, to escape single),", or'characters, you have to writ...
I cross-compiled a firmware withopenwrt, and a file is strange namedlibbfd.hand I compiling failed, I have ever seen it. Inlibbfd.hline 83: ``` 79 #define BFD_HOST_64BIT_LONG @BFD_HOST_64BIT_LONG@ 80 #define BFD_HOST_64BIT_LONG_LONG @BFD_HOST_64BIT_LONG_LONG@ 81 #if @BFD_HOST_64_BIT_DEFINED@ 82 #define BFD_HOST_64_BI...
@VARIABLES@are replaced with values during configuration on the target system. Seethis page of the autoconf manual. Did you do the typical: ``` ./configure make ``` To build it? Those should have constant values.
This question already has answers here:What is the difference between char s[] and char *s?(14 answers)Closed10 years ago. I have learned that the traditional way of declaring a character array is as follows: ``` char c[] = "John"; ``` However, I have also noticed that you can declare it as: ``` char *c = "John"; ...
In your first example,cis an array ofchar. But in: ``` char *c = "John"; ``` chere is not an array but a pointer (typechar *) to a string literal. Pointers and arrays are different types in C. Below is a good link if you want to learn about pointers and arrays: http://www.torek.net/torek/c/pa.html
I think I found a bug in VS2010 (C / C++), but it seems so obvious, I cannot believe it.(in the vein ofSelect isn't Broken). Please let me know if this is a bug, or if I'm missing something: ``` int main(void) { int x; // Declare a variable x; for(int i=0, x = 10; i<5; ++i) // Initialize X to 10. No way a...
``` int i=0, x = 10; ``` You just declared a secondxvariable scoped to theforloop. The outerxvariable is not affected.
Good day everyone I have a quick question.. How do I make fscanf read the whole entire file? Let's say I have the files settings.txt ``` setting1 = 1 setting2 = 2 setting3 = 3 ``` How do I parse those into C programming Variables? ``` int setting1, setting2,setting3; ``` I tried by simple doing this: ``` fscanf...
What about reading each line withfgets()and parsing their content withsscanf()like in this example:https://stackoverflow.com/a/861822/1150918? :) Also, personally for such kind of configs i'd prefer Lua or something tiny and simple like that. Built-in syntax check, C API and small interpreter size.
now writing complicatedclassand felt that I use to muchCRITICAL_SECTION. As far as I know there are atomic operations for some types, that are always executed without any hardware or software interrupt. I want to check if I understand everything correctly. To set or get atomic value we don't needCRITICAL_SECTIONbec...
You don't need locks round atomic data, but internally they might lock. Note for example, C++11'sstd::atomichas ais_lock_freefunction.boolmay not be atomic. Seehereandhere
Is there a way/tool to automatically remove blank lines on kdevelop Version 4.3.1? For instance, this: ``` tmpTime.tm_year = RTC_Time->bYear1 + RTC_Time->bYear; tmpTime.tm_mon = RTC_Time->bMonth; tmpTime.tm_mday = RTC_Time->bDay; ``` would become this: ``` tmpTime.tm_year = RTC_Time->bYear1 + RTC_Time->bYear; tm...
Regarding my comment above, here is a better picture highlighting why I think the referenced page will help:
This question already has answers here:Error: lvalue required in this simple C code? (Ternary with assignment?)(4 answers)Closed10 years ago. ``` #include <stdio.h> int main() { int a = 1, b; a ? b = 3 : b = 4; printf("%d, %d", a, b); return 0; } [user@localhost programs]$ gcc -Wall v...
It has to do with operator sequencing. What the compiler thinks you're doing is ``` (a ? b = 3 : b) = 4 ``` which obviously is incorrect. Instead, why not put thebon the left side, and get only the value to assign using the conditional expression, like ``` b = a ? 3 : 4; ```
This question already has answers here:Unnecessary curly braces in C++(14 answers)Closed10 years ago. I found in a programm that code fragment ``` { Aux_U16 = 16; } ``` so the question is : why there a this curly brackets. No keyword like if or switch are visible. So what function have curly brakets in ...
It's sometimes nice since it gives you a new scope, where you can more "cleanly" declare new (automatic) variables. Those braces are controlling the variable scope.And since variables with automatic storage are destroyed when they go out of scope. It is simply to isolate a block of code that achieves a particular (s...
This question is an extensiontothis previously asked question: I implemented thesolution given byjxhwith following params: ``` SO_KEEPALIVE = Enabled TCP_KEEPIDLE = 120 secs TCP_KEEPINTVL = 75 secs TCP_KEEPCNT = 1 ``` Then why the server still waits forever for client to respond? Also I found out on internet...
Because the client hasn't exited yet, being still in STOPPED state, and therefore hasn't closed its connections either.
I'm working on a multi-threaded client-server application designed for usage in the enterprise internal network. I uselibeventfor asynchronous I/O (several pthreads with one evconnlistener/bufferevent object per thread) andOpenSSLfor cryptography. Now I need to determine mechanism of monitoring of the established co...
I am afraid there is no way to list the objects watched by an event base, let alone list only the established connections and their status. You could try to patch libevent for your needs, or you can keep score out of the connections accepted outside of libevent.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed10 years ago.Improve this question What will be output if you will compile and execute the following c statement? `...
The docs forprintfexplain why this happens Return valueUpon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings). printf("This is")returns 7 so yourifcondition succeeds.