question
stringlengths
25
894
answer
stringlengths
4
863
I'm writing a simple code for removing spaces from a string in C however I get the following message after compiling: EXC_BAD_ACCESS (code=2, adresss=....). It's coming from the line '*temp = *str' however I don't understand why? How can I fix it? ``` void removeSpaces(char * str) { char * temp = str; while (*str != '\0') { if (*str != ' ') { *temp = *str; temp++; } str++; } *temp = '\0'; } ```
The function works fine when passed a string declared like this ``` char s[] = "Hallo World!"; ``` but if you declared the string like this, as a pointer to string literal ``` char *s = "Hallo World!"; ``` you are not supposed to modify the string.
Is it possible to change the title of a window using a GObject method? I have the below lines of code ``` window=gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(window),"Hello World"); ``` What I wish to do is to replace thegtk_window_set_titlewith a method defined in GObject(ie one of its ancestor class) so as to change the title.
Many gettable and settable values in a GObject are provided asproperties. One of the properties of GtkWindow is"title". You can get properties withg_object_get()and set them withg_object_set(). The GObject version ofgtk_window_set_title()then is ``` g_object_set(window, "title", "New title", NULL); ``` Each class has a Properties section in its documentation showing all the properties for that class. A class also inherits the properties of its superclasses.Here's the documentation forg_object_set().
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 am developing a software using C language. I would like to build a nice graphical user interface to get the input and present the output as well as the progress status. The console is OK when it comes to test the software but to attract attention when presenting my software to other, I need something better. Any ideas.. Thanks! I am using : Visual Studio 2010 on Windows7.
Hat's off for sticking with C for this, it's kinda the hard way! Anyway, you could link to the Win32 Api and create a GUI that way.http://www.winprog.org/tutorial/start.html Another option would be to use a cross platform framework like GTK+:http://www.gtk.org/
I took a class of programming at my university and I am working on some program. I want to know if it is possible to program my ownkbhit()function. And if it is possible to look, howkbhit()is coded. The purpose is that I need to know how functions I use work.
Yes and no. C language has no notion of input and output. It relies on a standard library (essentially written in C) that in turn relies on system calls. Neither the standard library, nor the set of system calls common to Unix-like systems and Windows deal with non blocking system calls, so you have to call system specific ones. But again, you can call them easily from C language.
I'm trying to develop client in C for ActiveMQ using OpenWire and after compiling examplemainfor OpenWire ActiveMQ on Ubuntu, when I try to run it I get this error: ``` bash: ./test: cannot execute binary file: Exec format error ``` I've tried it on both ubuntu 32 and 46 bit but it didn't work Any Ideas? Is there any other C alternative then OpenWire?
The problem is the-cflag, as it tellsgccto generate anobjectfile and not an executable file. Remove the-cflag: ``` gcc main.c -o test ```
I'm getting a wrong solution for this series:(-1/4)^(n+1)*(z-1)^n For|z-1|<4should the series tend to converge to-1/3+z Forz=0.5should be the solution-2/7, but if i try to plot with c, the result is 0... Here is my code: ``` #include <stdio.h> #include <math.h> int main(){ double sum=0; int n; for(n=0;n<=100000;n++){ sum+=pow((-1/4),(n+1)) * pow((0.5-1),n); } printf("sum= %f\n",sum); } ```
Problem right here: ``` sum+=pow((-1/4),(n+1)) * pow((0.5-1),n); ``` -1is an integer literal, and so is4; hence,(-1/4)is-0, and not-0.25(which was probably what you wanted to use). Use floating point literals like-1.0if you want them in C!
I took a class of programming at my university and I am working on some program. I want to know if it is possible to program my ownkbhit()function. And if it is possible to look, howkbhit()is coded. The purpose is that I need to know how functions I use work.
Yes and no. C language has no notion of input and output. It relies on a standard library (essentially written in C) that in turn relies on system calls. Neither the standard library, nor the set of system calls common to Unix-like systems and Windows deal with non blocking system calls, so you have to call system specific ones. But again, you can call them easily from C language.
I'm trying to develop client in C for ActiveMQ using OpenWire and after compiling examplemainfor OpenWire ActiveMQ on Ubuntu, when I try to run it I get this error: ``` bash: ./test: cannot execute binary file: Exec format error ``` I've tried it on both ubuntu 32 and 46 bit but it didn't work Any Ideas? Is there any other C alternative then OpenWire?
The problem is the-cflag, as it tellsgccto generate anobjectfile and not an executable file. Remove the-cflag: ``` gcc main.c -o test ```
I'm getting a wrong solution for this series:(-1/4)^(n+1)*(z-1)^n For|z-1|<4should the series tend to converge to-1/3+z Forz=0.5should be the solution-2/7, but if i try to plot with c, the result is 0... Here is my code: ``` #include <stdio.h> #include <math.h> int main(){ double sum=0; int n; for(n=0;n<=100000;n++){ sum+=pow((-1/4),(n+1)) * pow((0.5-1),n); } printf("sum= %f\n",sum); } ```
Problem right here: ``` sum+=pow((-1/4),(n+1)) * pow((0.5-1),n); ``` -1is an integer literal, and so is4; hence,(-1/4)is-0, and not-0.25(which was probably what you wanted to use). Use floating point literals like-1.0if you want them in C!
For example, takeint x = 30;andint y = 27;. My program would call the functionbool CheckWithinRange(int x, int y, int range);asCheckWithinRange(x, y, 3)orCheckWithinRange(y, x, 3)and it would return true. EDITSorry, my bad, my question is simply: How can such a function be written?
This question is actually a little tricky to answer in the general case. Ifxorycan be very large or very far apart,x-ymay overflow. Here is a solution that solves the question for allintvalues ofx,yandrange: ``` #include <limits.h> #include <stdbool.h> bool CheckWithinRange(int x, int y, int range) { if (range < 0) return false; if (x <= y) return x >= INT_MAX - range || x + range >= y; else return y >= INT_MAX - range || y + range >= x; } ```
This question already has answers here:Does C support overloading?(9 answers)Closed8 years ago. According tothe Linux manual page, the Linux C APIopenhas two prototypes as follows: ``` int open(const char *pathname, int oflags); int open(const char *pathname, int oflags, mode_t mode); ``` What makes me confused is: Why does the Linux C API 'open' support function overloading??
No, C doesn't support function overloading. The POSIXopenfunction is actually a variadic function, its signature is: ``` int open(const char *path, int oflag, ... ); ```
Can someone please tell me why theCcompiler outputs an error while using aCompound Assignmentand aPrefix Dec/Inctogether ? [ butC++does not ] ``` int myVar = 5; (--myVar) -= 4; // C : error C2106: '-=' : left operand must be l-value // C++: myVar=0; ``` I know what the error says ... But, I can't understandwhy aCcompiler can't recognizemyVaras a l-valuebutC++does?!
In C, prefix--operator yields an rvalue. An rvalue can't be a left operand of assignment operator. That said, C and C++ are two different languages.
``` int* dec2bin(int y){ int *arr = (int*)malloc(sizeof(int)*5); int i; for (i=0; i<5; i++) arr[i]=0; return arr; } ``` In this code, I write0toarr[0]through toarr[4], but the function returns1070192. I want to return00000. What am I doing wrong?
Most probably you are printing the address returned bymalloc(). You need a loop to print the contents, for example ``` int *dec2bin(int size) { return calloc(size, sizeof(int)); } int main(void) { int *data; int index; int size; size = 5; data = dec2bin(size); if (data == NULL) return -1; /* allocation error */ for (index = 0 ; index < size ; index++) printf("%d", data[index]); printf("\n"); free(data); return 0; } ``` You can see that I usedcalloc(), that's because you are going to initialize all the values to0, otherwise usemalloc()instead.
I am trying to find the total time between data being sent and received. I am simply sending some random generated data from a C-program viawebsocket, and the data is received in JavaScrip that displays a nice diagram usingCanvas.js. How can I find the total time, could I write a simple C-code or JavaScript code, or is there any program that handles this for me?
It's possible with Javascript. If you just want to see the time in your console, useconsole.time. console.time("answer time"); alert("Click to continue"); console.timeEnd("answer time"); Moveconsole.timeEndin your callback ajax, andconsole.timebefore your ajax call. Reference Console MDN Timers
In a custom library I saw an implementation: ``` inline int is_upper_alpha(char chValue) { if (((chValue >= 'A') && (chValue <= 'I')) || ((chValue >= 'J') && (chValue <= 'R')) || ((chValue >= 'S') && (chValue <= 'Z'))) return 1; return 0; } ``` Is that anEaster eggor what are the advantages vs standard C/C++ method? ``` inline int is_upper_alpha(char chValue) { return ((chValue >= 'A') && (chValue <= 'Z')); } ```
The author of this code presumably had to supportEBCDICat some point, where the numeric values of the letters are non-contiguous (gaps exist betweenI,JandR,S, as you may have guessed). It is worth noting that the C and C++ standards only guarantee that the characters0to9have contiguous numeric values for precisely this reason, so neither of these methods is strictly standard-conforming.
I understand that this valgrind error is occurred because I was trying to use something uninitialized. The code below is one that causes this error. What it's doing is it is trying to read Racket code and get each symbols such as + or define. (tokenize) I am not expecting you to thoroughly understand the code because there are a lot other codes to understand what it's doing. However, I'd really appreciate if you could give me your thoughts of the reason why I get this error on that line,symbol = strcat(symbol, newsymbol); ``` char* newsymbol = talloc(sizeof(char)*2); *newsymbol = charRead; newsymbol[1] = '\0'; symbol = strcat(symbol, newsymbol); ```
Becausesymbolis notnulterminated you need tonulterminate it before passing it tostrcat().
When I read someone's code, I came across the unfamiliar code. The code is as the following: ``` struct Employee { int id; }; #define getId(ptr) ((ptr)->id) #define setId(ptr, value) ((ptr)->id = (value), 0) ``` I couldn't understand of((ptr)->id = (value), 0). Is this macro the same as((ptr)->id = (value)?
I couldn't understand of "((ptr)->id = (id), 0)". Is this macro the same like "((ptr)->id = (id)" ? Assuming the macro definition is: ``` #define setId(ptr, name) ((ptr)->id = (name), 0) ``` If you have an expression ``` a = setId(ptr, name); ``` it is expanded to ``` a = ((ptr)->id = (name), 0); ``` When that expression is executed, the value ofais0, which is the value of the comma expression((ptr)->id = (name), 0). The side effect of evaluating the expression is that theidmember of the object thatptrpoints to is set toname.
I understand that this valgrind error is occurred because I was trying to use something uninitialized. The code below is one that causes this error. What it's doing is it is trying to read Racket code and get each symbols such as + or define. (tokenize) I am not expecting you to thoroughly understand the code because there are a lot other codes to understand what it's doing. However, I'd really appreciate if you could give me your thoughts of the reason why I get this error on that line,symbol = strcat(symbol, newsymbol); ``` char* newsymbol = talloc(sizeof(char)*2); *newsymbol = charRead; newsymbol[1] = '\0'; symbol = strcat(symbol, newsymbol); ```
Becausesymbolis notnulterminated you need tonulterminate it before passing it tostrcat().
I have seen many post on this topic. But haven't found a clear answer anywhere. Is there a way to toggle CAPS LOCK in Objective-C or C code? I am not looking for a solution using X11 libs. I am not bothered about the LED on/off status. But just the functionality of CAPS LOCK (changing the case of letters and printing the special characters on number keys). Why is CGEvent not supporting this the way it does for other keys?
``` var ioConnect: io_connect_t = .init(0) let ioService = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching(kIOHIDSystemClass)) IOServiceOpen(ioService, mach_task_self_, UInt32(kIOHIDParamConnectType), &ioConnect) var modifierLockState = false IOHIDGetModifierLockState(ioConnect, Int32(kIOHIDCapsLockState), &modifierLockState) modifierLockState.toggle() IOHIDSetModifierLockState(ioConnect, Int32(kIOHIDCapsLockState), modifierLockState) IOServiceClose(ioConnect) ```
I got a struct defining a node for a tree data structure: ``` struct Node { int data; struct Node *children[10]; } ``` Given thatchildrenis NOT a dynamic array, I would like to initialize each pointer ofchildrento NULL, but what follows doesn't work: ``` struct Node { int data; struct Node *children[10]={NULL}; } ``` Is there any workaround?
This ``` struct *Node children[10]; ``` is wrong. I would not even compile. It should be ``` struct Node *children[10]; ``` To initialize all elements of memberchildrentoNULLyou can use designated initializers. ``` struct Node { int data; struct Node *children[10]; } node = {.children = {NULL}}; ```
``` struct Student { char name[10]; }; void set(struct student *s,const char *n) { s->name=n; // this line is showing error(incompatible types in assignment) } int main() { struct Student stud; char name[]="abc"; set(&stud,name); } ``` this line ``` s->name=n; ``` is showing compile time error of incompatible assignment. how can I assign the name passed using function to the structure variable.
You need to usestrcpyto copy strings, so do ``` strcpy(s->name,n); ``` And change ``` void set(struct student *s,const char *n) ``` to ``` void set(struct Student *s,const char *n) ^ capital S ```
I am trying to figure out how to check if a character is equal to white-space in C. I know that tabs are'\t'and newlines are'\n', but I want to be able to check for just a regular normal space (from the space-bar) inside of anifstatement. Does anybody know what is the character for this?
There is no particular symbol for whitespace. It is actually a set of few characters which are: ``` ' ' space '\t' horizontal tab '\n' newline '\v' vertical tab '\f' form feed '\r' carriage return ``` Useisspacestandard library function fromctype.hif you want to check for any of these white-spaces. For just a space, use' '.
I am not sure what will be in the char array after initialization in the following way: ``` char buf[5]={0,}; ``` Is that equivalent to ``` char buf[5]={0,0,0,0,0}; ```
Yes, it is the same. If there are less number ofinitializersthan the elements in the array, then the remaining elements will be initialized as if the objects having static storage duration, (i.e., with0). So, ``` char buf[5]={0,}; ``` is equivalent to ``` char buf[5]={0,0,0,0,0}; ``` Related Reading : From theC11standard document, chapter 6.7.9, initalization, If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that havestaticstorage duration.
I am trying to figure out how to check if a character is equal to white-space in C. I know that tabs are'\t'and newlines are'\n', but I want to be able to check for just a regular normal space (from the space-bar) inside of anifstatement. Does anybody know what is the character for this?
There is no particular symbol for whitespace. It is actually a set of few characters which are: ``` ' ' space '\t' horizontal tab '\n' newline '\v' vertical tab '\f' form feed '\r' carriage return ``` Useisspacestandard library function fromctype.hif you want to check for any of these white-spaces. For just a space, use' '.
I am not sure what will be in the char array after initialization in the following way: ``` char buf[5]={0,}; ``` Is that equivalent to ``` char buf[5]={0,0,0,0,0}; ```
Yes, it is the same. If there are less number ofinitializersthan the elements in the array, then the remaining elements will be initialized as if the objects having static storage duration, (i.e., with0). So, ``` char buf[5]={0,}; ``` is equivalent to ``` char buf[5]={0,0,0,0,0}; ``` Related Reading : From theC11standard document, chapter 6.7.9, initalization, If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that havestaticstorage duration.
I have an image represented by a 1-dimension array (char[]). Image height isH, image width isW, and I would like to extract a subimage starting in(dx,dy)and which dimensions are(dW,dH) This seems not to work : ``` subimage(i,j) = image[(j+dy*W) * (W+i+dx)] ``` Can somebody help?
The formula for a particular pixel in an image stored a 1-dimensional array with the stride equal to the image width is: ``` pixel(x,y) = image[(y * width) + x] ``` So the formula you're looking for is (in pseudo-code): ``` subimage(i,j) = image[((j+dy)*W) + (i+dx)] ``` Iteratejover0todHandiover0todW.
I am using linux Lite. I have installed code Blocks. When i am creating any new project then it is working correctly. it compiling codes. But When any empty c file is creating and trying to compile then it is not working.Showing message that permission denied. I have checked the compiler setting for empty file. it is GNU GCC Compiler. How can i solve this?
It would be happen due to root access. run code-blocks as root user and try it would be work.
I am debugging some code and just wanted to make sure that the way I am setting a pointer to an array inside my struct is correct. Here is an example of what I am trying to do: ``` typedef struct Foo { uint32_t *bar; } Foo int main(void) { Foo *foo; uint32_t *bar[20]; foo = (Foo *)malloc(sizeof(Foo)); *bar = malloc(sizeof(uint32_t) * 20); for(int i = 0; i < 20; i++) { bar[i] = (uint32_t*)malloc(sizeof(uint32_t)); } foo->bar = *bar; } ```
The code ``` uint32_t *bar[20]; ``` declaresbaras an array of 20 pointers touint32_twhich is probably not what you intended. Since you allocate the array dynamically withmalloc, you should declarebaras a pointer rather than an array: ``` uint32_t **bar; ```
``` char types[5]; switch(buffer[9]){ case 1: types = "ICMP"; break; ``` error: ``` incompatible types when assigning to type 'char[5]' from type 'char *' ``` how would I fix this error? Thanks.
You can't fix it without changing its type. Array values are not modifiable l-values. If you plan to always assign it a string literal, declare it asconst char *instead of array: ``` const char *types; switch(buffer[9]){ case 1: types = "ICMP"; break; ``` If you want to later change the contents oftypes, then keep it as an array and just usestrcpy()or the safer variantstrncpy(): ``` char types[5]; switch(buffer[9]){ case 1: strncpy(types, "ICMP", sizeof(types)); break; ```
I want to return few values from method: ``` unsigned long long *operand1, *operand2; unsigned long long value1; int operation=0; ``` I was thinking about putting those datas in char array and then retrieve them byte after byte. Is this a good idea? How should I do this? Or could you suggest anything else?
I would suggest using astruct. ``` struct my_struct { unsigned long long *operand1, *operand2; unsigned long long value1; int operation=0; }; ```
I am trying to compile my kernel module. The .c file name isfile1.c, but I need the .ko file name to bemod1.ko. How can I do that? My current makefile: ``` obj-m := mod1.o KDIR :=/lib/modules/$(shell uname -r)/build PDW := $(shell pwd) all: $(MAKE) -C $(KDIR) M=$(PDW) modules clean: $(MAKE) -C $(KDIR) M=$(PDW) clean ```
You should change your first line to something like this: ``` obj-m += module_name.o module_name-y := file1.o ``` Wheremodule_nameis the module file name (in this example the output will bemodule_name.ko) and it will be build fromfile1.c. You can add more than one source file to the 2nd line, so it could be: ``` module_name-y := file1.o file2.o file3.o ``` In this casemodule_name.kowill be build fromfile1.c,file2.candfile3.c. You should readthis documentif you want to fully understand Linux kernel makefiles. Your problem is described somewhere around line 190.
I want to use theGBExtended libraryin my game but I am having difficulty understanding how I would include the library. I can see that the GBExtended library (at least from the loderunner example source) contains the directoriesincludes/,lib/andsrc/and the file which I need to include islib/gbext.lib. I would assume that you would have to include the library in your files as needed: ``` #include <gbextended/screen.h> # etc ... ``` What flags do you have to pass to thelcccompiler so that it will include these libraries? I'm having trouble identifying this from the examples.
With SDCC you can use the -l flag (lowercase L) to specify a library to be included, and the -L flag (uppercase L) to specify the directory from which the files can be found. You also have to use -I (uppercase I) to specify where the header files are located.
This might have been asked before. But I'll ask anyway. If someone could direct me to something relevant, that would also be great. So, if I have: ``` uint8_t src[] = {34, 56, 31, 89, 11, 32, 67, 89}; ``` Is this possible to get something like this through concatenation: ``` uint32_t dst[] = {34563189, 11326789}; ``` If yes, how? I saw a question for casting uint8_t array into a uint32_t but I need to put the 4-bytes chunk side by side into a uint32_t array. Thanks!
If you really are working with decimal values: ``` uint32_t dst[] = {1000000 * src[0] +10000 * src[1] + 100 * src[2] + src[3], 1000000 * src[4] +10000 * src[5] + 100 * src[6] + src[7]}; ```
I was doing a Bingo - type project when i started to get some errors in my first "for" loop and in the end of the "bingo" structure. Can someone tell me what have I done wrong? ``` struct bingo{ int table[5][5]; int i; int j; for (i = 0; i < 25; i++) { *(table + i) = rand()%75 + 1; for (j = 0; j < 25; j++) { if ((j != i) && ((*(table + i)) == (*(table + j)))) { i--; j = 5 * 5; } } } }; ``` errors: 1 IntelliSense: expected a type specifier ( first for) 2 IntelliSense: expected an identifier (end of the sturct)
Structs are only able to contain variables, they can't have any logic in them. In C++ you can have functions defined in structs, but even then you need a function header and body.
Is it possible to increment/advance a char array like I can a char pointer? For example I can do this for a char pointer: ``` while (*cPtr) printf("c=%c\n", *(cPtr++)); ``` But I am not able to do this: ``` // char cArray[] = "abcde"; while (*cArray) printf("c=%c\n", *(cArray++)); // Compile error: 19 26 [Error] lvalue required as increment operand ``` The purpose is to be able to iterate over a char array when I dont know the length of the array. My thinking is that I just want to advance till I find a null character I guess unless theres an easier way? ``` char a[] = "abcde"; int index = -1; while (a[++index]) printf("c=%c\n", a[index]); ```
Is it possible to increment/advance a char array like I can a char pointer? Unlike pointers, arrays are not lvalues and you can't modify it. That's a major difference between arrays and pointers.
``` /* check for number of friends each user */ for (i=0; i<num_users; ++i) { printf("Number of friends of user %d: %d\n", i, findFriends(matrixF, num_users, i)); } int findFriends (int **F, int size, int user) { int i, j; for(i=0; i<size; i++){ user=0; for(j=0; j<size; j++) user+=F[i][j]; return (user); } ``` This code doesn't return all the numbers of friends, only the one of first user. Can you help me find the problem?
Use return after the loop , using return inside the loop will terminate the loop as well as function , "return" statement terminates the function
Is there a way to combine several different conditionals with a shared statement? For example: ``` int a; ... if (a == 1){ foo; ... return K1; } else if (a == 2){ foo; ... return K2; } ... else if (a == i){ foo; ... return Ki; } ``` Is there a smart way to takefooout but make it happen only under these conditionals? (Like factoring in algebra: 2x+6=2(x+3)). It feels repetitive so I figure there should be way to make it shorter.
Would something like this be OK in your scenario? ``` int a; int k; // let's assume int ... k = a == 1? K1: a == 2? K2: ... a == i? Ki: K0; // a special value if (k != K0) foo; return k; ```
I've got the following code that pulls data from anALAssetRepresentation. ``` ALAssetRepresentation *representation = ...; size_t size = [representation size]; // 'size' returns a long long uint8_t *bytes = malloc(size); ``` When building for 32-bit devices on iOS, I get the following warning. Blindly casting thelong longto asize_tworks, but I don't know what the "right" way to handle this situation is. Would love to know how to best handle it.
Since you are assigning to a type ofsize_t, cast the result as asize_t. ``` size_t size = (size_t)[representation size]; ``` The only risk of this is thatrepresentation sizecould be a number larger than what will fit in asize_t. But if that happens, the value is too large to allocate memory for it anyway when running on an iOS device so that is a bigger problem than the loss in precision.
Many times I see programmers doing the following cast ``` unsigned long long minimumValue; minimumValue = (unsigned long long)-1; ``` but why do they do this, rather thanint minimumValue = -1?
That's a trick to give the maximum (not minimum) value of an unsigned type. Conversion from a signed value uses modular arithmetic to give a value in the range of the unsigned type; so-1becomespow(2,N)-1for an unsigned type withNbits, which is the largest representable value. The cast isn't strictly necessary, but some compilers might give a warning without it. A better style might be to specifyULLONG_MAX, orstd::numeric_limits<unsigned long long>::max()in C++.
``` /* check for number of friends each user */ for (i=0; i<num_users; ++i) { printf("Number of friends of user %d: %d\n", i, findFriends(matrixF, num_users, i)); } int findFriends (int **F, int size, int user) { int i, j; for(i=0; i<size; i++){ user=0; for(j=0; j<size; j++) user+=F[i][j]; return (user); } ``` This code doesn't return all the numbers of friends, only the one of first user. Can you help me find the problem?
Use return after the loop , using return inside the loop will terminate the loop as well as function , "return" statement terminates the function
Is there a way to combine several different conditionals with a shared statement? For example: ``` int a; ... if (a == 1){ foo; ... return K1; } else if (a == 2){ foo; ... return K2; } ... else if (a == i){ foo; ... return Ki; } ``` Is there a smart way to takefooout but make it happen only under these conditionals? (Like factoring in algebra: 2x+6=2(x+3)). It feels repetitive so I figure there should be way to make it shorter.
Would something like this be OK in your scenario? ``` int a; int k; // let's assume int ... k = a == 1? K1: a == 2? K2: ... a == i? Ki: K0; // a special value if (k != K0) foo; return k; ```
I've got the following code that pulls data from anALAssetRepresentation. ``` ALAssetRepresentation *representation = ...; size_t size = [representation size]; // 'size' returns a long long uint8_t *bytes = malloc(size); ``` When building for 32-bit devices on iOS, I get the following warning. Blindly casting thelong longto asize_tworks, but I don't know what the "right" way to handle this situation is. Would love to know how to best handle it.
Since you are assigning to a type ofsize_t, cast the result as asize_t. ``` size_t size = (size_t)[representation size]; ``` The only risk of this is thatrepresentation sizecould be a number larger than what will fit in asize_t. But if that happens, the value is too large to allocate memory for it anyway when running on an iOS device so that is a bigger problem than the loss in precision.
Many times I see programmers doing the following cast ``` unsigned long long minimumValue; minimumValue = (unsigned long long)-1; ``` but why do they do this, rather thanint minimumValue = -1?
That's a trick to give the maximum (not minimum) value of an unsigned type. Conversion from a signed value uses modular arithmetic to give a value in the range of the unsigned type; so-1becomespow(2,N)-1for an unsigned type withNbits, which is the largest representable value. The cast isn't strictly necessary, but some compilers might give a warning without it. A better style might be to specifyULLONG_MAX, orstd::numeric_limits<unsigned long long>::max()in C++.
I want to write code in C language to switch on/off an electric bulb via USB port. USB port gives 5 volts, so I want that bulb can take power from computer's USB port. Is it possible?
Using USB for this task is a bit complicated, the common way is to use some (ftdi) usb to serial converter. To switch a light bulb or motor you need a micro controller on the other side of the usb cable. In fact, an arduino-pcb has an build in usb to serial converter, so you can use an arduino to switch something on/off by using an usb port. How to read/write a serial port depends on your operating system, but there a lot of examples for each operating system
For example, I cast a pointer to anintto a pointer tochar: ``` int originalVar = 1; char *arr = (char *)&originalVar; ``` Then I cast it back (maybe I passarrto another function): ``` int *pOriginal = (int *)arr; ``` Does it break the rules? Or any undefined behaviors here? -- Actually my doubts are about understanding the "effective type" in C standard Does the object pointed byarralways regardintas its effective type? (Even ifarris passed to another function?)
That works and is well defined because the alignment of the original pointer will match the int. Only issue casing a char* to an int* can be alignment requirements. Certain architectures require an int to be aligned on a 4-byte boundary (ie. the last two binary digits of the pointer are 0). A char* generally does not have that limitation. However, since it started as an int*, and int* -> char* is never an issue, this will not cause any issue.
This is probably a dumb questions. I'm modifying a code developed by someone else. I need to particularize the value of some chars array based on a logic variableThreeDim. I'm trying to do this without success. ``` int VarNumber = ThreeDim==1 ? 3 : 2; const char* VarList [] = ThreeDim==1 ? {"X","Y","Z"} : {"X","Y"}; ``` But the compiler is giving me errors like ``` error: expected ‘;’ before ‘}’ token error: initializer fails to determine size of ‘VarList’ ``` VarListneeds to be aconst char*due to downstream requirements. And its size should beVarNumber. Thanks
You might consider using the preprocessor,#define THREE_DIM, and then use#ifdefto select one or the other code to compile: ``` #define THREE_DIM #ifdef THREE_DIM int VarNumber = 3; const char* VarList [] = {"X","Y","Z"}; #else int VarNumber = 2; const char* VarList [] = {"X","Y"}; #endif ```
Here is my problem: We would like to use our different Simulink models within a script in a much faster way than having to open the Simulink environment (our MATLAB script using Simulink is launched many time). For that purpose, I want to transform the Simulink model into a C version and launch it from a MATLAB script so that the process would be much faster than opening Simulink environment. Does anyone have already tried this ? Is it possible ? It is unclear to me if I should try to construct an MEX-file from the C code generated with Simulink coder, or if I should use this coder.ceval function to directly run the C code ?
Not sure about the C code approach, but you could generate an executable using the RSIM target. This is relatively easy to implement and should speed up the execution. SeeDeployment of Simulink ModelsandUsing RSim Target for Batch Simulationsfor more details.
I have been trying to figure this out, but any help shall be appreciated. I have this function - ``` void * func1(void * a) { return (void *)0x123; } ``` Now, when I retrieve the Value, I get some random numbers in 1E4 etc etc. Here is my code to retrieve - ``` void * check = func1; printf(1,"%x\n", (uint)check); ``` I do understand Void pointers but this is something getting above my head. I want to print "0x123"
You have tocallthe function: ``` void *check = func1(0); ``` Turn up your compiler warnings!
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 am trying to create a C program which will create a wordsearch and then give the user a time to complete it in and then the program will output a message accordingly. My problem is that I cannot figure out how to ask the user for input while counting down. Any help is appreciated.
Make the user input method it's own thread, a child of the main thread. Use wait in the main thread and then end the child thread when the wait is over. Let us know if you have questions on how to create threads or how to use mutex to keep data secure.
Does the following code free the memory that was allocated forx? ``` int main() { char *x = (char*)calloc(100, sizeof(char)); char *y = x; free(y); } ```
Yes When you do ``` char *y = x; ``` you makeypoint to the location wherexpoints to. Sinceypoints to a memory location returned bycalloc, ``` free(y); ``` is perfectly valid. As@hacckscommented, this would not work if you makeypoint to another memory location, provided that this memory location wasn't returned bymalloc/calloc/realloc. In C, youshould not cast the result ofmalloc/calloc/realloc. Also, checking the return value ofcallocto see if it was successful is good.callocwill returnNULLon failure.
I could find a lot of information how to retrieve the values of the table in lua from the stack in C api, however I am experiencing a bit different problem - when my function is called without the table passed my programs crushes without any warning. Which leads me to the following question, is there any way of checking the existence of table on the stack from C api? Similar to lua_checkstring(L, )?
I found the answer myself during the investigation of the C lua API. The proper function to use to investigate the stack are the is function, so instead of Lua_checkstring I should be using lua_isstring(L, offset). The alternative for lua_istable exists. As suggested by siffiejoe it is also possible to do with luaL_checktype(L, 1, LUA_TTABLE), the difference being the check type will rise an error in the parser.
I want to input two strings at different memory locations but after taking the first input it shows an error "segmentation fault(core dumped"). I am not getting what's wrong with this code. ``` #include <stdio.h> #include<iostream> using namespace std; int main() { char *str; int i; scanf("%s",str+0); scanf("%s",str+1); return 0; } ``` But when I only take one input it works fine. ``` #include <stdio.h> #include<iostream> using namespace std; int main() { char *str; int i; scanf("%s",str+0); return 0; } ``` Why?
Because you do not allocate any memory tostrbefore using it in yourscanf(). You need to allocate some memory withmalloc() Both your codes exhibitUndefined Behavioras you try to access unsafe memory.
I want to write code in C language to switch on/off an electric bulb via USB port. USB port gives 5 volts, so I want that bulb can take power from computer's USB port. Is it possible?
Using USB for this task is a bit complicated, the common way is to use some (ftdi) usb to serial converter. To switch a light bulb or motor you need a micro controller on the other side of the usb cable. In fact, an arduino-pcb has an build in usb to serial converter, so you can use an arduino to switch something on/off by using an usb port. How to read/write a serial port depends on your operating system, but there a lot of examples for each operating system
For example, I cast a pointer to anintto a pointer tochar: ``` int originalVar = 1; char *arr = (char *)&originalVar; ``` Then I cast it back (maybe I passarrto another function): ``` int *pOriginal = (int *)arr; ``` Does it break the rules? Or any undefined behaviors here? -- Actually my doubts are about understanding the "effective type" in C standard Does the object pointed byarralways regardintas its effective type? (Even ifarris passed to another function?)
That works and is well defined because the alignment of the original pointer will match the int. Only issue casing a char* to an int* can be alignment requirements. Certain architectures require an int to be aligned on a 4-byte boundary (ie. the last two binary digits of the pointer are 0). A char* generally does not have that limitation. However, since it started as an int*, and int* -> char* is never an issue, this will not cause any issue.
This is probably a dumb questions. I'm modifying a code developed by someone else. I need to particularize the value of some chars array based on a logic variableThreeDim. I'm trying to do this without success. ``` int VarNumber = ThreeDim==1 ? 3 : 2; const char* VarList [] = ThreeDim==1 ? {"X","Y","Z"} : {"X","Y"}; ``` But the compiler is giving me errors like ``` error: expected ‘;’ before ‘}’ token error: initializer fails to determine size of ‘VarList’ ``` VarListneeds to be aconst char*due to downstream requirements. And its size should beVarNumber. Thanks
You might consider using the preprocessor,#define THREE_DIM, and then use#ifdefto select one or the other code to compile: ``` #define THREE_DIM #ifdef THREE_DIM int VarNumber = 3; const char* VarList [] = {"X","Y","Z"}; #else int VarNumber = 2; const char* VarList [] = {"X","Y"}; #endif ```
I need to edit the values of an existing ListView row (i.e change the values of an Item and its Subitems). I need to do that programmatically and not by clicking on the ListView item at runtime to rename it.
just useLVM_SETITEMas documented.
I know a variable is a storage location paired with an associated symbolic name, now I write down this ``` int a=8; ``` My questions are: Where is8? Is the address of8same with the address ofa?
Variables are named location in memory. In other words, variables are just a place holder for a value. When you declare ``` int a = 8; ``` 8is stored at the memory location named asa. This integer literal can be accessed from that memory location usinga. ``` 0x12345 <--- Memory address +-------------+ | | | 8 | | | +-------------+ a <--- Name used to access value stored at location 0x12345 ``` You can think of it as putting the value assigned in a box with the variable name. ``` int a = 1; ```
I write a program, in c language. This program will ssh to another computer and touch a file periodically. However, sometimes the program crashes. How to restart this c program automatically when it crashes ? I know we can use cron job to do this, but I am not root, I don't know the password, too. I cannot access to /etc/init.d, too. It is on linux .
As mentioned in the comments, you can use a crontab job to ensure that a program runs.Here'sa quick introduction/reference. You do not need root access to create your own crontab job.
I know a variable is a storage location paired with an associated symbolic name, now I write down this ``` int a=8; ``` My questions are: Where is8? Is the address of8same with the address ofa?
Variables are named location in memory. In other words, variables are just a place holder for a value. When you declare ``` int a = 8; ``` 8is stored at the memory location named asa. This integer literal can be accessed from that memory location usinga. ``` 0x12345 <--- Memory address +-------------+ | | | 8 | | | +-------------+ a <--- Name used to access value stored at location 0x12345 ``` You can think of it as putting the value assigned in a box with the variable name. ``` int a = 1; ```
I write a program, in c language. This program will ssh to another computer and touch a file periodically. However, sometimes the program crashes. How to restart this c program automatically when it crashes ? I know we can use cron job to do this, but I am not root, I don't know the password, too. I cannot access to /etc/init.d, too. It is on linux .
As mentioned in the comments, you can use a crontab job to ensure that a program runs.Here'sa quick introduction/reference. You do not need root access to create your own crontab job.
Bind function is used to assign a name (a sockaddr struct) to a socket descriptor. Why is it required for TCP server but not TCP client ? And why it is required for bot UDP Client and server? I have also written correctly working code without using bind() in UDP Client . I do not understand why bind() is not used universally i.e. in all cases above.
Binding is only a required, if there is no other way for the computer to know which program to send the packets to. For connection less programs this is only the receiving end. Please have a look atsocket connect() vs bind()this post. There a much better job of explaining is done than I'm able to do. If you've got any questions after. Feel free to ask:)
TheLVM_GETITEMmessage documentation says: I'm not sure I understand what does the highlighted text means, does it mean that the buffer that I set to thepszTextmember could not be used, but rather thepszTextmember could map to a string that is placed elsewhere in memory?
I'm not sure I understand what does the highlighted text means, does it mean that the buffer that I set to the pszText member could not be used, but rather the pszText member could map to a string that is placed elsewhere in memory? Yes, that is exactly what it means.
The program is very simple, I have a handler function namedfintr()and the program is: ``` void fintr(); int main() { int i; signal(SIGINT,fintr); while(1) { printf("*"); } return 0; } void fintr() { printf("signal received"); exit(1); } ``` Can I putsignal(SIGINT,fintr);at the end of the functionmain()? And why do we have to put it in the beginning ofmain()?
Putting it at the end means it will come after thewhile (1) ...loop, so no, you can't put it in the end, because it would never be executed. Also, pay attention to the code you place inside signal handlers: It is not safe to callprintf()inside a signal handler.
I've initialized an array of structs with three items andit is showing 2for me !!! ``` #include <stdio.h> typedef struct record { int value; char *name; } record; int main (void) { record list[] = { (1, "one"), (2, "two"), (3, "three") }; int n = sizeof(list) / sizeof(record); printf("list's length: %i \n", n); return 0; } ``` What is happening here? Am I getting crazy?
Change initialization to: ``` record list[] = { {1, "one"}, {2, "two"}, {3, "three"} }; /* ^ ^ ^ ^ ^ ^ */ ``` Your initialization with(...)leaves effect similar to{"one", "two", "three"}and creates a struct array with elements{ {(int)"one", "two"}, {(int)"three", (char *)0} } comma operatorin C evaluates the expressions from left to right and discard all except the last. This is the reason why1,2and3are discarded.
What is the best way to do this? The templates seem to allow only for C++ (which is basically compatible with C, but not the same.) What is the proper way to do this? (A particular #define or whatever.) Any help would be appreciated.
The solution is simple and easy You create a new win32 console projectRemove the default .cpp fileAdd new .c file as you wishIn Properties, under C/C++ --> All Options, find "Compile as", then select "Compile as C code" Simple sanity check. This code doesn't work with C++ since "new" is a reserved word for C++.int new = 10;
Bind function is used to assign a name (a sockaddr struct) to a socket descriptor. Why is it required for TCP server but not TCP client ? And why it is required for bot UDP Client and server? I have also written correctly working code without using bind() in UDP Client . I do not understand why bind() is not used universally i.e. in all cases above.
Binding is only a required, if there is no other way for the computer to know which program to send the packets to. For connection less programs this is only the receiving end. Please have a look atsocket connect() vs bind()this post. There a much better job of explaining is done than I'm able to do. If you've got any questions after. Feel free to ask:)
TheLVM_GETITEMmessage documentation says: I'm not sure I understand what does the highlighted text means, does it mean that the buffer that I set to thepszTextmember could not be used, but rather thepszTextmember could map to a string that is placed elsewhere in memory?
I'm not sure I understand what does the highlighted text means, does it mean that the buffer that I set to the pszText member could not be used, but rather the pszText member could map to a string that is placed elsewhere in memory? Yes, that is exactly what it means.
The program is very simple, I have a handler function namedfintr()and the program is: ``` void fintr(); int main() { int i; signal(SIGINT,fintr); while(1) { printf("*"); } return 0; } void fintr() { printf("signal received"); exit(1); } ``` Can I putsignal(SIGINT,fintr);at the end of the functionmain()? And why do we have to put it in the beginning ofmain()?
Putting it at the end means it will come after thewhile (1) ...loop, so no, you can't put it in the end, because it would never be executed. Also, pay attention to the code you place inside signal handlers: It is not safe to callprintf()inside a signal handler.
I've initialized an array of structs with three items andit is showing 2for me !!! ``` #include <stdio.h> typedef struct record { int value; char *name; } record; int main (void) { record list[] = { (1, "one"), (2, "two"), (3, "three") }; int n = sizeof(list) / sizeof(record); printf("list's length: %i \n", n); return 0; } ``` What is happening here? Am I getting crazy?
Change initialization to: ``` record list[] = { {1, "one"}, {2, "two"}, {3, "three"} }; /* ^ ^ ^ ^ ^ ^ */ ``` Your initialization with(...)leaves effect similar to{"one", "two", "three"}and creates a struct array with elements{ {(int)"one", "two"}, {(int)"three", (char *)0} } comma operatorin C evaluates the expressions from left to right and discard all except the last. This is the reason why1,2and3are discarded.
What is the best way to do this? The templates seem to allow only for C++ (which is basically compatible with C, but not the same.) What is the proper way to do this? (A particular #define or whatever.) Any help would be appreciated.
The solution is simple and easy You create a new win32 console projectRemove the default .cpp fileAdd new .c file as you wishIn Properties, under C/C++ --> All Options, find "Compile as", then select "Compile as C code" Simple sanity check. This code doesn't work with C++ since "new" is a reserved word for C++.int new = 10;
What is the best way to do this? The templates seem to allow only for C++ (which is basically compatible with C, but not the same.) What is the proper way to do this? (A particular #define or whatever.) Any help would be appreciated.
The solution is simple and easy You create a new win32 console projectRemove the default .cpp fileAdd new .c file as you wishIn Properties, under C/C++ --> All Options, find "Compile as", then select "Compile as C code" Simple sanity check. This code doesn't work with C++ since "new" is a reserved word for C++.int new = 10;
``` #include<stdio.h> int main() { int i=0, k=0, m; m = ++i || ++k; printf("%d, %d, %d\n", i, k, m); return 0; } ``` returns ``` 1,0,1 ``` Why is k = 0 and not 1? what is the effect of the ||-operator on the ++k? Thanks! example:https://ideone.com/Fjsbii
In||OR , if first condition is true, it will not check second condition.(it will skip 2nd condition). As ``` m = ++i || ++k; ``` in this condition after++i, value ofiwill become1, as first condition istrue, so it will skip second condition. so the operation++kwill not be performed.And hencekwill remain0. Same as if you are using&&, and first condition isfalseit will skip second condition. and result will be0(false).
If I want to allocate memory in function: ``` char* allocate() { char *cp = (char*)malloc(10); ... return cp; } ``` can I use the returned content incpfrommain()? and how to freecp?
can I use the returned content in cp in main()? Yes, you can. and how to free cp? Using ``` free(cp); // Replace cp with the name of the pointer if you are using it in another function ``` Also, you should not cast the result ofmalloc(and family) in C
I have the following makefile structure ``` # Default optimization level O ?= 2 TESTS = $(patsubst %.c,%,$(sort $(wildcard test[0-9][0-9][0-9].c))) all: $(TESTS) hhtest -include build/rules.mk LIBS = -lm %.o: %.c $(BUILDSTAMP) $(call run,$(CC) $(CPPFLAGS) $(CFLAGS) -O$(O) $(DEPCFLAGS) -o $@ -c,COMPILE,$<) test%: test%.o m61.o $(call run,$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) $(LIBS),LINK $@) hhtest: hhtest.o m61.o $(call run,$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) $(LIBS),LINK $@) ``` And when I debugging I have<optimized out>value: ``` print ptr <optimized out> ``` How to disable that issue?
Your code seems to be structured in such a way (i.e. you pass-O$(O)to cc) that you should be able to say: ``` O ?= 0 ``` Instead ofO ?= 2.
This is part of a larger program to emulate the cat command in unix. Right now trying to take input and send it to stdout: ``` char in[1000]; int c = 0; while ((c = getchar()) != EOF) { fgets(in,1000,stdin); fputs(in, stdout); } ``` This sends output to stdout, but in every case it skips the first letter. For instance, if I type the wordComputer I get back: ``` omputer ```
Your problem is all abouteating. ``` c = getchar() ``` This line, as many I/O operations inC consume your buffer. Meaning that when you have say0123456789after yourgetchar()you're left with123456789in your buffer. What you want to do is use the same functions to control the input and to store it, so something like getting rid of thegetchar()should do the trick : ``` while (fgets(in,1000,stdin) != NULL) { fputs(in, stdout); } ``` And there you have it !
I did a simple program to light a led. ``` #define _XTAL_FREQ 19660800 #define USE_AND_MASKS #include <xc.h> #include <pic18f46k22.h> #include <stdio.h> #include <stdlib.h> void main(void) { TRISA=0; PORTA=0; PORTA=0x5A; while (1) { } } ``` I use a PIC18F46k22 and a XC8 compiler. The issue is that when I compile the program the compiler gives the messageno chip name specified; use "PICC18 --CHIPINFO" Do you know where is the problem?
When you compile, add--chip=18f452to your compilation flag. That should do the trick. Basically you need to tell your compiler what kind of chip you're willing to work with, since XC8 can build for different kinds of chip. Have fun with thoses chips anyway !
This question already has answers here:returning a local variable from function in C [duplicate](4 answers)Closed8 years ago. In our lecture we had the following example: ``` int *foo(int x) { return &x; } int* pt = foo(x); *pt = 17; ``` It was shown as a bad example, but not further explained. Why is this bad?
Bad thing is that you are returning a pointer to an automatic local variable. It will no longer be exist once function returns and then the statement*pt = 17;will cause program to behave erratically. A pointer tostaticlocal variable can be returned. ``` int *foo() { static int x; return &x; } int* pt = foo(); *pt = 17; ```
This is part of a larger program to emulate the cat command in unix. Right now trying to take input and send it to stdout: ``` char in[1000]; int c = 0; while ((c = getchar()) != EOF) { fgets(in,1000,stdin); fputs(in, stdout); } ``` This sends output to stdout, but in every case it skips the first letter. For instance, if I type the wordComputer I get back: ``` omputer ```
Your problem is all abouteating. ``` c = getchar() ``` This line, as many I/O operations inC consume your buffer. Meaning that when you have say0123456789after yourgetchar()you're left with123456789in your buffer. What you want to do is use the same functions to control the input and to store it, so something like getting rid of thegetchar()should do the trick : ``` while (fgets(in,1000,stdin) != NULL) { fputs(in, stdout); } ``` And there you have it !
I did a simple program to light a led. ``` #define _XTAL_FREQ 19660800 #define USE_AND_MASKS #include <xc.h> #include <pic18f46k22.h> #include <stdio.h> #include <stdlib.h> void main(void) { TRISA=0; PORTA=0; PORTA=0x5A; while (1) { } } ``` I use a PIC18F46k22 and a XC8 compiler. The issue is that when I compile the program the compiler gives the messageno chip name specified; use "PICC18 --CHIPINFO" Do you know where is the problem?
When you compile, add--chip=18f452to your compilation flag. That should do the trick. Basically you need to tell your compiler what kind of chip you're willing to work with, since XC8 can build for different kinds of chip. Have fun with thoses chips anyway !
This question already has answers here:returning a local variable from function in C [duplicate](4 answers)Closed8 years ago. In our lecture we had the following example: ``` int *foo(int x) { return &x; } int* pt = foo(x); *pt = 17; ``` It was shown as a bad example, but not further explained. Why is this bad?
Bad thing is that you are returning a pointer to an automatic local variable. It will no longer be exist once function returns and then the statement*pt = 17;will cause program to behave erratically. A pointer tostaticlocal variable can be returned. ``` int *foo() { static int x; return &x; } int* pt = foo(); *pt = 17; ```
I have a 2D array like this and I want a pointer to it. Currently I have this: ``` char* recv_args_msg_queue[20]; char** ref_temp = &recv_args_msg_queue[0]; char*** ref_queue = &ref_temp; ``` But I feel my way is really dumb. Is there a way to do it on one line? Note: char* recv_args_msg_queue[20];is later in my code allocated properly to be an array. I just wanted dynamic allocation otherwise I could have wrote: char recv_args_msg_queue[20][another_number_here];
Using atypedef for your array typewill make easier getting a pointer to it. Your code would look like this: ``` typedef char* msg_queue20[20]; msg_queue20 recv_args_msg_queue; msg_queue20* ref_queue = &recv_args_msg_queue; ``` Take care of reading the link I posted, as it containsimportant recommendations.
Opening some legacy code in Notepad++ and notice a few occurrences ofFFcharacter below function comment headers. They are ASCII code 12 which is the Form Feed character. Are FF characters valid in MISRA C2 standard please? Apologies I don't have access to PC-Lint/QAC checker.
You appear to be talking about a commercial product, whose announcements give no useful information, e.g., thispress release. Form feed is stated explicitly to be part of the character set inISO/IEC 9899:199 (E)5.2.1 Character sets. If the tool advised you not to use a documented, standard feature, that would be a defect in the tool itself. A comparable issue would be whether to allow tab characters in leading whitespace on a line. Given that context, the use of form feed characters is astylisticissue unrelated to static analysis, and I would not expect the two to be confused in a commercial product.
As discussed inthis question, GCC defines nonstandard unary operator&&to take the address of a label. Why does it define a new operator, instead of using the existing semantics of the&operator, and/or the semantics of functions (wherefooand&fooboth yield the address of the functionfoo())?
Label names do not interfere with other identifiers, because they are only used in gotos. A variable and a label can have the same name, and in standard C and C++ it's always clear from the context what is meant. So this is perfectly valid: ``` name: int name; name = 4; // refers to the variable goto name; // refers to the label ``` The distinction between & and && is thus needed so the compiler knows what kind of name to expect: ``` &name; // refers to the variable &&name; // refers to the label ```
I'm using theGNU Debuggeron Linux to debug C programs locally, but how do I do it on remote applications? Locally, a program can be ran with ``` ./programName ``` Gdb can be attached (without welcome text) by writing ``` gdb -q programName ``` To connect to the remote application I have to sign in to the "main" server then switch to another one: ``` netcat serverName portNumber ``` and it will automatically execute the remote application. Gdb is available on that machine. I triedgdb netcat serverName portNumberbut that didn't work.
You should launch gdbserver on the remote target like this: On Target Machine, ``` $ gdbserver ip_address_host:port programName ``` On Host Machine, ``` $ gdb programName (gdb) target remote ip_address_server:port ```
In Dennis M Richies book "C programming language" it talks about pointers, and one of the examples is swapping two pointers: ``` void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp } ``` What's confusing me slightly is*a = *b. Ifbis already a pointer being passed in, why does it need to be dereferenced before assigning it to*a? Why wouldn'ta = bwork as their both pointers already?
a = bmeans you are assigning address ofbtoawhich not the right way. for swapping two numbers means you need to getvalue at that addressand that value you have to swap.so right way is to do*a = *b;i.e value at the address ofbassigned to value at the address ofa.
I have a function in my program that takes 3 arguments. Some times in the code there is a macro defining 2 of these parameters. So this: ``` void func(int x, int y, int z){...} ``` Can be invoked like this: ``` #define PAR 10,20 int z = 3; func(PAR, z); ``` Now, I need to change my code so that the function is called like a macro for another function. ``` #define func(X,Y,Z) func2(X,Y,Z,#Z) ``` This works fine if X and Y are really passed as variables. Is there any way to make it work also with the macro PAR? I'm using GCC 4.6
You can do this with an extra level of indirection, (ab)using variadic macros: ``` #include <stdio.h> #define PAR 2,3 #define F(...) G(__VA_ARGS__) #define G(a,b,c) H(a,b,c) void H(int a, int b, int c) { printf("%d %d %d\n", a , b, c); } int main() { F(PAR, 42); return 0; } ``` There is probably a better solution for the underlying problem.
``` dataBuf[1] = acos(0.130f); ``` This is the code I'm running but when I print out the result, it comes out as 1 instead of 82. dataBuf is an int16_t array. All the other math.h functions work fine with the conversion but the trig ones don't work.
The trigonometric functions inmath.huse radians, not degrees. You can convert the radians to degrees by multiplying by180 / pi, (57.29577951308232). acos(0.13)would return1.440427347091751radians which multiplied by57.29577951308232gives the result of82.53040768358306degrees.
So I have valgrind complaining with this error in this function: ``` int getMembersNum(Party party){ assert(party != NULL); int i = 0; while (party->members[i] != NULL && i < party->maxMembersNum) <-- HERE i++; return i; ``` } Party is a pointer to a struct andparty->membersis of typechar**. When initialized withmallocall ofparty->memberscells are set toNULL. What am I missing?
You need to test before you use. ``` while (party->members[i] != NULL && i < party->maxMembersNum) ``` should be ``` while (i < party->maxMembersNum && party->members[i] != NULL) ```
When calling a function in c (programming an arduino), will that function finish before executing the next line of code in the original function? See comments in example below: ``` void loop() { duration = random(750, 1500); advertise("111", duration); // <-- will this function fully complete int delayDuration = random (300,500); // <--before executing this line of code? delay(delayDuration); } ```
Yes. Code execution in athreadhappens sequentially. The called function shouldreturnand the execution shall continue from the next statement in the function that called.
I'm looking for a message handler for Julia, because I want to integrate it in a bigger project with other services. The other services are using RabbitMQ, but I have not been able to find any RabbitMQ or ActiveMQ drivers for Julia. Is anyone aware of a message handler driver for Julia or should I just start implementing it on my own? [UPDATE] I just noticed that Julia is able to call C and Fortran code, so I thought perhaps I could use the RabbitMQ driver for C. What do you think about this idea? Thank you!
I'm not aware of one but have only done a cursory search. There are many Julia libraries which simply wrap an existing and well-understood C API. While getting the package build and install correct this way can be slightly tricky, it saves re-implementing complex protocols. There doesn't seem to be much dogma in the community about trying to make 'pure Julia' packages where there's no clear benefit.
I have to allocate huge amount of memory frequently in my kernel driver. Which memory allocation api is better to use and why ?
If you need large allocations,kmalloc()is not a good idea, because once the physical address space has become fragmented, largekmalloc()allocations will frequently fail. Sovmalloc()/vfree()is most probably the way to go - unless you need to share the buffer with the hardware device, in which case look into the CMA (Contiguous Memory Allocator),dma_alloc_from_contiguous()/dma_release_from_contiguous().
I have twochar's ,s1ands2and have a statement ``` if ((s1 && !s2) || (!s1 && s2)) ``` but I feel like that is redundant since the calculation involves looking at boths1and!s1separately, and the same fors2and!s2. For, by looking ats1ands2, you already have the information that underlies!s1and!s2. Is there a way to compress this statement?
That statement is a logical-exclusive-or for which there is no built-in operator. Under certain restrictions, you can convert it to a bitwise-exclusive-or^, but more generally it can be written as ``` if ( !s1 != !s2 ) ``` The logicalnotoperator!will convert a 0 to the logicaltruevalue, and will convert any other value to the logicalfalsevalue. The results can then be tested with!=.
The second field of Linux/proc/%d/statfiles is a command name enclosed in parentheses, which itself might contain parentheses as part of the command. What is the correct way to deal with this when parsing thestatpseudo-files? My inclination would be to find the last')'(e.g. usingstrrchron the whole file contents) but I'm concerned this might not be future-proof against addition of new fields at the end. Is there any documentation of the correct way to handle this issue?
Looking for the last ) is the best way to go about it and will most likely be future-proof. strrchris used for parsing in theprocps source(the ps family of functions,ps,top,kill, etc). ``` S = strchr(S, '(') + 1; tmp = strrchr(S, ')'); num = tmp - S; if(unlikely(num >= sizeof P->cmd)) num = sizeof P->cmd - 1; memcpy(P->cmd, S, num); P->cmd[num] = '\0'; S = tmp + 2; // skip ") " ```
I have a C array as follows: ``` unsigned long arr[10]; ``` On my machine,unsigned longis 8 bytes. I have a situation where I write 4 bytes using arr[0], and then need to find the address of the next byte in the array. ``` void * ptr = arr[0] + (sizeof(unsigned long) / 2); ``` Will the above work ?
No it will not. You should cast tochar*first and then do the pointer arithmetic. ``` void * ptr = ((char*) &arr[0]) + (sizeof(unsigned long) / 2); ```
I have a C header for which I want to write an introductory comment. Like this: ``` /** * @brief Provides stuff for my great program. */ #ifndef MYHEADER_H #define MYHEADER_H #define __USE_GLIBC #endif ``` Furthermore, I have this Doxyfile: ``` FULL_PATH_NAMES = YES TAB_SIZE = 8 OPTIMIZE_OUTPUT_FOR_C = YES RECURSIVE = YES INPUT = . EXTRACT_ALL = YES QUIET = YES EXTRACT_STATIC = YES ``` When I run Doxygen now, it generates HTML and LaTeX documentation, but the brief description ends up documenting the macro instead of the whole file. So how can I provide Doxygen with a brief description of the file?
You should use the@filemacro to denote this comment related to the file as a whole: ``` /** * @file myheader.h * @brief Provides stuff for my great program. */ ```
How can I get theASCIIrepresentation of hexadecimal values in the memory by examining ingdb? The gdb commandx/[repeatCount] [memoryAddress]gives me hexadecimal 32-bit values starting atmemoryAddressrepeatCounttimes but I want the readable text/String which is represented by this data. How do I do that?Thispage doesn't seem to tell. For instance I get the following by examining: ``` 0x41414141 ``` What I want to see instead or as well is this: ``` AAAA ``` Like an ordinaryHex <-> ASCII converter.
Nevermind, I need to use theformat lettersforString. ``` x/[repeatCount]s [memoryAddress] ``` Found by typing ``` help x ``` and reading the help documentation. <_<
I have twochar's ,s1ands2and have a statement ``` if ((s1 && !s2) || (!s1 && s2)) ``` but I feel like that is redundant since the calculation involves looking at boths1and!s1separately, and the same fors2and!s2. For, by looking ats1ands2, you already have the information that underlies!s1and!s2. Is there a way to compress this statement?
That statement is a logical-exclusive-or for which there is no built-in operator. Under certain restrictions, you can convert it to a bitwise-exclusive-or^, but more generally it can be written as ``` if ( !s1 != !s2 ) ``` The logicalnotoperator!will convert a 0 to the logicaltruevalue, and will convert any other value to the logicalfalsevalue. The results can then be tested with!=.
The second field of Linux/proc/%d/statfiles is a command name enclosed in parentheses, which itself might contain parentheses as part of the command. What is the correct way to deal with this when parsing thestatpseudo-files? My inclination would be to find the last')'(e.g. usingstrrchron the whole file contents) but I'm concerned this might not be future-proof against addition of new fields at the end. Is there any documentation of the correct way to handle this issue?
Looking for the last ) is the best way to go about it and will most likely be future-proof. strrchris used for parsing in theprocps source(the ps family of functions,ps,top,kill, etc). ``` S = strchr(S, '(') + 1; tmp = strrchr(S, ')'); num = tmp - S; if(unlikely(num >= sizeof P->cmd)) num = sizeof P->cmd - 1; memcpy(P->cmd, S, num); P->cmd[num] = '\0'; S = tmp + 2; // skip ") " ```
I have a C array as follows: ``` unsigned long arr[10]; ``` On my machine,unsigned longis 8 bytes. I have a situation where I write 4 bytes using arr[0], and then need to find the address of the next byte in the array. ``` void * ptr = arr[0] + (sizeof(unsigned long) / 2); ``` Will the above work ?
No it will not. You should cast tochar*first and then do the pointer arithmetic. ``` void * ptr = ((char*) &arr[0]) + (sizeof(unsigned long) / 2); ```
I have a C header for which I want to write an introductory comment. Like this: ``` /** * @brief Provides stuff for my great program. */ #ifndef MYHEADER_H #define MYHEADER_H #define __USE_GLIBC #endif ``` Furthermore, I have this Doxyfile: ``` FULL_PATH_NAMES = YES TAB_SIZE = 8 OPTIMIZE_OUTPUT_FOR_C = YES RECURSIVE = YES INPUT = . EXTRACT_ALL = YES QUIET = YES EXTRACT_STATIC = YES ``` When I run Doxygen now, it generates HTML and LaTeX documentation, but the brief description ends up documenting the macro instead of the whole file. So how can I provide Doxygen with a brief description of the file?
You should use the@filemacro to denote this comment related to the file as a whole: ``` /** * @file myheader.h * @brief Provides stuff for my great program. */ ```