question
stringlengths
25
894
answer
stringlengths
4
863
I have this code and I intend to create a set of 4 decks, the problem is that in the suits, after the card 51 the result of the division gives 4 and the arrays of the suits do not return the initial position, how can I solve this situation? Thank you ``` #include <stdio.h> #define NCARTAS 52 int main() { const char *numero[]= {"A","2","3","4","5","6","7","8","9","10","V","D","R"}; const char *naipes[]= {"P","O","C","E"}; char baralho[208]; int posNumero,posNaipe; for(int i=0; i<208; i++) { baralho[i]=i; posNumero=i%13; posNaipe=i/13; printf("%s%s \n", numero[posNumero],naipes[posNaipe]); } } ```
``` posNaipe = i % NCARTAS / 13; ``` would do it. This is also a touchstone for your knowledge of operator precedence and associativity.
How can I exit the while loop when stdin line is empty? ``` #include <unistd.h> #include <stdio.h> int main(){ FILE* stream = popen("sort", "w"); char *line = NULL; size_t size; while (getline(&line, &size, stdin)) { fprintf(stream,"%s\n", line); } pclose(stream); return 0; } ``` I tried checking the length of line and checking ifgetline != -1and it doesn't work.
The problem you have is the newline you read. if you add ``` if (*line == '\n') break; ``` to your loop, it will probably work as intended. Testing getline() for a -1 return value is a good idea; you might encounter an End Of File instead of an empty line
I'm imagining readingbyte by bytewould be very inefficient, but reading in bulks would almost always read more than needed, requiring to store the rest of the read input in a global context for all subsequent read operations to find. What am I missing?
The prototype is: ``` ssize_t getline(char **lineptr, size_t *n, FILE *stream); ``` So it's clearly usingFILE, which is already buffered. So reading character-by-character is not inefficient at all.
I have this code and I intend to create a set of 4 decks, the problem is that in the suits, after the card 51 the result of the division gives 4 and the arrays of the suits do not return the initial position, how can I solve this situation? Thank you ``` #include <stdio.h> #define NCARTAS 52 int main() { const char *numero[]= {"A","2","3","4","5","6","7","8","9","10","V","D","R"}; const char *naipes[]= {"P","O","C","E"}; char baralho[208]; int posNumero,posNaipe; for(int i=0; i<208; i++) { baralho[i]=i; posNumero=i%13; posNaipe=i/13; printf("%s%s \n", numero[posNumero],naipes[posNaipe]); } } ```
``` posNaipe = i % NCARTAS / 13; ``` would do it. This is also a touchstone for your knowledge of operator precedence and associativity.
I'm imagining readingbyte by bytewould be very inefficient, but reading in bulks would almost always read more than needed, requiring to store the rest of the read input in a global context for all subsequent read operations to find. What am I missing?
The prototype is: ``` ssize_t getline(char **lineptr, size_t *n, FILE *stream); ``` So it's clearly usingFILE, which is already buffered. So reading character-by-character is not inefficient at all.
I have this code and I intend to create a set of 4 decks, the problem is that in the suits, after the card 51 the result of the division gives 4 and the arrays of the suits do not return the initial position, how can I solve this situation? Thank you ``` #include <stdio.h> #define NCARTAS 52 int main() { const char *numero[]= {"A","2","3","4","5","6","7","8","9","10","V","D","R"}; const char *naipes[]= {"P","O","C","E"}; char baralho[208]; int posNumero,posNaipe; for(int i=0; i<208; i++) { baralho[i]=i; posNumero=i%13; posNaipe=i/13; printf("%s%s \n", numero[posNumero],naipes[posNaipe]); } } ```
``` posNaipe = i % NCARTAS / 13; ``` would do it. This is also a touchstone for your knowledge of operator precedence and associativity.
Sanitization keeps code clean, removing the "dirty" injections. In HTML and JavaScript, this is accomplished by removing unsafe tags or escaping user input. What does "sanitization" mean to C?
It's a compiler feature (at least in Clang) that tries to detect memory addresses that are invalid, such as those that are out-of-bounds, or that are still being used after they are freed. You can enable it with the-fsanitize=addresscompiler flag. Seeherefor more info.
I have simple bash script ``` #!/bin/bash make ./code1_test/test_syn1 ./code2_test/test_syn2 ./code3_test/test_syn3 ``` test_syn are my program tests. In every of these programs, I'm using fopen command to open .txt file. If I run programs from command line, I have a correct test output, but when I'm using this bash script, fopen return me NULL, so I can't open my .txt files and I can't run tests. Why is this happening, and how can I fix this?
If you’re usingfopen()with a relative path, you should execute the script from its directory. Try this: ``` #!/bin/bash make (cd code1_test/ && exec ./test_syn1) (cd code2_test/ && exec ./test_syn2) (cd code3_test/ && exec ./test_syn3) ``` Otherwise your program tries to open your.txtin the directory from where your run your Bash script, that’s not what you want. If you want to be able to run your program from anywhere, you might try not to use a relative path when youfopen().
Given a path ``` /level1/level2/level3/level4 ``` I want to be able to split this string such that I can retrieve each individual entry,i.e "level1", "level2", "level3", "level4". Now my first idea was usingstrtok, but apparently most people recommendagainstusing this function. What is another approach so that I can pass in astring (char* path)and get each entry split at "/".
strtokis actually the preferred way to tokenize a string such as this. You just need to be aware that: The original string is modifiedThe function uses static data during its parsing, so it's not thread safe and you can't interleave parsing of two separate strings. If you don't want the original string modified, make a copy usingstrdupand work on the copy, then copy the results as needed. If you need to worry about multiple threads or interleaved usage, usestrtok_rinstead which has an additional state parameter.
How do I print character 128 from extended ascii with write function in c language? ``` #include <unistd.h> int main(void) { int c; c = 128; write(1, &c, 1); return(0); } ``` Output:� Ascii extended 128: Ç
Using awchar_t: ``` #include <stdio.h> #include <wchar.h> #include <locale.h> int main(void) { wchar_t c; setlocale(LC_ALL, ""); for (c = 128; c < 256; c++) { wprintf(L"%lc\n", c); } return 0; } ```
I can determine if my application last terminated due to a call toexit()by usingatexitor a destructor function. Is there any way to determine if my application last terminated due to_exit()?
From theman page The function _exit() terminates the calling process "immediately". Any open file descriptors belonging to the process are closed; any children of the process are inherited by process 1, init, and the process's parent is sent a SIGCHLD signal.The value status is returned to the parent process as the process's exit status, and can be collected using one of the wait(2) family of calls. and you cannot expectatexit()to be called. However, similarly toexit, a status is set and returned from_exitthat you might want to test from a calling script, for instance. (e.g.exit(0);and_exit(1);, if the returned value is 1 you know that_exitwas used, notexit.)
I am getting error when i am running this code ``` int row1=2,col1=2; int mat1[row1][col1]= { {1,5}, {4,6} }; ``` What is wrong with this code?? IDE: CodeBlocks error: variable-sized object may not be initialized|
What you have here is a variable length array. Such an array cannot be initialized. You can only initialize an array if the dimensions are constants (i.e. numeric constants, not variables declared asconst): ``` int mat1[2][2]= { {1,5}, {4,6} }; ```
How can you format an double like 12345.0 to be printed as 1.234E+04? I want to print something like this: ``` int N = 1024; int time = 3476; printf("%f", (N/time)); ``` Where the output would be:3.394531E+00
You could either usefloatfor your variables or cast some of the variables to floating-point type like this: ``` printf("%f", ((float)N/time)); ``` If you want to have your numbers always inScientific notationhttp://www.cplusplus.com/reference/cstdio/printf/you can replace the format with "%e". It's worth noting thatprintfexpectsdoubleby default for allf F e E g G a A.
I am getting error when i am running this code ``` int row1=2,col1=2; int mat1[row1][col1]= { {1,5}, {4,6} }; ``` What is wrong with this code?? IDE: CodeBlocks error: variable-sized object may not be initialized|
What you have here is a variable length array. Such an array cannot be initialized. You can only initialize an array if the dimensions are constants (i.e. numeric constants, not variables declared asconst): ``` int mat1[2][2]= { {1,5}, {4,6} }; ```
How can you format an double like 12345.0 to be printed as 1.234E+04? I want to print something like this: ``` int N = 1024; int time = 3476; printf("%f", (N/time)); ``` Where the output would be:3.394531E+00
You could either usefloatfor your variables or cast some of the variables to floating-point type like this: ``` printf("%f", ((float)N/time)); ``` If you want to have your numbers always inScientific notationhttp://www.cplusplus.com/reference/cstdio/printf/you can replace the format with "%e". It's worth noting thatprintfexpectsdoubleby default for allf F e E g G a A.
How do I handle more than one condition (with different boolean expressions) in a UML state machine transition (as guard)? Example: In this example I would like to add more than only one condition (Tries < 3) in the transition from "logging in" to "Logged In" like discribed in the note. How to handle this UML compliant?
Simply spoken (and to focus on the needed step) put a boolean condition like above in theGuard. This can be any text. You can write C-style or plain text. I'm not sure about OCL here, but that's for academic purpose anyway (my opinion). N.B. Your diagram showsTries = 3which should be aGuardalso (i.e.[Tries = 3]) rather than aName.
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.Closed5 years ago.Improve this question I wanted to create a cryptographic secure octet in c. I've heard, that therand()function is not secure enough so I need an alternative. Do you have any ideas how to deal with this problem? Would be glad if someone can help me.
Under Linux, read /dev/urandom to get some random seed, then srandom(seed). On bare metal, reading ADC values + some mathematics helped me in past.
I am coding a program that will take an array, heapify it, then find the kth smallest element. From my textbook I was able to get a lot of the algorithms needed down, but I am stuck now, because I am receiving a segmentation fault whenever I attempt to test the program. In the textbook in the struct it has PQ_SIZE as size of q, but I could not figure out why or how to make that work, so I made it 6 because the n I have been testing with is 5, however whenever I compile the program then enter 5 as my first number, I receive a segmentation fault even though it is less than 6. I am just in general confused and any advice at all regarding my code would be much appreciated, thank you.
inmain()you passed*heapwhich is uninitialized pointer topq_init()where you are assigning value to its member ``` priority_queue* heap; pq_init(heap); ``` This is going to lead undefined behaviour, you need to allocate memory toheapprior to using it
I'm a noob at shellcodes and I'm trying to understand all scenarios. I have found many codes to test my shellcodes in C, but to my surprise they are very unreadeable and I can't understand neither this code: ``` int (*func)(); func = (int (*)()) code; (int)(*func)(); ``` Or this one: ``` int (*ret)() = (int(*)())code; ret(); ``` Is this an equivalent toeval()in Javascript? And how doest it work?
int (*func)();is a pointer to a function (taking no parameters in C++) that returns anint. (*func)();or justfunc();calls the function pointed to. (int (*)()) code;is a nasty type cast telling the compiler thatcodeis pointing to such a function. If it is not, but you still try to call the function, the program is invalid and anything can happen. "Anything" includes actually executing the shell code, or crashing, or something else. The language standard doesn't say.
I am attempting to debug the following line of code in GDB: ``` p=((uint32 *) tiff_pixels)+image->columns*i; ``` p iyeilds8 p columnsyeilds32 p image->columns*icorrectly yields256 p ((uint32 *) tiff_pixels)yields0x619000008780 so I expect((uint32 *) tiff_pixels)+image->columns*ito yield0x619000008880but I get0x619000008b80instead. I am probably making some trivial error/assumption here but I cannot seem to figure it out.
You forgot to multiply by the size of each pixel, which is 4 bytes. ``` p=((uint32 *) tiff_pixels)+image->columns*i; ``` You've casttiff_pixelsto be a pointer to auint32. Eachuint32is four bytes. So if you add one to the pointer, it will point to thenextuint32, which is four bytes after the first one.
I want to know whether threads created usingpthread.hlibrary are using one core, or they are running in multiple cores.
A newly created thread has no affinity, and will be shuffled around the process as deemed best by the system. If you need to pin it to a specific core,this answer provides detailsfor setting affinity to a specific pthread.
Hi this is my code for calculating pascal triangle but it runs error : has stopped working... why ? i think its error is in paskal function ``` #include <stdio.h> long paskal(int,int); int main (void) { int n = 0 ; int m = 0 ; int k = 0 ; scanf("%d" , &n); for(k = 1 ; n >= k ; ) { for( m = 1 ; k >= m ; m++ ) { long f = paskal(k , m ) ; printf("%ld" , f); } printf("\n"); k++; } return 0; } long paskal( int n , int i ) { if(n == 1 && i == 1 ) return 1 ; else return paskal(n-1,i) + paskal(n-1,i-1); } ```
The limit-conditions are not correct. The correct way to put the limit conditions is ``` if(n == 1 || i == 1 ) return 1 ; else .... ```
Is there any macro in GCC that contain compilation flags used to compile the program? I want something like this: ``` printf("Compilation flags: %s", __FLAGS__); ``` To output for example: ``` Compilation flags: -02 -g ```
Short answer: No. Slightly longer answer: Even if there was, your code would become non-portable. Projects needing this sort of functionality let the build system do it, e.g. by having all the flags in aCFLAGSvariable inmakeand have a rule create aconfig.hputting all these flags in a#definethere.
I am really confused, but cannot to do simple task as it seems: I simply need to set number of bits in byte. For example: I need 5 bits set. So I need0xb00011111. Is it possible to do this without loop? Also I'd not like to write lot of#definestoo.
For any integernless than the number of bits in the word, the mask you need is: ``` const unsigned int mask = (1u << n) - 1; ``` No loop required. A simple function using this: ``` unsigned int set_lsbs(unsigned int n) { return (1u << n) - 1; } ``` The ten first results are: ``` 0: 0x0 1: 0x1 2: 0x3 3: 0x7 4: 0xf 5: 0x1f 6: 0x3f 7: 0x7f 8: 0xff 9: 0x1ff ``` Note: the syntax0xb00011111is not not a binary literal, that 'b' is simply interpreted as a hex digit.
I was given this code to look into, and this code is filled with these arrow type symbols: Those symbols are seen around variable declarations like in the image, and they disappear if I copy them and try to paste them into web browser. Are they like some sort of custom symbol from different keyboard? What could possibly be their functions? I checked preprocessor macros, and it does not have any macro defined for arrow symbols.
Those arrow symbols are actually visualizations of the tab character. What you actually have is this: ``` void *ptr; int len = strlen( string ) + 1; ``` The arrows are there just to show you that there are tabs in the code.
While I was browsing cppreference, I saw a strange type array in function parameters like this: ``` void f(double x[volatile], const double y[volatile]); ``` So, What is the purpose of thevolatilekeyword appearing inside an array subscript? What does it do?
Thevolatilekeyword is used to declare an array type of a function parameter. Here,double x[volatile]is equivalent todouble * volatile x. Thecppreferencesays : In a function declaration,the keywordvolatilemay appear inside the square brackets that are used to declare an array type of a function parameter.It qualifies the pointer type to which the array type is transformed. The following two declarations declare the same function:void f(double x[volatile], const double y[volatile]); void f(double * volatile x, const double * volatile y); This syntax only valid in C language in function parameters.
I would like to create a 2D string array so i try that: ``` char **value[] = {"integer", "char", "string", "octal", "hexa_min", "hexa_maj", "pointer", "integer", "bin_int", "non_printable", "unsigned_int", NULL}; ``` but i have a warning for each str of my array. https://pastebin.com/bwJtB1CR Thanks for your help ;)
``` char value[12][30] = { "integer", "char", "string", "octal", "hexa_min", "hexa_maj", "pointer", "integer", "bin_int", "non_printable", "unsigned_int", "NULL"}; ``` Always remember when you declare 2D array as follows: array2D[No_Of_Rows][No_Of_Coloums];
Any time I had the need of a Boolean type I was told to either create one, or better yet, usestdbool.h. Sincestdbool.husestypedef bool _Bool, is there a reason to use the header instead just using type_Bool? Is it just for the additional macros (/* #define true 1 #define false 0 */)?
The obvious type to add into the language wasbool. But unfortunately, plenty of code was written that includedboolin other shapes and forms. Recall that support for a boolean type was added only in C99. So the C language committee had no choice but to pull out a reserved identifier for it (_Bool). But, since the obvious choice of type name is still the same,stdbool.hwas added to allow users the obvious name. That way, if your code didn't have a home-brewedbool, you could use the built in one. So do indeed usestdbool.hif you aren't bound to some existing home-brewedbool. It will be the standard type, with all the benefits that type brings in.
How doeswhileterminate when count becomes 0 without a condition likecount!=0? ``` #include<stdio.h> static int count=5; void func(void); void main() { while(count--) { func(); } } void func(void) { static int i=5; i++; printf("%d\t%d\n",i,count); } ```
In C Language0( Zero ) is considered as being false. When you use0in any conditional statement, it will evaluate as false. Ex:if( 0 )evaluates as false and the else code (if any) is triggered. In your code, whencount--equals0, the while condition evaluates towhile (0). Since an iteration of thewhileloop will only be triggered when the condition evaluates as true, thewhileloop will terminate at this point.
Is there any way to print multiple strings in C based on only one condition for example ``` int main(int argc, char const *argv[]) { printf("%s %s\n", condition ? "string1","string2" : "string3","string4"); return 0; } ``` if the condition is true then I would like to have ``` string1 string2 ``` as the output but when I do it this way, it is not what I get
I think you need: ``` printf("%s %s\n", condition ? "string1" : "string3", condition ? "string2" : "string4"); ```
The C standard states (emphasis mine): If an identifier designates two different entities in the same name space, the scopesmightoverlap. [...] (section 6.2.1.4 fromhttp://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf) When can an identifier refer to two different entities but their scopes do not overlap? Or, put differently, why is there the word "might" in the quote?
These scopes fornameoverlap: ``` int f(void) { int name = 4; { int name = 6; } } ``` These ones do not overlap: ``` int f(void) { { int name = 4; } { int name = 6; } } ```
I looked through several sites ,but, I am not able to find a suitable answer. It seems really hard to convert my c programme to assembly code...
if you use keil uvision ,than 1. goto Debug >> click "start/stop Debug Session" it'll start simulator if ide 2. 2. view >> click Disassembly Window and you can see the assembly. if not then go to below link and download it DIS8051 Cross-Disassembler V2.1 (you need hex file to convert your program to assembly of 8051)http://bit.kuas.edu.tw/~8051/
I would like to analyze an ELF binary file and figure out how many calls to dlopen() it makes in C, are there any libraries that can do this? Or how would I go about finding the count?
You could simply useltrace: Example: ``` #include <dlfcn.h> #include <stdio.h> int main(int C, char **V) { char **a = V+1; while(*a){ void *h; if(0==(h=dlopen(*a++, RTLD_LAZY))) fprintf(stderr, "%s\n", dlerror()); } } ``` Compile it: ``` $ gcc example.c -fpic -pie ``` Invoke it on self and countdlopencalls: ``` $ ltrace -o /dev/fd/3 \ ./a.out ./a.out ./a.out ./a.out 3>&1 >/dev/null| \ grep ^dlopen\( -c 3 ```
This question already has an answer here:How to change console window style at runtime?(1 answer)Closed5 years ago. So I was searching (a lot) and haven't find anything on how to prevent user from resizing my program's console window. I had found information for languageC++andC#but not forC. I already managed to set the size of the console but if the user changes it afterwards it is not good for my program's looking. Is there anything I can do to perfectly resize the console and keep it that way?
Okay so I managed to do the magic with combining codes. First of all you need a ``` #define _WIN32_WINNT 0x0500 ``` and after that (the order is important) ``` #include <windows.h> ``` and after all this you need this code in your main: ``` HWND consoleWindow = GetConsoleWindow(); SetWindowLong(consoleWindow, GWL_STYLE, GetWindowLong(consoleWindow, GWL_STYLE) & ~WS_MAXIMIZEBOX & ~WS_SIZEBOX); ```
I have a GTK application where I need to allow the user to open a file manager to delete older data files. I have successfully incorporated this using this bit of code: ``` GError *error = NULL; if (!g_app_info_launch_default_for_uri ("file:///", NULL, &error)) { g_warning ("Failed to open uri: %s", error->message);} ``` This brings up the file manager, but it is beneath my gtk application. Is there a way to put the file manager on top?
Maybe as alternative consider GtkFileChooserDialog in your app? It should allow deleting files through that one and you have full control over the window.
When I useIF_NAMESIZE(fromnet/if.hin libc implementations) as array size, should I use it as it is or with+ 1for\0(null byte)? ``` char iface[IF_NAMESIZE]; ``` or ``` char iface[IF_NAMESIZE + 1]; ``` I see it using both ways across various open source projects.
The header shall define the following symbolic constant for the length of a buffer containing an interface name (including the terminating NULL character):IF_NAMESIZE Interface name length. http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/net_if.h.html So: ``` char iface[IF_NAMESIZE]; ``` is enough
schot's answeris a good one. He claimed that Tags (names of structures, unions and enumerations). I think that the tags for structures, unions and enumerations have different namespaces, so that this code is completely fine: ``` // In the same scope struct T {}; union T {}; enum T {}; ``` But inferring from the quotation above, it looks like all tags share the same namespace. Is the answer not clear enough or am I wrong?
No. All the tags share the same namespace. So you are not allowed to have: ``` struct T {...}; union T {...}; enum T {...}; ``` C11 draft N1570, 6.2.3 Name spaces of identifiersexplicitly add s footnote. 32) There isonly one name space for tagseven though three are possible.
I'm using this function to read the input matrix: ``` void leMatInt(int **M,int linhas,int colunas){ int i, j; for (i = 0; i < linhas; i++){ for (j = 0; j < colunas; j++){ scanf("%d", &M[i][j]); //printf("Leu [%d, %d]\n", i, j); } } } ``` And I'm creating the matrix like this: ``` scanf("%d", &v1); int **matriz1=(int **)malloc(v1 * sizeof(int)); for(i = 0;i < v1; i++){ matriz1[i] = (int *)malloc(v1 * sizeof(int)); } leMatInt(matriz1, v1, v1); ``` The code works nicely for v1 <= 4, but if I try to input a 5v5 matrix, the code gets runtime error at the function.
matriz1is a double pointer so while allocating memory you should writesizeof(int*). because** pointerwill holds/contains* singlepointers. ``` int **matriz1 = malloc(v1 * sizeof(int*)); for(i = 0;i < v1; i++){ matriz1[i] = malloc(v1 * sizeof(int)); } ``` typecastingmalloc()is discouraged.
This question already has answers here:Is CHAR_BIT ever > 8?(3 answers)Closed5 years ago. As far as I know the standard says that the size of theshorttype must be at least 16 bits. Now I'm wondering if there are actually platforms whereshorts are 32 bit or even larger. I'm aware ofstddef.hand that the types defined there should be used if a certain size is required.
Yes. You can findan example here(well, not 32 bit, but "larger than 16"). The example given there is theUNICOSoperating system for "Cray" supercomputers, which has 64bitshort.
I'm using this function to read the input matrix: ``` void leMatInt(int **M,int linhas,int colunas){ int i, j; for (i = 0; i < linhas; i++){ for (j = 0; j < colunas; j++){ scanf("%d", &M[i][j]); //printf("Leu [%d, %d]\n", i, j); } } } ``` And I'm creating the matrix like this: ``` scanf("%d", &v1); int **matriz1=(int **)malloc(v1 * sizeof(int)); for(i = 0;i < v1; i++){ matriz1[i] = (int *)malloc(v1 * sizeof(int)); } leMatInt(matriz1, v1, v1); ``` The code works nicely for v1 <= 4, but if I try to input a 5v5 matrix, the code gets runtime error at the function.
matriz1is a double pointer so while allocating memory you should writesizeof(int*). because** pointerwill holds/contains* singlepointers. ``` int **matriz1 = malloc(v1 * sizeof(int*)); for(i = 0;i < v1; i++){ matriz1[i] = malloc(v1 * sizeof(int)); } ``` typecastingmalloc()is discouraged.
This question already has answers here:Is CHAR_BIT ever > 8?(3 answers)Closed5 years ago. As far as I know the standard says that the size of theshorttype must be at least 16 bits. Now I'm wondering if there are actually platforms whereshorts are 32 bit or even larger. I'm aware ofstddef.hand that the types defined there should be used if a certain size is required.
Yes. You can findan example here(well, not 32 bit, but "larger than 16"). The example given there is theUNICOSoperating system for "Cray" supercomputers, which has 64bitshort.
So I create a new file: ``` fd = open("tester.txt", O_CREAT | O_RDWR); ``` then using the system call write I add some info to it. But when I try to read the info from the file, it can't be made. Using theterminalI found out, that the only way to open the file is to usesudoand thecontent is successfully written. However, my program can't be root. So, how do I open the file, write some content to it and without closing the C program output the file.
You are missing to specify the file mode as third argument to the creating open call; try the following: ``` fd = open("tester.txt", O_CREAT | O_RDWR, 0644); ``` Then, the file should be created with mode-rw-r--r--, so your own user can open it for reading and writing. Otherwise, it might end up with some random permission, i.e.---------, and only root can open this for reading (without chmodding it, at least).
MSDN link for TTM_GETBUBBLESIZEdoesn't have an example, how the lower word and higher word get returned. Didn't get much from Google. Please care to provide an example of it. Thanks!
FromMSDN: Returns the width of the tooltip in the low word and the height in the high word if successful. A "word" in the context of the Win API usually has a size of 16-bit. You have to use somebitwise arithmeticto extractwidthandheightfrom theresultof the message: ``` width = result & 0xFFFF; // extract the low word height = result >> 16; // extract the high word ``` Alternatively these macros declared in "windows.h" do the same: ``` width = LOWORD(result); height = HIWORD(result); ```
I have declared onlychartype members in the structure. ``` #include <stdio.h> struct st { char c1; char c2; char c3; char c4; char c5; }; int main() { struct st s; printf("%zu\n", sizeof(s)); return 0; } ``` Output:[Live Demo] ``` 5 ``` So, why is there no padding in the structure for onlychartype members?
Padding is to enforcealignmentrequeriments. A member is said to bealigned(to its size) if it is located at an address that is divisible by its size. There is no need for padding in your example, since all members of theststructure are already aligned to their size, i.e.: the address of each member ofstis already divisible by its size. All members are of typecharand the size of acharis1. If a member's size is1, that member is always aligned to its size, since any address is divisible by1.
I have a problem assigning values to variable in struct. My code is shown below. ``` typedef struct _neuron { double value[100]; int id; }NEURON; int main() { NEURON node; int i; for(i = 0; i < 100; i++){ node.value[i] = 10; printf("the value is %d\n",node.value[i]); } } ``` The values I assigned to struct variables are 10, but I am getting 0 instead of 10. Does anyone know where the problem is?
You're using the wrong format specifier toprintf. The%dformat specifier expects anintargument, but you're passing in adouble. Using the wrong format specifier invokes undefined behavior. For adouble, use the%fformat specifier. ``` printf("the value is %f\n",node.value[i]); ```
Some C/C++ headers like<sys/ioctl.h>have asys/prefix in front of them. (There are also some with anet/prefix.) Why is this?
Practically, this shows those file are under a sub-folder named "sys" in one of the standard list of system directories (e.g compiler default search path, or folder given as a parameter during the build). The reason they are in a sub-folder is to indicate they are not a part of the c or c++ standard libraries, but rather a specific extension, usually provided by the operating system you are working in. Note that this is only a matter of conventions, and not part of the specified behavior by C or C++. Usually to really understand those kind of header you will look at further documentation provided by the operating system you are working under.
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.Closed5 years ago.Improve this question Is this possible to get lines from file one by one and save them to the char array which size is determined by the number of characters in each line?
fromhttps://linux.die.net/man/3/getline ``` ssize_t getline(char **lineptr, size_t *n, FILE *stream); ``` getline automatically allocates lineptr if it is NULL or not large enough to contain the string
This question already has answers here:What is 'forward declaration' and the difference between 'typedef struct X' and 'struct X'?(5 answers)Closed5 years ago. Why does ``` //The type anything_at_all exists nowhere. typedef struct anything_at_all lol; ``` compile without errors, whereas ``` //The type anything_at_all_2 exists nowhere. typedef anything_at_all_2 rofl; ``` produces errors? What's so special about structs? In a way I'm glad it works like this because it allows us to create opaque structs. But it would be nice to understandwhyit works.
You can declare astructwithout defining it. This is called aforward declaration. It allows you to do things like this: ``` struct s1; struct s2 { int x; struct s1 *p; }; struct s1 { int y; struct s2 *p; }; ```
For example, I have a 64 bit vara, and a 8 bit charb ``` unsigned long long a = 0x1234567890123456; unsigned char b = 0x78; ``` I wantato become 0x1234567890123478 I want rightmost 8 bit ofato set tob, and remain left 56 bits untouched, how can i do this? ``` a = a & (0xFFffFFffFFffFFff | b); //is this correct? ``` ??
There's a useful macro defined inlimits.hthat can help make it portable. It'sCHAR_BIT. ``` a = ((a >> CHAR_BIT) << CHAR_BIT) | b; ``` And that's it. The piece in parentheses clears the least significantCHAR_BITs ofa, and then that can be bitwise-ored withb.
I followed the solution here:How to Calculate Double + Float Precisionand have been unable to calculate the maximum value for variables of type double. I run: ``` double dbl_max = pow(2, pow(2, 10)) * (1-pow(2, -53)); printf("%.2e", dbl_max); Result: inf ``` Or: ``` double dbl_max = (pow(2, pow(2, 10))); printf("%.2e", dbl_max); Result: inf ``` Or: ``` double dbl_max = pow(2, pow(2, 9)) * (1-pow(2, -53)); printf("%.2e", dbl_max); Result: 1.34e+154 ``` Why isn't the calculation fitting into the variable? The top sample above works just fine for float variables.
The intermediate exponent is one too high. Changepow(2, 10)to(pow(2, 10) - 1)and it should work. You can compensate by multiplying the final result by 2. – Tom Karzes ``` double dbl_max = pow(2, pow(2, 10)-1) * (1-pow(2, -53)) * 2; printf("%.2e", dbl_max); ```
Is there a better way than: ``` #define BOUND 7 int r; int e = 1; r = rand() % BOUND; while (r == e){ r = rand() % BOUND; } ``` for generating numbers in a range except for a valuee?
What you're asking for is generating a random number in the range[0, BOUND)excluding the valuee Thealgorithm explained hereseems to be the best way to do it without using a loop. Here is the C code: ``` #define BOUND 7 int r; int e = 1; r = rand() % (BOUND-1); if (r >= e){ r = r+1; } ``` So, you basically generate a value in the range[0, BOUND-1), and if the value is greater than or equal to the excluded valuee, you increment the random number by one. Keep in mindthat usingrandwith%does not guarantee a strict uniform distribution across the generated numbers. For more info,check out this question/answers.
I want to read the values of the register starting from 0x20000000 to 0x20000FFC. Architecture: ARMRegister width: 32 bit I did following: ``` #define REG 0x20000000 unsigned int volatile * const port = (unsigned int *) REG; for(int i=0; i<4093; i++) { printf("%d", *(port+i)); } ``` Is this the right way?
``` #define REG 0x20000000 unsigned int volatile const* port = (unsigned int *) REG; for(; port < (unsigned int *) REG+0x1000; port++) printf("%u", *port); ```
So i'm debugging a very rare case that SEGSEV occurs, I do not know when it will happen, but i know that when it happens, one local var is-1, so I did this in gdb ``` break file.c:100 if t1 == -1 ``` the problem is i have to go back many steps to find out what happened, is it possible to record all execution information, so that I can replay the execution?
there is currently therr projectfor linux which record the execution of your program and help you replay the execution in GDB. Windows also seem to have somereplay debugging capabilities with winDbg preview
How do you allocate an array comprised of fixed size array of floats ? I tried this: ``` float **sub_uvs = malloc(sizeof(float [2]) * size * size); /* Seg. fault */ sub_uvs[0][0] = 0.3; sub_uvs[0][1] = 0.4; ```
Multidimensional arrays of variable size are still tricky. Several options: Use an array of pointers to arrays. Use onemallocfor the array of pointers, then loop overmallocto make each row-array. But, this is a whole different data structure.Find a class providing memory management and multidimensional indexing methods. Perhaps Blender has one?UseEigenor a similar complete math library.
Currently, I'm taking C language certification course at cppinstitute.org. In one of it's quizzes there is a question as below to recognize output. ``` int i = 1,j= 1; int w1,w2; w1 = (i>0) && (j<0) || (i<0) &&(j>0); w2 = (i<=0) || (j>=0) && (i>=0) || (j<=0); printf("%d",w1 == w2); ``` I think the program should print 0 to the screen, but the quiz accepts printing 1 as the answer. Am I correct?if not ,where I'm wrong? Thanks in advance!I'm a beginner.
Here,&&higher precedence than||operator. So, ``` w1 = (i>0) && (j<0) || (i<0) &&(j>0); = 1 && 0 || 0 && 1; = 0 || 0 = 0 ``` And ``` w2 = (i<=0) || (j>=0) && (i>=0) || (j<=0); = 0 || 1 && 1 || 0 = 0 || 1 || 0 = 1 || 0 = 1 ``` So,w1 == w2become false. So, correct output is 0.
Is there difference in code for writing to a serial port in C usingcanonicalornon-canonicalmethod?
yes, there is a major difference. The parameters of the communication port need to be modified to be transferring 'raw' or 'cooked' characters. 'raw' transfers every char, exactly as it is received. 'cooked' makes the I/O module handle control characters, back space, etc Suggest starting by reading the MAN page fortcgetattr()and reading about (and understanding) all the related functions. The functions are all part of thetermiosfamily of functions.
I have a struct defined by: ``` typedef struct { char name[CANDY_NAME_LEN]; bool vegan; } candy; ``` I define an array of size 10 of these structs: ``` const candy candy_db[NUM_OF_CANDIES]; ``` and try to fill the array: ``` strcpy_s(candy_db[0].name, sizeof(candy_db[0].name), "Apple"); candy_db[0].vegan = true; ``` but setting true to the bool field of the first element (or any element) in the array gives me an error: expression must be a modifiable lvalue. what is the problem? thanks
const candy candy_db[NUM_OF_CANDIES]; You've defined your array asconst, so none of its elements can be modified.
I know I can print an address using: ``` printf("%p\n",(void*)&a); ``` Is there a way to just access the address (=int representing place in memory) of a variable? A possible workaround is atoi of sprintf %p but common, is there a cleaner way? I need that for a Nachos project.What I am trying to do is writing into the return register the address of an object I created in the kernel.
You can cast avoid *to auintptr_t, which is an integer type large enough to represent a pointer. ``` uintptr_t p = (uintptr_t)(void *)&a; ``` Note that the double cast is needed, as the standard states the conversion is only valid between auintptr_tand avoid *.
I know I can print an address using: ``` printf("%p\n",(void*)&a); ``` Is there a way to just access the address (=int representing place in memory) of a variable? A possible workaround is atoi of sprintf %p but common, is there a cleaner way? I need that for a Nachos project.What I am trying to do is writing into the return register the address of an object I created in the kernel.
You can cast avoid *to auintptr_t, which is an integer type large enough to represent a pointer. ``` uintptr_t p = (uintptr_t)(void *)&a; ``` Note that the double cast is needed, as the standard states the conversion is only valid between auintptr_tand avoid *.
I want to pack the following numbers into a 64 bit int64_t field in the following order: int8_t num1int8_t num2int32_t num3int16_t num4 So, the 64 bits should be in the following layout: ``` [ num1(8) | num2(8) | num3(32) | num4(16) ] ``` I'm not able to wrap my head around the bit packing logic, i.e. I want those numbers to be packed into a single int64_t field, similar tothis question. Any help is greatly appreciated.
You probably want this: ``` int8_t num1; int8_t num2; int32_t num3; int16_t num4; ... uint64_t number = ((uint64_t)num1 << (16 + 32 + 8)) | ((uint64_t)num2 << (16 + 32)) | ((uint64_t)num3 << 16) | (uint64_t)num4; ``` From this you should be able to figure out how to do the inverse conversion. If not, post another question.
I am new to messaging world and started usingNanomsglibrary in my application. I want to know whether the messages are encrypted by default between the server and the client by theNanomsglibrary. If not, how can I add encryption to secure the messages between the communicating nodes?
The payload of the message is not encrypted. You can add encryption and decryption for payload into the client and server. A very simple encryption is described hereSimply encrypt a string in C
I've found out where caused SEGSEV, but only happens when that function be called hundreds of thousands times to trigger some rare case, is it possible to set breakpoint there when something is true? either on the gdb command line or c source file
Try like this: ``` (gdb) break file.c:15 if some_variable == some_value ```
I saw following macrohere. ``` static const char LogTable256[256] = { #define LT(n) n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n -1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, LT(4), LT(5), LT(5), LT(6), LT(6), LT(6), LT(6), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7) }; ``` What does#define LT(n) n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, ndo here?
If simply repeats its argument 16 times. See how it is used in the code at your link, immediately after its definition, to produce sequential repetitive values in the initializer ofLogTable256array: ``` static const char LogTable256[256] = { -1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, LT(4), LT(5), LT(5), LT(6), LT(6), LT(6), LT(6), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7) }; ``` No rocket science here. Just saves some typing, no more no less.
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.Closed5 years ago.Improve this question how can I increase accuracy in double. for example in this code: ``` #include <stdio.h> int main() { long double a = (long double) 5 / 3; printf("%.62LLF", a); return 0; } ```
Floating Point Numbers have a limited precision.Mandatory Reading Here. Theboost.multiprecisionlibrary can give you access to higher precision floating point numbers, whether in the form ofquadtypes which simply double the precision ofdouble, or in the form of arbitrary precisionrationalnumbers. If you're willing to take the time to learn how to install and use that library, you'll be able to improve the precision of your numbers.
I've trying to do this but I can't find the right way. I have this : ``` #include <string.h> #include <stdio.h> int main(){ char a = 'a'; char b[1] = " "; strcat(b,a); printf ("%s",b); return 0; } ``` I know it's wrong. How can I fix this code in order to turn'a'into"a"?
``` #include <string.h> #include <stdio.h> int main(){ char a = 'a'; char b[2] = " "; b[0] = a; printf ("%s",b); return 0; } ``` A c string is just an array of characters - if you want to set individual characters in that string, you can do so exactly as you would any other array. One thing you missed though is that c strings have to be 1 longer than the number of characters you want to store - to store the terminating\0.
the following error shows ,when i try to compile the source code ``` C:/Program Files (x86)/mingw-w64/i686-7.1.0-posix-dwarf-rt_v5-rev2/mingw32/bin/. ./lib/gcc/i686-w64-mingw32/7.1.0/../../../../i686-w64-mingw32/bin/ld.exe: cannot open output file print.exe: Permission denied collect2.exe: error: ld returned 1 exit status ``` the code of my program is given below ``` #include<stdio.h> void print(int x) { if(x==1) { printf("%d\n", x); return; } else { print(x-1); printf("%d\n",x); } } void main() { print(10); } ``` it is working fine in Turbo C. what kind of error it is ? how can I correct it?
You have to kill the existing process that is running. kill theprint.exeprocess an it will be accessible or simply close thecommand prompt windowwhich opened the execution instance.
Hello! I want to make Makefile.win which will make a tar.gz with 2 other files(dodaj.c and another Makefile, both are in the same directory where i want use commend make ).My problem is ``` make dodaj.tar.gz make: *** No rule to make target 'dodaj.tar.gz'. Stop ``` Here is my code: ``` dodaj.tar.gz: dodaj.c Makefile mkdir dodaj-434686 cp ./dodaj.c ./dodaj-434686 cp ./Makefile ./dodaj-434686 tar -czvf dodaj.tar.gz ./dodaj-43468 rm -rf ./dodaj-434686 ```
Make will look for files named 'makefile' and 'Makefile'. If you are using Gnu make, it will also look for 'GNUmakefile'. It does not look for 'Makefile.win'. To use that file, you must domake -f Makefile.win dodaj.tar.gz
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.Closed5 years ago.Improve this question how can I increase accuracy in double. for example in this code: ``` #include <stdio.h> int main() { long double a = (long double) 5 / 3; printf("%.62LLF", a); return 0; } ```
Floating Point Numbers have a limited precision.Mandatory Reading Here. Theboost.multiprecisionlibrary can give you access to higher precision floating point numbers, whether in the form ofquadtypes which simply double the precision ofdouble, or in the form of arbitrary precisionrationalnumbers. If you're willing to take the time to learn how to install and use that library, you'll be able to improve the precision of your numbers.
I've trying to do this but I can't find the right way. I have this : ``` #include <string.h> #include <stdio.h> int main(){ char a = 'a'; char b[1] = " "; strcat(b,a); printf ("%s",b); return 0; } ``` I know it's wrong. How can I fix this code in order to turn'a'into"a"?
``` #include <string.h> #include <stdio.h> int main(){ char a = 'a'; char b[2] = " "; b[0] = a; printf ("%s",b); return 0; } ``` A c string is just an array of characters - if you want to set individual characters in that string, you can do so exactly as you would any other array. One thing you missed though is that c strings have to be 1 longer than the number of characters you want to store - to store the terminating\0.
the following error shows ,when i try to compile the source code ``` C:/Program Files (x86)/mingw-w64/i686-7.1.0-posix-dwarf-rt_v5-rev2/mingw32/bin/. ./lib/gcc/i686-w64-mingw32/7.1.0/../../../../i686-w64-mingw32/bin/ld.exe: cannot open output file print.exe: Permission denied collect2.exe: error: ld returned 1 exit status ``` the code of my program is given below ``` #include<stdio.h> void print(int x) { if(x==1) { printf("%d\n", x); return; } else { print(x-1); printf("%d\n",x); } } void main() { print(10); } ``` it is working fine in Turbo C. what kind of error it is ? how can I correct it?
You have to kill the existing process that is running. kill theprint.exeprocess an it will be accessible or simply close thecommand prompt windowwhich opened the execution instance.
Hello! I want to make Makefile.win which will make a tar.gz with 2 other files(dodaj.c and another Makefile, both are in the same directory where i want use commend make ).My problem is ``` make dodaj.tar.gz make: *** No rule to make target 'dodaj.tar.gz'. Stop ``` Here is my code: ``` dodaj.tar.gz: dodaj.c Makefile mkdir dodaj-434686 cp ./dodaj.c ./dodaj-434686 cp ./Makefile ./dodaj-434686 tar -czvf dodaj.tar.gz ./dodaj-43468 rm -rf ./dodaj-434686 ```
Make will look for files named 'makefile' and 'Makefile'. If you are using Gnu make, it will also look for 'GNUmakefile'. It does not look for 'Makefile.win'. To use that file, you must domake -f Makefile.win dodaj.tar.gz
This question already has answers here:Modify a string with pointer [duplicate](4 answers)Closed5 years ago. I am getting segmentation fault when running the below code. What could be the reason for this error? Please help ``` int main() { char *str2 = "Hello"; str2[3] = 'J'; printf("%s\n",str2); return 0; } ```
It is aundefined behaviourbecause you are trying to modify the content of astring literal. A string literal mainly stored in aread only location. so you do not modify it, otherwise it is invoked undefined behaviour. C11 §6.4.5 String literals(Paragraph 7): It is unspecified whether these arrays are distinct provided their elements have the appropriate values.If the program attempts to modify a string literal of either form, the behavior is undefined"
Let's say here is a char with unknown digit number in C: ``` char char_id[1000] = {'1', '2', '3', ..., '8', '9', '\0'}; ``` If I want the last two digit to form an integer i.e. '89'. What is the easiest way?
may be this ``` char char_id[1000] = {'1', '2', '3', /*..., */ '8', '9', '\0'}; int what_i_want = atoi( char_id + ( strlen(char_id) - 2 ) ); ``` by the way those dots are a bit of rubbish, comment them
This question already has answers here:How do I align a number like this in C?(11 answers)Closed5 years ago. So I want to align my outputs like so: ``` John Smith Age: 34 Gender: M Micheal Smith Age: 9 Gender: F ``` and so on I have an array that contains the information for this and I loop through it and print the information: ``` for (int i = 0; i < ARRAY_LENGTH; i++) { printf ("%s Age: %d Gender: \n", person[i].name, person[i].age, person[i].gender); } ``` I am stuck on how to make it align so all the spaces are even. Thanks
If you look at the manual for printf(), and note that you can do things like %-18s and %2d - putting a field width and alignment in the format group. So I'd do something like ``` printf("%-20s Age:%3d Gender: %1s", person[i].name, person[i].age, person[i].gender); ``` which should align nicely for you.
In C, how can I declare and use/manipulate a an array of strings? For example, it could be ``` a[1]="Apples"; a[2]="Pineapples are red" ``` How can I access these elements and modify them?
In your code,amust be an array of pointers to char, e.g.char *a[5], to which you then assign pointers to string literals: ``` a[1]="Apples"; a[2]="Pineapples are red"; ``` You can modify an element in the sense to let it point to a different string, e.g.a[1]="another fruit";. You can access an entire string like, for example,printf("%s", a[1]), and you can access single characters like, for example,char willBeA_p = a[1][1]; But you cannot modify the contents of the strings in your example, because they are string literals (and modifying string literals yields undefined behaviour). Soa[1][1]='b'is not allowed.
I know what the difference between these types of variables is, but I'm wondering if making a static variable local actually affects, or can affect the compiler's code-generation in any way.
Static variables declared at file scope have the same properties as static variables declared locally (aside from theirscope, i.e. visibility region of the identifier). Both kinds have the same storage duration. Both kinds are initialized before program's startup. There's no reason to expect them to behave differently in terms of code generation. As a side note: static variables cannot be declared locally ininline definitionsof functions, but it is not related to code generation.
When I try to assign a big number to adoublevariable, I get this warning sqrt.c:8:11: warning: integer constant is too large for its typedouble x=28462391747582051264412870770688; ``` #include <stdio.h> #include <math.h> #include <limits.h> #include <float.h> int main() { printf("MAX_DBL=%.53f\n",DBL_MAX); double x=28462391747582051264412870770688; } ``` However MAX_DBL is larger than the number I am trying to assign.
``` double x=28462391747582051264412870770688; ``` The type of the number literal is notdouble, butint. This number is too large for anint. If you use adoubleliteral: ``` double x=28462391747582051264412870770688.0; ``` The warning disappears, but the number will be rounded to the next representabledouble, if needed. (This particular number here is representable,as @chux noticed.)
I'm trying to make my charpWRtaking the value of the first 6 characters of charpWbut I am getting the following error: ``` incompatible types in assignment of 'char' to 'char [6]' pWR = pW[1,2,3,4,5,6]; ``` This is part of my code: ``` char pWR[6]; char pW[30]; pWR = pW[1,2,3,4,5,6]; ``` Any help would be great.
You can use the library functionstrncpyto achieve your objective: ``` char pWR[6]; char pW[30] = "abcdefghij"; strncpy(pWR, pW, 6); ``` However, if you are planning to treat pWR as a string, make sure you allow for the null terminator character to mark the end of the string. The other alternate as suggested by a few commenters is to usememcpyfunction. ``` char pWR[6]; char pW[30] = "abcdefghij"; memcpy(pWR, pW, 6); ```
I'm currently learning the basics in C programming and was about to try out the switch-statement. My questions is: ``` switch (answer) { case ('Y' || 'y') : printf("\nYay! Me too. "); break; case ('N' || 'n') : printf("\nBoo! :("); break; default: printf("\nInput error!"); break; } ``` Why can't I write an || in my different cases?
switch case doesn't support logical operations. In your case the solution is easy: ``` switch (answer) { case 'Y': case 'y': printf("\nYay! Me too. "); break; case 'N': case 'n': printf("\nBoo! :("); break; default: printf("\nInput error!"); break; } ```
Parentheses and pointer symbol have same priority, and they are dealed from left to right. Why does the following code try to get the membernfctfromskb, then do the type conversion? It's seems that the associativity is from right to left. ``` (struct nf_conn *) skb->nfct ```
I believe the point you're missing here is theOperator Precedence. The pointer member access operator (->) has higher precedence than the cast. To elaborate, (borrowed wordings) Operator precedence determines which operator is performed first in an expression with more than one operators with different precedence.Associativity is used (or comes into play) when two operators ofsame precedenceappear in an expression.
I'm using 32-bit variable for storing 4 8-bit values into one 32-bit value. ``` 32_bit_buf[0]= cmd[9]<<16 | cmd[10]<<8| cmd[11] <<0; ``` cmdis of unsigned char type with data ``` cmd [9]=AA cmd[10]=BB cmd[11]=CC ``` However when 32-bit variable is printed I'm getting0xFFFFBBCC. Architecture- 8-bit AVR Xmega Language- C Can anyone figure out where I'm going wrong.
Your architecture uses 16bitint, so shifting by 16 places is undefined. Cast yourcmd[9]to a wider type, e.g.(uint32_t)cmd[9] << 16should work. You should also apply this cast to the other components: When you shiftcmd[10]by 8 places, you could shift into the sign-bit of the 16bitsignedintyour operands are automatically promoted to, leading to more strange/undefined behavior.
This question already has answers here:How do I properly compare strings in C?(11 answers)string comparison inside if condition malfunctioning [duplicate](2 answers)Closed5 years ago. ``` #include<stdio.h> int main(){ char name[20]; scanf(" %s", name); if (name == 'James'){ printf("Welcome James"); }else{ printf("You are not James"); } } ``` Hope you got my idea. I know this doesn't work. But is there any way to do something like this?
Use ``` if (strcmp(name, "James") == 0) ``` instead of ``` if (name == 'James') ``` Man page ofstrcmp: Return Value Thestrcmp()andstrncmp()functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.
I know what the difference between these types of variables is, but I'm wondering if making a static variable local actually affects, or can affect the compiler's code-generation in any way.
Static variables declared at file scope have the same properties as static variables declared locally (aside from theirscope, i.e. visibility region of the identifier). Both kinds have the same storage duration. Both kinds are initialized before program's startup. There's no reason to expect them to behave differently in terms of code generation. As a side note: static variables cannot be declared locally ininline definitionsof functions, but it is not related to code generation.
When I try to assign a big number to adoublevariable, I get this warning sqrt.c:8:11: warning: integer constant is too large for its typedouble x=28462391747582051264412870770688; ``` #include <stdio.h> #include <math.h> #include <limits.h> #include <float.h> int main() { printf("MAX_DBL=%.53f\n",DBL_MAX); double x=28462391747582051264412870770688; } ``` However MAX_DBL is larger than the number I am trying to assign.
``` double x=28462391747582051264412870770688; ``` The type of the number literal is notdouble, butint. This number is too large for anint. If you use adoubleliteral: ``` double x=28462391747582051264412870770688.0; ``` The warning disappears, but the number will be rounded to the next representabledouble, if needed. (This particular number here is representable,as @chux noticed.)
I'm trying to make my charpWRtaking the value of the first 6 characters of charpWbut I am getting the following error: ``` incompatible types in assignment of 'char' to 'char [6]' pWR = pW[1,2,3,4,5,6]; ``` This is part of my code: ``` char pWR[6]; char pW[30]; pWR = pW[1,2,3,4,5,6]; ``` Any help would be great.
You can use the library functionstrncpyto achieve your objective: ``` char pWR[6]; char pW[30] = "abcdefghij"; strncpy(pWR, pW, 6); ``` However, if you are planning to treat pWR as a string, make sure you allow for the null terminator character to mark the end of the string. The other alternate as suggested by a few commenters is to usememcpyfunction. ``` char pWR[6]; char pW[30] = "abcdefghij"; memcpy(pWR, pW, 6); ```
This may be a silly question, but I'm struggling to solve this problem. I know that to append a char to a string I can do something like this: ``` char c; char string[10] = ""; strcat(string, &c); ``` Now, this works well for char variables, but the problem is that when I try to append a char from an array: ``` char array[5]; char string[10] = ""; strcat(string, &array[0]); //&array[0] returns the entire array, not just array[0] ``` Question: How can I append a single char from an array to a string?
You can use strncat().Here length is the number of characters you want to append to string ``` strncat(string, array, length); ``` For appending single character, use length = 1
May I know if there is anything like the easiest node to be removed or deleted from a LinkedList. I know that deleting a node from in between requires a change of the preceding nodes link, whereas deleting from beginning needs a change of pointer to the new head and deleting from the end needs a change of new end of the list. But, if asked to delete a node from the LinkedList which is easier which of these should be preferred?
Sounds like you are on the right track with your thoughts on linked lists. Another thing to consider about removing theeasiestnode from a linked list is the following: How often will theseeasiestnodes be removed? If the node is removed from theheadof the list the removal will becomplete in O(1)time, but if theeasiestnodes are at therearof the list removal will take a full traversal of the listcompleting in O(n)time.
For example, if I had amakefilethat contains this: ``` dynArray.o: dynArray.c dynArray.h type.h gcc -Wall -ansi -c dynArray.c ``` How would I translate that into aCMakeLists.txtfile?
ProbablyCMake's object librarieswould do that, that mean compile objects but not archive them like normal library would. ``` add_library(<name> OBJECT <src>...) ```
If we open FIFO with O_NONBLOCK set, why opening with read-only or write-only set,open()behave differently?
There is asymmetry due to communication semantic. Opening for writing in non blocking mode should fail if there is no reader at that time because writing into a channel with no reader is of no usage (without any reader writing should fail). Opening for reading in non blocking can succeed (and does) because it declares that somebody will (eventually) be able to read something in the future.
This may be a silly question, but I'm struggling to solve this problem. I know that to append a char to a string I can do something like this: ``` char c; char string[10] = ""; strcat(string, &c); ``` Now, this works well for char variables, but the problem is that when I try to append a char from an array: ``` char array[5]; char string[10] = ""; strcat(string, &array[0]); //&array[0] returns the entire array, not just array[0] ``` Question: How can I append a single char from an array to a string?
You can use strncat().Here length is the number of characters you want to append to string ``` strncat(string, array, length); ``` For appending single character, use length = 1
May I know if there is anything like the easiest node to be removed or deleted from a LinkedList. I know that deleting a node from in between requires a change of the preceding nodes link, whereas deleting from beginning needs a change of pointer to the new head and deleting from the end needs a change of new end of the list. But, if asked to delete a node from the LinkedList which is easier which of these should be preferred?
Sounds like you are on the right track with your thoughts on linked lists. Another thing to consider about removing theeasiestnode from a linked list is the following: How often will theseeasiestnodes be removed? If the node is removed from theheadof the list the removal will becomplete in O(1)time, but if theeasiestnodes are at therearof the list removal will take a full traversal of the listcompleting in O(n)time.
For example, if I had amakefilethat contains this: ``` dynArray.o: dynArray.c dynArray.h type.h gcc -Wall -ansi -c dynArray.c ``` How would I translate that into aCMakeLists.txtfile?
ProbablyCMake's object librarieswould do that, that mean compile objects but not archive them like normal library would. ``` add_library(<name> OBJECT <src>...) ```
If we open FIFO with O_NONBLOCK set, why opening with read-only or write-only set,open()behave differently?
There is asymmetry due to communication semantic. Opening for writing in non blocking mode should fail if there is no reader at that time because writing into a channel with no reader is of no usage (without any reader writing should fail). Opening for reading in non blocking can succeed (and does) because it declares that somebody will (eventually) be able to read something in the future.
For example, if I had amakefilethat contains this: ``` dynArray.o: dynArray.c dynArray.h type.h gcc -Wall -ansi -c dynArray.c ``` How would I translate that into aCMakeLists.txtfile?
ProbablyCMake's object librarieswould do that, that mean compile objects but not archive them like normal library would. ``` add_library(<name> OBJECT <src>...) ```
If we open FIFO with O_NONBLOCK set, why opening with read-only or write-only set,open()behave differently?
There is asymmetry due to communication semantic. Opening for writing in non blocking mode should fail if there is no reader at that time because writing into a channel with no reader is of no usage (without any reader writing should fail). Opening for reading in non blocking can succeed (and does) because it declares that somebody will (eventually) be able to read something in the future.
I'm programming some functions to treat with strings without using<string.h>, and I'm getting the length of a string by doing this: ``` char *str= "Getting the length of this"; int c; for (c= 0; str[c]!='\0'; c++); ``` Nowcis the length of my string so it makes work with strings a lot easier, but i wonder if this is correct (it works but maybe is not a proper way to do this).
... i wonder if this is correct Yes, it is correct. For readability I would prefer: ``` char *str= "Getting the length of this"; int c = 0; while(str[c]) c++; ``` but that's just a matter of taste. Be aware that it is unusual to useintfor string length. Thestrlenfunction returnssize_tso to mimic the library function, you should also usesize_tLike: ``` size_t my_strlen(const char* s) { size_t c = 0; while(s[c]) c++; return c; } char *str= "Getting the length of this"; size_t c = my_strlen(str); ```
``` #include <stdio.h> void main() { char c = getchar(); while ( c != '.') { putchar(c); c = getchar(); } } ``` when you run above code and input any string like "Shubham jain". the whole string gets copied and gets printed whilegetchar()should have read only the first character from the string. can someone explain how is this happening?
When you input a string using your program, it will automatically provide input for every char in the string ongetcharfunction, calling it multiple times. The moment the loop detects a '.' the program stops reading any more characters.
What's the difference betweenchar str[10]andchar *str = (char *) malloc(10)? As I understand, don't both of them allocate 10 bytes for an array ofchars?
char str[10]; Global (static) scope - allocated in the.dataor.bsssegments (depending on the initialisation. Cannot be freed before program termination. Local (automatic) scope - usually (most implementations but C standard does not defie anything like the "stack") allocated on the stack. Automatically freed when program leaves the scope. 2. char *str = malloc(10); Allocated on heap. Needs to be freed by the program using thefreefunction
I have the following code: ``` struct coord { float x; float y; }; struct coord vertices[4]; ``` But when I do the following, an error occurs: ``` void setVertices(float x, float y) { vertices[0] = (struct coord) { x, y }; } ``` Why isn't this allowed in C? Is there another way to do this? Thank you.
I can initialize structs that way, actually. The IDE just lagged on its error-checking for several minutes, for some reason.
``` #include <stdio.h> void main() { char c = getchar(); while ( c != '.') { putchar(c); c = getchar(); } } ``` when you run above code and input any string like "Shubham jain". the whole string gets copied and gets printed whilegetchar()should have read only the first character from the string. can someone explain how is this happening?
When you input a string using your program, it will automatically provide input for every char in the string ongetcharfunction, calling it multiple times. The moment the loop detects a '.' the program stops reading any more characters.