question
stringlengths
25
894
answer
stringlengths
4
863
I have read this subject:Relationship slow system call with signal and everything isn't clear for me. Especially I don't understand this part of answer because I don't see a problem with included source code. Please explain me. Thanks in advance. Anyway, back to the question. If you're wondering why the read doesn't fail with EINTR the answer is SA_RESTART. On most Unix systems a few system calls are automatically restarted in the event of a signal.
The OP was expecting thereadcall to return an error code because it was interrupted by a signal. In the case of thereadsystem call, the OS automatically restarts this system call in the event of a signal, so no error was returned.
Is it possible to get the file name (and path) from a call tomkstemp()? And if "yes", how?
From themkstempmanual page: The last six characters of template must be "XXXXXX" and these are replaced with a string that makes the filename unique. Since it will be modified, template must not be a string constant, but should be declared as a character array. So you declare an array and pass it to the function, which will modify it, and then you have the filename in the array.
``` #include <stdio.h> #include <unistd.h> int main() { while(1) { fprintf(stdout,"hello-out"); fprintf(stderr,"hello-err"); sleep(1); } return 0; } ``` The above program prints "hello-err" but not "hello-out", why?
You can try to use ``` setbuf(stdout, NULL); ``` to stop buffering of thestdoutor else you can flush like this: ``` fprintf(stdout,"hello-out"); fflush(stdout); fprintf (stderr, "hello-err"); ``` From the C 11 standards §7.21.5.2 part 2: If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.
In SDL2 when you resize the window by dragging the corners during runtime, a window resized event is triggered and can be used like this: ``` SDL_Event e; int width, height; SDL_PollEvent(&e); if(e.type == SDL_WINDOWEVENT && e.window.event == SDL_WINDOWEVENT_RESIZED) { width = e.window.data1; height = e.window.data2; } ``` If I resize a window manually like this: ``` SDL_SetWindowSize(window, myWidth, myHeight); ``` (documentation) Will this trigger a window event like above?
Yes, just likeSDL_SetWindowFullscreen ().SDL_SetWindowSize ()triggers window events. Technically, I think it just resizes the window, which is treated as if the user manually resized it.
Below shown is the code snippet i am using. Should I allocate space using malloc before doing dlopen? ``` void* pvHandle = NULL; /* Dynamically loading library */ pvHandle = dlopen ("libame.so", RTLD_LAZY | RTLD_GLOBAL); if (!pvHandle) { pszError = dlerror(); cout << "Error : " << pszError; } ``` Please help me clear this doubt. Thanks in Advance.
No,dlopenreturns an opaque handle to the library, you do not need to allocate any memory yourself.
``` #include <stdio.h> void main(){ short num[3][2]={3,6,9,12,15,18}; printf("%d %d",*(num+1)[1],**(num+2)); } ``` answer is 15 15 !! Can any one of you explain it to me please !
*(num+1)[1]and**(num+2)are different ways of writing the same thing. That is, the third element ofnum.The type ofnumisshort (*)[2]. That is, it is a pointer to an array of 2shortvalues. With these two facts in mind we can work out what the code is doing. Below assumes a 32 bit system for simplicity. num+1. Sincenumpoints to twoshortvalues, using pointer arithmetic,num+1will be 4 bytes (2 shorts) afternum.(num+1)[1]. The array index gives the second element starting fromnum+1. That means another 4 bytes pastnum+1and hence 8 bytes pastnum.Accessing 8 bytes afternumgives exactly15.
C++11 hassleep_for. But C standard doesn't have the equivalent. I think I can write a wrapper to call such C++ functions from C. And there are useful libraries like Boost Filesystem and Asio. These are more complicated but I can also write the wrapper. Could it be reinventing the wheel? Could it be a bad idea?
An issue with this is, if you want to write C wrappers which call Boost functions, what do you do if an exception is thrown? You basically have to swallow it in the caller before it reaches C, but its a bit awkward to properly report it to C then and there are quite a few types of exceptions. Usually people use C instead of C++ when they specifically want the extra portability or cannot provide all the C++ dependencies for some reason. If you want to write a C program that uses boost::filesystem, why not just compile it as C++? You will have a lot less exception handling boiler plate code to write, and less can go wrong.
I am trying to produce an output as double quoted input . For e.g if the argument that is passed in str() is somenamethen the output should be"name"which is not happening in below code. ``` #include<stdio.h> #include<string.h> #define str(s) #s #define newline printf("\n") int main() { printf("Your double quoted code is : %s ",str(GHOST)); newline; } ``` Output : GHOST
What is happening is that the quotesarebeing added, but they are consumed as part of the syntax of the language. Because, you need to pass astringlike"GHOST"toprintf, not just an identifier. If you want quotes to appear when you run the program, I would make it ``` printf("Your double quoted code is : \"%s\" ",str(GHOST)); ``` instead. The escaped quotes in the format string will appear in the output.
I am trying to use execvp to execute unix commands with given flags. My array, argv, might contain these elements: ``` {"ls", "-a"} ``` I am then passing this array to ``` execvp(argv[0], argv); ``` How can I safely appendNULLonto the end of the argv array so execvp will know where to terminate?
You have 2 elements in your array. Simply allocate three elements instead and set the last one to NULL: ``` char* args[] = {"ls", "-a", NULL}; execvp(path, args); ``` Or, since you mentionmalloc(): ``` char** args = malloc(3 * sizeof args[0]); args[0] = "ls"; args[1] = "-a"; args[2] = NULL; execvp(path, args); free(args); ```
This question already has answers here:Why isn't sizeof for a struct equal to the sum of sizeof of each member?(13 answers)Closed8 years ago. ``` typedef struct{ short age; int money; char c; }Persoana; int main(void){ Persoana *a = malloc(sizeof(Persoana)); printf("%ld %ld",sizeof(a->money),sizeof(a->age)); printf(" %ld\n",sizeof(*a)); } ~ ``` The code prints "4212".4 and 2 are ok but how so 12???
It's to demonstrate padding issues done by the compiler. What it (the compiler) did here was to align each part of the struct to 4 byte word boundaries (=> 4*3 = 12 bytes) instead of packing them into 9 bytes. This is performed by the compiler to allow for data member access that respects the target CPU memory access patterns.
What limitations are imposed when a C module instantiates its own corestruct(as a singleton) and user code accesses this usingextern VS. has user code instantiate the singletonstructinstead ? For example, one limitation of the former is that the user cannot choose the allocation method. EDITThe reason for the question is that I have hit some walls with approach no. 1 in the past (C language limitations) but have now forgotten what they were!
If you want make absolutely sure, that the singleton "stays single", let the module handle its creation.If the singleton's implementation details shall stay hidden, you also want to let the module handle it and optionally just return an opaque pointer to the singleton'sinternalstruct, so the user has nothing more than a "handle". The handle however is not necessary as its a singleton :-).
In my makefile, I added parameters to linker flags as a variableBOOTLOAD ``` LDFLAGS += -Wl,--section-start=.bootloader=$(BOOTLOAD) ``` If i writeBOOTLOAD = 0x3800in makefile everything is working fine. But i want to pass this variable from C code, so i tried to define it like#define BOOTLOAD 0x3800. But the linker cannot find it. How should i passBOOTLOADfrom C file?
Instead of "passing" the macro from a C source file (which is possible but not easy), you could instead ask the preprocessor to define the macro when compiling with the-Doption: ``` gcc -DBOOTLOAD=$(BOOTLOAD) -c source_file.c ``` I recommend you check theGCC preprocessor command line option referencefor more information about the-Doption. Itispossible to search a specific source file to the macro definition and then set a makefile variable to the extracted value, but it's easier to do it the other way around as shown above.
Current effort: 1, hidapi-1.1.jar 2, GetRawInputDeviceList hidapi-1.1.jar is aborted in my app for some reason. GetRawInputDeviceList isn't stable in Win10 referringhttps://stackoverflow.com/questions/32419314/getrawinputdevicelist-and-getrawinputdeviceinfo-fail-to-work-in-win10 I wonder is there any other method to reach my goal? OS is windows, programming language is not limited.
You can use the hotplug event notification API present inlibusb. Documentation is here:http://libusb.sourceforge.net/api-1.0/hotplug.html In a nutshell, this API lets your program get a callback whenever a device is connected or disconnected, and lets you filter for just the devices you care about (seelibusb_hotplug_register_callback). Note that the hotplug API isn't supported on all OSes; if it isn't, you will have to fallback to enumerating devices usinglibusb_get_device_list.
Sometimes in GDB I want to see the control flow that got the program to where it is now. Simply put, how do I make GDB print the last x lines executed?
This is yet another use case forReverse Debugging. You should start process record and replay at some point:(gdb) recordWhen you want to see last executed lines you can go backwards like this:(gdb) reverse-step 3or(gdb) reverse-next 3Use this answerhttps://stackoverflow.com/a/1545732/72178to actually print the next N executed lines.
i was trying to compare two strings using strcmp() , and in the case they're equal the function returns -1 (meaning they are not equal) , i dont know whats wrong . ``` int main() { char password[]={'6','6','6','6','6','6'}; char passmatch[6]; int i =0; for(i ; i<6 ; i++) { passmatch[i]='6'; } printf("\n"); if(strcmp(password,passmatch)==0) { printf("Strings are equal"); } else { printf("String are'nt equal"); } return 0; ``` }
In C, strings need to be null terminated in order to be used with the standard library. Try putting a '\0' at the end, or make a string literal in the "normal" way, e.g.char password[] = "666666";, then the language will automatically put\0at the end.
i was trying to compare two strings using strcmp() , and in the case they're equal the function returns -1 (meaning they are not equal) , i dont know whats wrong . ``` int main() { char password[]={'6','6','6','6','6','6'}; char passmatch[6]; int i =0; for(i ; i<6 ; i++) { passmatch[i]='6'; } printf("\n"); if(strcmp(password,passmatch)==0) { printf("Strings are equal"); } else { printf("String are'nt equal"); } return 0; ``` }
In C, strings need to be null terminated in order to be used with the standard library. Try putting a '\0' at the end, or make a string literal in the "normal" way, e.g.char password[] = "666666";, then the language will automatically put\0at the end.
i was trying to compare two strings using strcmp() , and in the case they're equal the function returns -1 (meaning they are not equal) , i dont know whats wrong . ``` int main() { char password[]={'6','6','6','6','6','6'}; char passmatch[6]; int i =0; for(i ; i<6 ; i++) { passmatch[i]='6'; } printf("\n"); if(strcmp(password,passmatch)==0) { printf("Strings are equal"); } else { printf("String are'nt equal"); } return 0; ``` }
In C, strings need to be null terminated in order to be used with the standard library. Try putting a '\0' at the end, or make a string literal in the "normal" way, e.g.char password[] = "666666";, then the language will automatically put\0at the end.
While I was looking for MMX functions, I noticed that two of them,_m_emptyand_mm_empty, haveexactly the same definition. So why do they both exist ? Is one of them older than the other ? Is there a difference that is not mentioned in the manual ?
Differences would/should be pointed out in the documentation. TheMSDNis more precise. They explicitly mention this: A synonym for_mm_emptyis_m_empty.
I want to reduce the resolution of a video from 1024*768 to 800*600. I found on the web ffmpeg, and the library swscale (I use in C. And I found some informations on the web, but nothing about how to reduce the resolution of a video nor about which functions to use How can I do ?
Seethisorthisexample code. Usesws_getContext() to set up a scaler, andsws_scale() to convert one frame or slice.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed8 years ago.Improve this question I was doing a simple server client console chat box in winsock2.Then my colleague asked me if i can do a single server multi client connection in which the SERVER will be in TCP and the CLIENTS will be in UDP. Also the client does not know the IP of the server but knows the port number i.e the Client has to search for the server and then connect it.All this over a LAN. Could any one tell me how to do such program or if possible could post a code for reference.
TCP and UDP are 2 completely separated worlds. No, you can't have a TCP server communicating with UDP clients.
If I have the next function ``` Stack *construct_stack(void) { Stack *instance = (Stack *) malloc(sizeof(Stack)); // Stuff... return instance; } ``` It's sort of "constructor". But I'v been having problems with the "destructor". If I do this I get an error. ``` void destruct_stack(Stack **st) { // Stuff... free(st); } ``` Some idea?
``` void destruct_stack(Stack **st) { // Stuff... free(*st);//free the pointer which st points to *st = NULL;//set it to null } ``` And You don't need to cast the result of malloc:Do I cast the result of malloc?
I'm trying to assign an enum value to an enum variable with its "Full" name in c. Is this possible?: ``` enum EnumActions{ SHIFT, REDUCE, ACCEPT, GOTO , ERROR_A }; int main(){ enum EnumActions __actionType; __actionType = EnumActions::SHIFT; //this is giving an error __actionType = SHIFT;//this works fine } ``` any ideas how I can get the first one working?
The answer is NO, in C it's not possible. You could do it with a C++11enum classor with C++namespace's: If you want to make it easier to understand you can use a prefix: ``` enum EnumActions{ ACTION_SHIFT, ACTION_REDUCE, ACTION_ACCEPT, ACTION_GOTO , ACTION_ERROR_A }; //... __actionType = ACTION_SHIFT; ```
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed8 years ago.Improve this question I was doing a simple server client console chat box in winsock2.Then my colleague asked me if i can do a single server multi client connection in which the SERVER will be in TCP and the CLIENTS will be in UDP. Also the client does not know the IP of the server but knows the port number i.e the Client has to search for the server and then connect it.All this over a LAN. Could any one tell me how to do such program or if possible could post a code for reference.
TCP and UDP are 2 completely separated worlds. No, you can't have a TCP server communicating with UDP clients.
If I have the next function ``` Stack *construct_stack(void) { Stack *instance = (Stack *) malloc(sizeof(Stack)); // Stuff... return instance; } ``` It's sort of "constructor". But I'v been having problems with the "destructor". If I do this I get an error. ``` void destruct_stack(Stack **st) { // Stuff... free(st); } ``` Some idea?
``` void destruct_stack(Stack **st) { // Stuff... free(*st);//free the pointer which st points to *st = NULL;//set it to null } ``` And You don't need to cast the result of malloc:Do I cast the result of malloc?
I'm trying to assign an enum value to an enum variable with its "Full" name in c. Is this possible?: ``` enum EnumActions{ SHIFT, REDUCE, ACCEPT, GOTO , ERROR_A }; int main(){ enum EnumActions __actionType; __actionType = EnumActions::SHIFT; //this is giving an error __actionType = SHIFT;//this works fine } ``` any ideas how I can get the first one working?
The answer is NO, in C it's not possible. You could do it with a C++11enum classor with C++namespace's: If you want to make it easier to understand you can use a prefix: ``` enum EnumActions{ ACTION_SHIFT, ACTION_REDUCE, ACTION_ACCEPT, ACTION_GOTO , ACTION_ERROR_A }; //... __actionType = ACTION_SHIFT; ```
I am used to C# or Java. How could the following statement be correct in C? printf("aaa" "bbb"); On my Xubuntu 15.04 with GCC 4.9. It outputs: aaabbb And as I tried, below works too! ``` CHAR *p = "aaa""bbb""ccc"; printf(p); ``` It outputs: ``` aaabbbccc ``` I think there should be a comma but in that way, the first string will be treated as a format string. So, is this syntax legal?
Yes it is legal syntax because oftranslation phase 6in ISO C99, #5.1.1.2 Translation phases: Adjacent string literal tokens are concatenated.
I can't seem to find this anywhere, but does strcspn() return -1 when str1 does not contain str2? For example, say I have: ``` strcspn(argv[1], " "); ``` Will the function return -1 or something else if argv[1] does not contain a space?
Seestrcspn reference on cplusplus.com ``` strcspn(str1, str2) ``` returnsThe length of the initial part of str1 not containing any of the characters that are part of str2. This is the length of str1 if none of the characters in str2 are found in str1. So your callstrcspn(argv[1], " ");should return the length ofargv[1].
The following C code, ``` #include <stdio.h> int main() { char *source="{\"address\":\"10.10.2.130\"}"; char ip[32]; sscanf(source, "{\"address\":\"%s\"}", ip); printf("%s\n%s\n", source, ip); return 0; } ``` I expect to extract 10.10.2.130 in ip, but the output shows 10.10.2.130"}, why? Thanks.
Each part of the format string is executed without looking forward to see what's to come. So the%smatches the rest of the string. The subsequent characters in the format string just fail to match because you're trying to match characters that have already been read. You may want something like%[^\"]s, which additionally stops reading if a quote is encountered.
This question already has answers here:Dividing 1/n always returns 0.0 [duplicate](3 answers)Closed8 years ago. Why does output equal zero in this code? Number 1 with weight of 2, number two with weight of 3 and number three with weight of 5. I can not understand why output = 0. ``` #include <stdio.h> int main () { float A ,B, C ,MEDIA=0 ; scanf("%f%f%f",&A ,&B,&C); MEDIA+=1/2*A + 1/3*B + 1/5*C; printf("MEDIA = %.1f", MEDIA ); return 0; } ```
MEDIA+=1/2*A + 1/3*B + 1/5*C; Because1/2,1/3and1/5will be evaluated as 0. Since they are integers. Either write 1.0/2,1.0/3and1.0/5instead. So the compiler will know to treat the result asfloat. Or ``` MEDIA+=A/2 + B/3 + C/5; ``` P.S. Maybe I am wrong but if I understood correctly what you wrote at the description then I think your calculation of the weighted average is incorrect. It should be something like (A*2 + B*3 + C*5)/10
I tried to supply strftime the modifier %k which is not in the list, and it prints 11, what does strftime do, when I supply a modifier that is not in its list ?
From the C standard ofstrftime: 6 If a conversion specifier is not one of the above, the behavior is undefined. You can see thelist of format specifiersfor strftime. So what you are getting is anundefined behavior. See themanualwhich says about %k %kThe hour (24-hour clock) as a decimal number (range 0 to 23); single digits are preceded by a blank. (See also %H.) (TZ)
I am used to C# or Java. How could the following statement be correct in C? printf("aaa" "bbb"); On my Xubuntu 15.04 with GCC 4.9. It outputs: aaabbb And as I tried, below works too! ``` CHAR *p = "aaa""bbb""ccc"; printf(p); ``` It outputs: ``` aaabbbccc ``` I think there should be a comma but in that way, the first string will be treated as a format string. So, is this syntax legal?
Yes it is legal syntax because oftranslation phase 6in ISO C99, #5.1.1.2 Translation phases: Adjacent string literal tokens are concatenated.
I can't seem to find this anywhere, but does strcspn() return -1 when str1 does not contain str2? For example, say I have: ``` strcspn(argv[1], " "); ``` Will the function return -1 or something else if argv[1] does not contain a space?
Seestrcspn reference on cplusplus.com ``` strcspn(str1, str2) ``` returnsThe length of the initial part of str1 not containing any of the characters that are part of str2. This is the length of str1 if none of the characters in str2 are found in str1. So your callstrcspn(argv[1], " ");should return the length ofargv[1].
I would like to use regexes in a linux kernel module. I have the regexes ready, and I tested them in user space withregex.h. I know thatregex.his a user space library, but is there a kernel alternative? Thanks! Edit:I am trying to find C code in SMTP connections for a university project.
The kernel already has a regexp engine; the functions are declared inkernel/trace/trace.h. It is part of the linux trace framework, and could relatively easily be adapted. You can see where it is currently used(identifier search). Note also someone has got there before you.Thel7-filterkernel componentclassifies L7 traffic based on (inter-alia) regex matching the packets. Their regex implementation hasa man page. You could also pass the packets to userspace via a socket usinglibipq, classify them, and pass them back. This is an easier approach, but slower, and apparently isn't what you want (but might be useful to another reader).
I'm rewriting some Mac code that embeds a freeware library originally written in C. The compiler is complaining that since I'm usinglong double, I should usefabslrather thanfabs. So I went and changed them. However, readinga few pageson the topic it seems that there should be no difference, that ever since C99, there is a type generic macro that inserts the correct call based on type. So perhaps I am using the wrong dialect? Does anyone know what the Compiler Default is in xcode7, and whether it has the generic macro?
The generic macro is defined in<tgmath.h>, so you need to#include it, as shown in the following snippet: ``` #include <tgmath.h> #include <stdio.h> int main() { long double ld = 3.14; double d = 3.14; float f = 3.14f; printf("%Lf %lf, %f\n",fabs(ld), fabs(d), fabs(f)); return 0; } ``` It compiles flawlessly with ``` gcc -Wall -Wextra a.c -oa -std=c99 ```
``` #include <stdio.h> int main(){ int b = 10,a; if (a = 5){ printf("%d",b); } } ``` In the above program if statement always returns true even if i change the data type of the variable "a" from "int" to "char". What does = mean in the if statement??
=is anassignment operatorin C. According to C99 6.5.16: An assignment operator stores a value in the object designated by the left operand.An assignment expression has the value of the left operand after the assignment, but is not an lvalue. It means that expressiona = 5will return5and therefore instructions insideifblock will be executed. In contrary, if you replaced it witha = 0then0would be returned by assignment expression and instructions insideifwould not be executed.
I have a piece of code like this: ``` struct mystruct *v; size_t sz; sz = sizeof(*v); ``` Whatszis expected to be?What's the difference withsizeof(struct mystruct)?What's the point of havingszin the stack (instead eg, of a#define)?
sizeofis a compile time operator, the compiler replaces it with the relevant number. so in runtime there will be a number there - no pointer. sizeof(*t)gives you the size ofTwheretisT*. so let's assumechar* c;sizeof(c)will give the size of thepointerwhilesizeof(*c)will give the size of thecharacter, which is 1 byte.
Is it possible torefresh a button boxhaving a number of buttons, when a specific action is implemented such as Submit and Delete? On Submit a new button should be added and on Delete (after selecting the button), the button should get destroyed (not hiden). The GUI is designed usingGladeinGtk-2and codes are in theClanguage.
Usegtk_box_pack_start()or...pack_end()or any of the other related methods to add a button to the box. Usegtk_widget_destroy()on a button to remove it from its container and destroy it at the same time.
I was trying to read a 20x20 maze from a .txt file into a 2D array. Because fgets also reads the NUL and \n, I left room for 22 characters per row (20 for maze). However, it does not work the way I intended. When I tested this code to print just a single array (maze[0] for example), it seems that the whole file is copied into a single array. What have I done wrong? ``` #include <stdio.h> #define BUFLEN 22 int main() { FILE *fp = fopen ("maze.txt", "r"); char maze[22][20]; int i = 0; int j = 0; for (i=0; i<20; i++){ fgets(maze[i], BUFLEN, fp); } for (j=0; j<20; j++){ printf("%s", maze[j]); } fclose(fp); return 0; ``` }
You declared your datatype backwards. You need: ``` char maze[20][BUFLEN]; ``` That will give you 20 "rows" ofBUFLENcharacters.
I want the user to decide the size of my arrayCan i do it?I tried: ``` #define max 8 int a[max]; ``` But then, user cant change a constantI tried: ``` int i, a[i]; ``` But it gives an errorHelp?
Assuming your compiler supports C99 andvariable-length arrays, then the following code will work: ``` int size; fputs("Array size? ", stdout); scanf("%d", &size); int array[size]; ``` If your compiler does not, you'll have to usemalloc. ``` int size; int* array; fputs("Array size? ", stdout); scanf("%d", &size); array = malloc(size * sizeof(*array)); /* do stuff with array */ free(array); /* don't forget to free() when finished */ ``` Some implementations supportalloca, which allocates on the stack like a variable-length array would, but this is non-standard.
I was trying to read a 20x20 maze from a .txt file into a 2D array. Because fgets also reads the NUL and \n, I left room for 22 characters per row (20 for maze). However, it does not work the way I intended. When I tested this code to print just a single array (maze[0] for example), it seems that the whole file is copied into a single array. What have I done wrong? ``` #include <stdio.h> #define BUFLEN 22 int main() { FILE *fp = fopen ("maze.txt", "r"); char maze[22][20]; int i = 0; int j = 0; for (i=0; i<20; i++){ fgets(maze[i], BUFLEN, fp); } for (j=0; j<20; j++){ printf("%s", maze[j]); } fclose(fp); return 0; ``` }
You declared your datatype backwards. You need: ``` char maze[20][BUFLEN]; ``` That will give you 20 "rows" ofBUFLENcharacters.
I want the user to decide the size of my arrayCan i do it?I tried: ``` #define max 8 int a[max]; ``` But then, user cant change a constantI tried: ``` int i, a[i]; ``` But it gives an errorHelp?
Assuming your compiler supports C99 andvariable-length arrays, then the following code will work: ``` int size; fputs("Array size? ", stdout); scanf("%d", &size); int array[size]; ``` If your compiler does not, you'll have to usemalloc. ``` int size; int* array; fputs("Array size? ", stdout); scanf("%d", &size); array = malloc(size * sizeof(*array)); /* do stuff with array */ free(array); /* don't forget to free() when finished */ ``` Some implementations supportalloca, which allocates on the stack like a variable-length array would, but this is non-standard.
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed8 years ago.Improve this question I tried to compile the following program ``` void rec(int n) { if(n>0) { rec(n-1) print ("n"); } } ``` Herenvalue is a big no. like1000000. o/p is :segmentation fault (core dumped) Can anyone explain what exactly happens here ? Thanks.
For programs compiled with GCC with default settings stack size is about 2 megabytes. So you are limited in recursive calls by your stack size, because every not-tail recursion function call reduces free stack memory. Thats why you will get stack overflow whennis big number.
When you callmethod_missingwith first parameter as'string'instead of:symbolyou get this cryptic error message: ``` BasicObject.send(:method_missing, 'any-method') ArgumentError: no id given from (pry):3:in `method_missing' ``` When you look at thesource codefor method_missing ``` static VALUE rb_method_missing(int argc, const VALUE *argv, VALUE obj) { rb_thread_t *th = GET_THREAD(); raise_method_missing(th, argc, argv, obj, th->method_missing_reason); UNREACHABLE; } ``` there is nothing with error messageArgumentError: no id given. Where it comes from?
raise_method_missing()does raise that argument error: ``` static void raise_method_missing(rb_thread_t *th, int argc, const VALUE *argv, VALUE obj, int last_call_status) { // ... if (argc == 0 || !SYMBOL_P(argv[0])) { rb_raise(rb_eArgError, "no id given"); } // ... } ```
I have recently been learning C, and have come across a few return statements with logical operators in them, ie ``` return(statement LOGIC statement); ``` Where the statements evaluate to True or false (ie 1 or 0), and LOGIC is a logical operator like &&, || etc. Is this good coding practice, as it seems a bit off to me, would it not be better to use if/else if statements?
There is nothing wrong with this coding practice and actually you don't need the parentheses. Beware of lazy evaluation. return foo1() && foo2() If the return value of the call tofoo1is falsefoo2never gets called.
In C there is the way to initialize array or struct with predefined list of values: ``` #define STRUCT_DUMMY_VAL1 "dummy", 21, 2.3 struct dummy d = {STRUCT_DUMMY_VAL1}; #define INT_ARRAY_VAL1 1,2,3 int a[] = {INT_ARRAY_VAL1}; ``` Is there the way to pass the predefined list of arguments to function? ``` #define IP_ADDR 192,168,3,3 ip_addr_assemble(u8_t,u8_t,u8_t,u8_t); void dosmth(){ u32_t ip = ip_addr_assemble(IP_ADDR); // Compile error } ```
No problem with such code. GCC ate it without any warnings. The problem is with my compilier. You can test on ideonehttps://ideone.com/0VIkz5
Recently, I've been learning algorithms, so I try to code leetcode. There are some programs like ``` int pop(struct node ** top_pt){ //弹出数据并且释放内存 if (*top_pt==NULL){ printf("stack overflow\n"); exit(0); } struct Node *top=*top_pt; //满递增 int res=top->val; *top_pt=top->Next; free(top); return res; ``` } so, what is the difference between the pointers like*and**?
Nothing really, a pointer is a pointer is a pointer, it's how youuseit that makes all the difference. This pattern (passing a pointer to a pointer to something) is a ways of emulatingpass by reference(which C doesn't have) for a pointer. This means that when you change the pointer using e.g.*top_ptr = top->Nextthat change will be in the calling function as well.
I have written a small pager in C using ncurses on Linux. Because this pager is only for myself, and because I find it easier to read text with the whole page in reverse video, I want to find a way to change the entire screen colour to reverse video, i.e. not just until the last character before the newline. Something like the difference between the commandsemacsandemacs -r.
This gave me black text on a white background. ``` #include <ncurses.h> int main(void) { initscr(); if (has_colors()) { assume_default_colors( COLOR_BLACK, COLOR_WHITE); start_color(); } printw("line 1\n"); printw("line 2\n"); printw("line 3\n"); printw("press enter"); getch(); endwin(); return 0; } ```
Suppose we have the scenario.. ``` char *a[] = {"abcd","cdef"}; ``` I want to know the sizeof of string "abcd", I dont want to usestrlen. Please answer me how to get sizeof of the string "abcd"?
As"abcd"is compile-time known array of typechar[5]and it is written directly into source code, you could just use: ``` sizeof("abcd") ``` Notice, that: ``` sizeof("abcd") == strlen("abcd") + 1 ``` as the former includes terminatingNULcharacter.
I just created new console application project byDev-C++ 4.9.9.2. But Project Options(Alt+P) not working andError: Access violation at address 0012F64B. Write of address 0012F64B. How to fix this problem.
Its Dev-C++ problem , update it .Details
In ANSI C, which of the following is faster, and why? Or doesn't it make a difference because it will be compiled to the same? ``` int main(void) { double width = 4.5678; double height = 6.7890; double perimeter = width + width + height + height; return 0; } ``` Or the following: ``` int main(void) { double width = 4.5678; double height = 6.7890; double perimeter = width * 2 + height * 2; return 0; } ```
The compiler will figure that out, and use whatever is fastest. Possibly even computeperimeterat compile time. You should concentrate on writing the most readable code. That helps both humans and the compiler to understand your intentions.
for example, in c, converting -1234 to unsigned char would become 46: ``` int main(){ int a=-1234; unsigned char b=a; printf("%d\n",b); return 0; }; ``` I want to convert the code to java version, now the code is: ``` public class Test{ public static void main(String[] args){ int a=-1234; int b=(a%(Byte.MAX_VALUE-Byte.MIN_VALUE+1))+(a<0?(Byte.MAX_VALUE-Byte.MIN_VALUE+1):0); System.out.println(b); } } ``` Is there any faster (or simpler) way to do this (e.g.:bitwise operation)?
``` int a = -1234; a = (byte) a & 0xFF; System.out.println(a); //Output: 46 ```
This question already has answers here:Copying structure in C with assignment instead of memcpy() [duplicate](5 answers)Closed8 years ago. I often use memcpy to copy a struct in C/C++. I see someone use equal sign directly copy struct in C/C++. For example: ``` struct A { char* name; int value; }; struct B { struct A happy[10]; }; struct A a1, a2; struct B b1, b2; memcpy(&a1, &a2, sizeof(struct A)); b1 = b2; ``` What's the efficiency difference between memcpy and equal sign ?
Now that the c++ tag has beed removed, we are talking C and not C++. Assuminga1anda2being variables of the samestructtype ``` memcpy(&a1, &a2, sizeof(struct A)); ``` and ``` a1 = a2; ``` do exactly the same thing. But it is entirely up to the compiler if the assignement operatoractuallyusesmemcpyor not.
I just created new console application project byDev-C++ 4.9.9.2. But Project Options(Alt+P) not working andError: Access violation at address 0012F64B. Write of address 0012F64B. How to fix this problem.
Its Dev-C++ problem , update it .Details
In ANSI C, which of the following is faster, and why? Or doesn't it make a difference because it will be compiled to the same? ``` int main(void) { double width = 4.5678; double height = 6.7890; double perimeter = width + width + height + height; return 0; } ``` Or the following: ``` int main(void) { double width = 4.5678; double height = 6.7890; double perimeter = width * 2 + height * 2; return 0; } ```
The compiler will figure that out, and use whatever is fastest. Possibly even computeperimeterat compile time. You should concentrate on writing the most readable code. That helps both humans and the compiler to understand your intentions.
for example, in c, converting -1234 to unsigned char would become 46: ``` int main(){ int a=-1234; unsigned char b=a; printf("%d\n",b); return 0; }; ``` I want to convert the code to java version, now the code is: ``` public class Test{ public static void main(String[] args){ int a=-1234; int b=(a%(Byte.MAX_VALUE-Byte.MIN_VALUE+1))+(a<0?(Byte.MAX_VALUE-Byte.MIN_VALUE+1):0); System.out.println(b); } } ``` Is there any faster (or simpler) way to do this (e.g.:bitwise operation)?
``` int a = -1234; a = (byte) a & 0xFF; System.out.println(a); //Output: 46 ```
This question already has answers here:Copying structure in C with assignment instead of memcpy() [duplicate](5 answers)Closed8 years ago. I often use memcpy to copy a struct in C/C++. I see someone use equal sign directly copy struct in C/C++. For example: ``` struct A { char* name; int value; }; struct B { struct A happy[10]; }; struct A a1, a2; struct B b1, b2; memcpy(&a1, &a2, sizeof(struct A)); b1 = b2; ``` What's the efficiency difference between memcpy and equal sign ?
Now that the c++ tag has beed removed, we are talking C and not C++. Assuminga1anda2being variables of the samestructtype ``` memcpy(&a1, &a2, sizeof(struct A)); ``` and ``` a1 = a2; ``` do exactly the same thing. But it is entirely up to the compiler if the assignement operatoractuallyusesmemcpyor not.
I am trying to compile the code for one of the projects and the source file uses autoreconf for generating the makefiles. " autoreconf --verbose --force --make " The problem is that this somehow generates the makefiles that uses the compiler as GCC. I want it to generate the configuration files with a different compiler. How can I do it? I can issue the command as make CC= but this throws an error in the libtool that is used later on. Thank You
Typicallyautoreconfjust regenerates theconfigurescript and the autoconf makefile templates, it doesn't create any actual makefiles. Makefiles get created whenconfigureis run, and that's when you want to override the compiler: ``` configure CC=clang CXX=clang++ ``` that should create makefiles that useCC=clangandCXX=clang++
In python, I'm able to build a string using this method: ``` >>> s = "%s is my name" %("Joe") >>> s 'Joe is my name' ``` Is there a similar way to do this in C++? I know C has ``` printf("%s is my name", "Joe") ``` But that's for printing to standard out. Ideally I'd like something like the Python example. Thanks! EDIT: Is there a name for this kind of thing? I couldn't think of what to google!
The sprintf command works like printf, but has an extra parameter at the front. The first parameter is an array of characters of where to store the string instead of printing it. ``` char chararray[1000]; sprintf(chararray,"%s is my name","Joe"); ``` http://www.cplusplus.com/reference/cstdio/sprintf/
According tothisquestion, gcc's-lcommand requires your library to be named libXXX.a. Is there a way to link a static library using a different command with gcc? The goal is to avoid this lib- prefix.
Just pass the library as in input file like so: ``` gcc main.c yourlibrary.a -o prog ```
This question already has answers here:Stringification - how does it work?(2 answers)Closed8 years ago. My first time seeing stringification and token pasting. I feel like it could be a good tool for this macro: ``` #define MY_NUMBER 3 #define MY_STRING "the number three: ##MY_NUMBER" printf("%s\n", MY_STRING); ``` should output: ``` the number three: 3 ```
try this ``` #define S_(x) #x #define S(x) S_(x) #define MY_NUMBER 3 #define MY_STRING "the number three: " S(MY_NUMBER) ```
I mostly use Java for programming and I used Eclipse as an (IDE). Now, I would like to add CDT to use c to program network sockets. I followed the stepshere i.e., first I downloaded Xcode, then added the plug in "C/C++ Development Tools" I don't know how to create a c project, when I clicked on File > New > Project, there is no option to choose c/c++ project. I also, tried thesuggested solution, but the problem still occurs I'm using mac OS X Yosemite. Is there something I'm missing? Thanks
You might have Java 6 installed. Check the version and update to Java 7 at least. Eclipse site says "A Java 7 JRE/JDK is required" for Eclipse Mars(4.5).
I want to get achararray values usingscanf. I used this code: ``` // get first array printf("first length:\n"); scanf("%d", &f_l); printf("first number:\n"); for(i=0 ; i<=f_l ; i++) { scanf("%c", &first[i]); } //start test printf("first number is:\n"); for(i=0 ; i<=LEN ; i++) { printf("(%c | %d)", first[i],i); } ``` but when I print the array, I found a\nin the first place (first[0]), and the other chars starts fromplace[1]instead! why is that, and how to fix it?
This is because a'\n'is left in the buffer when you doscanf()forf_l. Use a trailing space, it should work ``` for(i=0 ; i<=f_l ; i++) { scanf(" %c", &first[i]); } ```
I'm trying to make a linked list for a bookshelf, but when I compile it says ``` In file included from libreria.c:3:0: libreria.h:8:2: error: unknown type name ‘Book’ Book* next; ^ ``` Like if Book is not defined. this is the header file ``` #ifndef LIBRERIA_H #define LIBRERIA_H typedef struct Book { char author[50]; char title[50]; int year; Book* next; } Book; void newbook(Book* book); #endif ``` What is the problem?
Inside of your struct definition, the typedef forBookhasn't been defined yet, so you need to usestruct Bookin that instance: ``` typedef struct Book { char author[50]; char title[50]; int year; struct Book* next; } Book; ```
I'm using the C interface of igraph, and sometimes, while debugging I would like to see the content of someigraph_vector_tvariables as well asigraph_matrix_t. Is there some GDB pretty printer available like those available for STL containers (std::vector<T>usually?)
No, there isn't, but you can try callingigraph_vector_print()from withingdbif that is possible. Alternatively, you can access thestor_beginmember ofigraph_vector_t-- this is a pointer to the memory area that hosts the contents of the vector.stor_endpoints to the end of that area, andendpoints right after the last element of the vector - so, the "useful" part of the vector is betweenstor_beginandend.
This question already has answers here:problems with char array = char array(2 answers)Closed8 years ago. Well here is my first post. I've been trying to do this choice choosing thing and I want the user to choose only numbers instead of typing them down (easier) but when I want the numbers to equal a string, it says "array typechar[30]is not assignable". Even if at the back I put semi-colon or not. ``` #include <stdio.h> int main() { int choice1; char word[30]; printf("You have three choice.\n"); printf("[1] Jump [2] Run [3] Dance\n"); scanf("%d",&choice1); if (choice1 == 1) { word = "Jump" //Error #1 } else if (choice1 == 2) { word = "Eat" //Error #2 } else if (choice1 == 3) { word = "Sleep"; //Error #3 } printf("You will now be %sing",word); } ```
You can'tassignto an array, onlycopyto it. Usestrcpyinstead, like ``` strcpy(word, "Jump"); ```
``` uint8_t ui8 = 255; ui8 == (int16_t)-1 ``` As far as I understand thestandard: Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type. ui8would be converted/promoted to int16_t and then it's arithmetic value would be-1. Unfortunately the compiler I am using says I am not right.
Whenever auint8_tor any other small integer type is used as part of an expression, it gets integer promoted to typeint. The same goes forint16_t, in caseintis larger than 16 bits. So your code is guaranteed to be equal to: (int)255 == (int)-1 which is always false. Because of integer promotions, both operands are already of the same type, so no balancing between operands takes place.
This question already has answers here:What is the behavior of integer division?(6 answers)Closed8 years ago. ``` size.total = size.width * size.height; y = yuv[position.y * size.width + position.x]; u = yuv[(position.y / 2) * (size.width / 2) + (position.x / 2) + size.total]; v = yuv[(position.y / 2) * (size.width / 2) + (position.x / 2) + size.total + (size.total / 4)]; rgb = YUV444toRGB888(y, u, v); ``` Here/is Div not division. The above formula is taken from thewikipedialink . The one thing I want to know is that the statement mentioned Here/is Div not division. What isDivhere then, it is not dividing then what?
What the page means by Div is integer division. In C, if both operands to the/operator are of an integral type, the result is also of an integral type and any fractional part is truncated. For example,5 / 2evaluates to 2.
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed8 years ago.Improve this question Here is the source code: ``` #include <stdio.h> enum coordinate_type{ RECTANGULAR = 1,POLAR }; int main(void) { int RECTANGULAR; printf("%d %d\n",RECTANGULAR,POLAR); return 0; } ``` Why is the result the following: ``` 3 2 ```
You are redefining what RECTANGULAR is in the main function. It gets initialized with a "random" value, in this case it is 3, but it could be anything else. POLAR keps its value of 2 because of how the enum is defined. Try redefining the RECTANGULAR variable in main to see different outputs.
This question already has answers here:problems with char array = char array(2 answers)Closed8 years ago. Well here is my first post. I've been trying to do this choice choosing thing and I want the user to choose only numbers instead of typing them down (easier) but when I want the numbers to equal a string, it says "array typechar[30]is not assignable". Even if at the back I put semi-colon or not. ``` #include <stdio.h> int main() { int choice1; char word[30]; printf("You have three choice.\n"); printf("[1] Jump [2] Run [3] Dance\n"); scanf("%d",&choice1); if (choice1 == 1) { word = "Jump" //Error #1 } else if (choice1 == 2) { word = "Eat" //Error #2 } else if (choice1 == 3) { word = "Sleep"; //Error #3 } printf("You will now be %sing",word); } ```
You can'tassignto an array, onlycopyto it. Usestrcpyinstead, like ``` strcpy(word, "Jump"); ```
``` uint8_t ui8 = 255; ui8 == (int16_t)-1 ``` As far as I understand thestandard: Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type. ui8would be converted/promoted to int16_t and then it's arithmetic value would be-1. Unfortunately the compiler I am using says I am not right.
Whenever auint8_tor any other small integer type is used as part of an expression, it gets integer promoted to typeint. The same goes forint16_t, in caseintis larger than 16 bits. So your code is guaranteed to be equal to: (int)255 == (int)-1 which is always false. Because of integer promotions, both operands are already of the same type, so no balancing between operands takes place.
This question already has answers here:What is the behavior of integer division?(6 answers)Closed8 years ago. ``` size.total = size.width * size.height; y = yuv[position.y * size.width + position.x]; u = yuv[(position.y / 2) * (size.width / 2) + (position.x / 2) + size.total]; v = yuv[(position.y / 2) * (size.width / 2) + (position.x / 2) + size.total + (size.total / 4)]; rgb = YUV444toRGB888(y, u, v); ``` Here/is Div not division. The above formula is taken from thewikipedialink . The one thing I want to know is that the statement mentioned Here/is Div not division. What isDivhere then, it is not dividing then what?
What the page means by Div is integer division. In C, if both operands to the/operator are of an integral type, the result is also of an integral type and any fractional part is truncated. For example,5 / 2evaluates to 2.
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed8 years ago.Improve this question Here is the source code: ``` #include <stdio.h> enum coordinate_type{ RECTANGULAR = 1,POLAR }; int main(void) { int RECTANGULAR; printf("%d %d\n",RECTANGULAR,POLAR); return 0; } ``` Why is the result the following: ``` 3 2 ```
You are redefining what RECTANGULAR is in the main function. It gets initialized with a "random" value, in this case it is 3, but it could be anything else. POLAR keps its value of 2 because of how the enum is defined. Try redefining the RECTANGULAR variable in main to see different outputs.
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.Closed8 years ago.Improve this question I am wondering,How to write a function in c that returnintpointer for anystringinput The below function is my attempt to solve the requirment ``` int* methodname(char* param) { int *a; int b=3; a=&b; return a; } ``` Please correct me for any mistakes.
Within the definition of the question, which places no functionality on the function, the following would be a proper implementation without mallocs or undefined behavior: ``` int* methodname(char* param) { return ((int *)param); // just return the param as a pointer to int } ```
I just finished compiling and installing flex for my macbook pro and tried to compile a file using flex. I get the following error: ``` ld: library not found for -lfl clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [myhtml2txt] Error 1 ``` I believe-lflis the linker for flex, so why am I getting this error, and how can I fix it?
you are missing to add libflex or it could be libfl. your main errorld: library not found for -lfltells that library is missing. l in -lfl denotes the library. by adding library you will not see this error
Can somebody help me to understand the following statement? Why before #endif is "{" not "#ifdef", this seems illogical, If you have a function implemented in C and want to call it from C++. 1.1). if you can modify C header files Typically the declarations in a C header file are surrounded with ``` #ifdef __cplusplus extern "C" { #endif [... C declarations ...] #ifdef __cplusplus } #endif ``` to make it usable from C++.
If __cplusplus has been defined, and therefore it is C++ code, then we want ``` extern "C" { ``` and close it with ``` } ``` at the end. I hope I have decoded your message properly.
I have been having some odd problems as of late with some code that I have written. ``` printf("%li\n",(sizeof(char))); printf("%li\n",sizeof(4*(sizeof(char)))); ``` When I run the code the first line prints "1" and the second prints "8". If I were to multiply 4 by 1 I would get four. Why is this happening?
Maybe you meant to print4*(sizeof(char)). That would have given4. However you actually printedsizeof(4*(sizeof(char))).sizeofyields the number of bytes required to store its operand. The type of4*sizeof(char)issize_twhich is a 64-bit type on your system, so you are getting8as the output. You would get the same result by printingsizeof(123456*sizeof(float)).sizeofdoes not tell you anything about the value of its operand, just how many bytes are required to store it.
Considering that the main Python implementation CPython written in C, and libraries exist that can convert Python code to C, would it be possible to run compiled Python bytecode in C or C++?
First, you cannot run anything in C, C is a programming language. You can embed python in your C program (seeDocumentation), because python can be compiled as library. But Python is not only the pyc-File, but consists of many modules, that make python as powerful as it is.
This question already has answers here:End of File (EOF) in C(3 answers)Closed8 years ago. When I use this code, I can type into the command line and get back what I typed: ``` main() { int c; while ((c = getchar()) != EOF) { putchar(c); } } ``` Output: ``` ~/code/c $ ./a.out one one two two ``` But when I use this code, it only works when I pipe in data, not when I type data into the command line: ``` main() { int nc; nc = 0; while (getchar() != EOF) { nc++; } printf("%d\n", nc); } ``` When I pipe data in from a text file: ``` ~/code/c $ ./a.out < practice.txt 14 ``` When I try to input data from the command line: ``` ~/code/c $ ./a.out one two three ``` What's going on?
The while loop never exits sincewhile (getchar() != EOF)is always true. After you're done with the input, pressCntrl+Dfor Linux orCtrl+Zfor Windows to indicate EOF.
Can anyone explain what is happening in this code? ``` #include <stdio.h> void f(const char * str) { printf("%d\n", str[4]); } int main() { f("\x03""www""\x01""a""\x02""pl"); f("\x03www\x01a\x02pl"); return 0; } ``` why output is? ``` 1 26 ```
The issue is with"\x01""a"versus"\x01a", and the fact that the hex->char conversion and the string concatenation occur during different phases of lexical processing. In the first case, the hexadecimal character is scanned and converted prior to concatenating the strings, so the first character is seen as\x01. Then the "a" is concatenated, but the hex->char conversion has already been performed, and it's not re-scanned after the concatenation, so you get two letters\x01anda. In the second case, the scanner sees\x01aas a single character, with ASCII code 26.
This is a practice quiz question: ``` int main() { char ch = '\060'; printf("%d\n", ch+1); return 0; } // What is the output? ``` And the answer was49. I think it's49because a0is48on the ASCII table, and 48 + 1 = 49. Is60ignored/disregarded (chis a char variable, not a string one)? Also, I thought\0represented a null character at first, so I thought the output was1(null characters have a value of0on the ASCII table).
'\060'is a single character, in which060are octal digits, whose value is indeed48in decimal. C11 §6.4.4.4 Character constantsoctal-escape-sequence: \ octal-digit \ octal-digit octal-digit \ octal-digit octal-digit octal-digit
In ubuntu I would do it by following command ``` ./a.out < input.txt | cat > ouput.txt ``` how can I do this in Windows cmd?
You can do it in two lines: ``` a.exe < input.txt >output.txt type output.txt ```
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.Closed8 years ago.Improve this question ``` #include <stdio.h> #include <string.h> struct{int x,y;}x; struct{int x,y;}y; int main(void) { return 0; } ``` Are theses declararations legal on an individual basis these structs? Could both declarations appear as shown in the code or program?
Wen a structures is declared, it represents a new scope. Therefore, each structure has it own name space. So, nothing wrong with the above snippet.
This is the code: ``` unsigned int c; signed int d = -1; c = d; if(c == d) printf("c == d\n"); ``` Running this gives the output:c == d. The variableccan not be negative right?
According to the rules ofusual arithmetic conversions, expressionc == dis interpreted asc == (unsigned int) d. More specifically, when you mixsigned intandunsigned intoperands in equality comparison operator, thesigned intoperand is implicitly converted tounsigned inttype before the comparison. The same is true for majority of binary operators in C. At the same time, you assigned the value ofcasc = d, which is equivalent toc = (unsigned int) d. So, as you can immediately see, you are comparing the same thing to the same thing: you are essentially comparing(unsigned int) dto(unsigned int) d. No wonder the equality holds.
I do not see why 3 & 0x1111 = 1 ? It seems that: for any unsigned 32-bit integer i, i & 0x1111 should be i, right? However when I tried this on ubuntu 14.04, I got3 & 0x1111=1. Why? ``` int main() { unsigned int a =3; printf("size of a= %lu\n",sizeof(a)); printf("value of 3 & 0x1111= %d\n",a & 0x1111); return 0; } ```
Convert both of them to binary: ``` 0x1111 = 0001 0001 0001 0001 3 = 0000 0000 0000 0011 ``` When you&them bit by bit, what else do you expect?
``` printf("%d", 7 - 9 % 4 * 2); ``` I got 3 as my printed answer but the answer was 5. Can anyone tell me why I got this wrong?
Multiplication, division, and modulus have the same precedence, and they all have higher precedence than addition and subtraction. If two operators have the same precedence, they are (in most cases) evaluated left to right. So the expression effectively looks like this: ``` 7 - ((9 % 4) * 2) ``` Which gives you: ``` 7 - ((9 % 4) * 2) = 7 - (1 * 2) = 7 - 2 = 5 ``` You probably did division instead of modulus: ``` 7 - ((9 / 4) * 2) = 7 - (2 * 2) = 7 - 4 = 3 ```
In ubuntu I would do it by following command ``` ./a.out < input.txt | cat > ouput.txt ``` how can I do this in Windows cmd?
You can do it in two lines: ``` a.exe < input.txt >output.txt type output.txt ```
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.Closed8 years ago.Improve this question ``` #include <stdio.h> #include <string.h> struct{int x,y;}x; struct{int x,y;}y; int main(void) { return 0; } ``` Are theses declararations legal on an individual basis these structs? Could both declarations appear as shown in the code or program?
Wen a structures is declared, it represents a new scope. Therefore, each structure has it own name space. So, nothing wrong with the above snippet.
This is the code: ``` unsigned int c; signed int d = -1; c = d; if(c == d) printf("c == d\n"); ``` Running this gives the output:c == d. The variableccan not be negative right?
According to the rules ofusual arithmetic conversions, expressionc == dis interpreted asc == (unsigned int) d. More specifically, when you mixsigned intandunsigned intoperands in equality comparison operator, thesigned intoperand is implicitly converted tounsigned inttype before the comparison. The same is true for majority of binary operators in C. At the same time, you assigned the value ofcasc = d, which is equivalent toc = (unsigned int) d. So, as you can immediately see, you are comparing the same thing to the same thing: you are essentially comparing(unsigned int) dto(unsigned int) d. No wonder the equality holds.
I do not see why 3 & 0x1111 = 1 ? It seems that: for any unsigned 32-bit integer i, i & 0x1111 should be i, right? However when I tried this on ubuntu 14.04, I got3 & 0x1111=1. Why? ``` int main() { unsigned int a =3; printf("size of a= %lu\n",sizeof(a)); printf("value of 3 & 0x1111= %d\n",a & 0x1111); return 0; } ```
Convert both of them to binary: ``` 0x1111 = 0001 0001 0001 0001 3 = 0000 0000 0000 0011 ``` When you&them bit by bit, what else do you expect?
``` printf("%d", 7 - 9 % 4 * 2); ``` I got 3 as my printed answer but the answer was 5. Can anyone tell me why I got this wrong?
Multiplication, division, and modulus have the same precedence, and they all have higher precedence than addition and subtraction. If two operators have the same precedence, they are (in most cases) evaluated left to right. So the expression effectively looks like this: ``` 7 - ((9 % 4) * 2) ``` Which gives you: ``` 7 - ((9 % 4) * 2) = 7 - (1 * 2) = 7 - 2 = 5 ``` You probably did division instead of modulus: ``` 7 - ((9 / 4) * 2) = 7 - (2 * 2) = 7 - 4 = 3 ```
I'm trying to call c function from java code. I'm using swig (ver 1.3.40) and running under ubunto. my interface file looks: ``` %module test %include "typemaps.i" %apply(char *STRING, int LENGTH) {(char* pchInput, int inputSize)}; %{ #include "example.h" %} void testFunc(char* pchInput, int inputSize); ``` I'm getting the following wanning/error: warning(453): Cant apply (char *STRING,int LENGTH). No typemaps are defined. The following links doesnt help me: SWIG: Warning 453: Can't apply SWIG: No typemaps are defined Swig typemap java object
Strange. I tried your above example with the current swig 3.0.7 (calling it test.i and usingswig -java test.i) and it works fine. Also, you don't need to%include "typemaps.i"for this to work. However as far as I can tell this should also work with (ancient) swig 1.3.40.
Hi considering this code: ``` uint16_t dest_pid; uint8_t *p; pf->dest_pid = p[0] + (p[1] << 8) //(p[1] << 8) equals 0 right? ``` This code is a part of embedded operating system's driver. Some ideas what might be the idea behind that statement? Or may be I am missing something essential?
I assume that yourpis meaningfully initialized (to point to some valid location). Then inp[0] + (p[1] << 8)thep[1]would be implicitly promoted tounsignedbefore doing the left shift<< 8, so the code does make sense (e.g. on 32 bits processors like ARM). Informally it makes a 16 bit number whose lower 8 bits are fromp[0]and higher 8 bits are fromp[1] Grossly speaking, the implicit rule is that in C arithmetic operations are onintat least (and never on smaller pieces of data likeshortoruint8_torchar). But the details are more complex (and have slightly evolved from C89 to C99 and to C11 standards).
Why is my simple C program printing "hello world" and being compiled with no errors and is running fine when I gave a floating point number next to return statement? Shouldn't it be an error to do so? Here is my code: ``` #include<stdio.h> int main() { printf("hello world"); return 2.1; } ```
For the same reason of ``` int main(void) { // ... int x = 2.1; // ... return x; } ``` This is calledimplicit conversion.
I am using strcmp for comapring the file with same name in the directory. ``` while((entry = readdir(dp)) != NULL) { if(strcmp(dirp->dname,filename) == 0) { print("match found"); } else { printf("match not found"); } } ``` considering that i have some 500 files in the directory it is checking for all those files and sending error many time till the match is found. i Want to optimize this . please help
After specific file is found no need to iterate so usebreakandmatch not foundmessage should not be print inside while loop. please refer below code for understanding. ``` int flag = 0; while((entry = readdir(dp)) != NULL) { if(strcmp(dirp->dname,filename) == 0) { print("match found"); flag = 1; break; } } if(flag == 0) printf("match not found"); ```
int val = 7; ``` int *ptr = &val; ``` val is a variable of type int and ptr is a pointer to type intso the assignment above is right and there is no warning from compiler. ``` int val[5] = {5, 3, 2, 33,557}; int (*ptr)[1]=&val; ``` val is an array of integers and ptr is a pointer to an array of intwhen run compiler give me a warning: ``` warning: initialization from incompatible pointer type [enabled by default] ``` please someone explain me what is the differece between them?
The warning is because the type of the pointer (pointer to length 1 array ofint) doesn't match the type of the array, with is length 5 array ofint. You need ``` int (*ptr)[5]=&val; ``` There is no warning in the first example because the type of the pointer on the LHS of the initialization matches the type of the pointer on the RHS.
I run the code on this page,enter link description here some error comes. First,"#include " and "#include "/usr/local/include/eigen3/Eigen/Eigen" " is necesary in the file std.h?I can not find these included file.Second,when i comment out the code lines "#include " and "#include "/usr/local/include/eigen3/Eigen/Eigen",then i run the code,many error comes,as follow I tried,but failed,can someone help me?Thanks in advands!
Eigenis a C++ library for linear algebra that you need to install and include the correct headers.The source code seems to target Linux./usr/local/include/eigen3/Eigen/Eigenimplies a unix path.You are on Windows, that won't work. you have to modify the code to work.
I run the code on this page,enter link description here some error comes. First,"#include " and "#include "/usr/local/include/eigen3/Eigen/Eigen" " is necesary in the file std.h?I can not find these included file.Second,when i comment out the code lines "#include " and "#include "/usr/local/include/eigen3/Eigen/Eigen",then i run the code,many error comes,as follow I tried,but failed,can someone help me?Thanks in advands!
Eigenis a C++ library for linear algebra that you need to install and include the correct headers.The source code seems to target Linux./usr/local/include/eigen3/Eigen/Eigenimplies a unix path.You are on Windows, that won't work. you have to modify the code to work.
``` typedef void* TVPtr; typedef const void* CTVPtr; const TVPtr func3 (const TVPtr p) { return p; } const void* func4 (const void* p) { return p; } CTVPtr func5 (CTVPtr p) { return p; } int main () { const uint64_t i = 10; func3(&i); // compilation error here // cannot convert argument 1 from 'const uint64_t *' // to 'const TVPtr' Conversion loses qualifiers func4(&i); // no compilation error func5(&i); // no compilation error return 0; } ``` I do not understand why there is error is one case and not in the other two?
const TVPtris notconst void*, it'svoid* const. In other words, it's not a pointer toconst void, it's aconstpointer tovoid. Sinceiis declaredconstit will happily bind to aconst void*, but not avoid* const, because that discards theconstness of the object itself.
The Realm mobile database have Objective-C and Java bindings, suitable for iOS and Android respectively. However I want to use Realm in Blackberry and Windows Phone and Realm has no C/C++ bindings yet. My question is: can you link/call Objective-C library from C/C++, with Realm library to be used in Blackberry and Windows Phone in particular?
Its not the lack of C/C++ bindings that's your problem, rather that Realm only runs on iOS and Android - there is no Realm for Blackberry and Windows Phone. The source is public domain though (Apache 2 licence), so you could consider porting it yourself...
Open system call in unix The following is the prototype of open system call: ``` int open(const char *pathname, int flags); int open(const char *pathname, int flags, mode_t mode); ``` pathname --> It is used to mention the path of the file like /home/mohan/a.txt flags --> It is used to mention on which mode the file will be open like Readonly, writeonly or readwrite. mode --> ? What is use of mode and when I use the mode. Is there any example for using mode. Thanks in advance.
As we can see in theopen(2) man page, the mode is used to set the access-rights of the file (as you could do with the UNIX commandchmod). It's useless when you're not creating the file, but when you use the flagO_CREAT, you have to use it. In example : creating a file with rights 644 in read + write mode: int fd = open("file", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);