question
stringlengths
25
894
answer
stringlengths
4
863
This question already has answers here:Writing to pointer out of bounds after malloc() not causing error(7 answers)Undefined, unspecified and implementation-defined behavior(9 answers)Closed3 years ago. I am performing sprintf on a char array of size 1 and the code works fine. i.e strlen returns 1 even though it may not be null terminated. To my understanding sprintf will do null termination, however in this case it does not have enough space. Can someone explain the reason it works? ``` #include <stdio.h> #include <string.h> #define STATUS "1" int main(void){ char *data = malloc(1); sprintf(data, "%s", STATUS); printf(">%s<\n", data); printf(">%d<\n", strlen(data)); } ``` Output ``` >1< >1< ```
The program has undefined behavior. It works because in general malloc allocates memory chunks multiple by the paragraph size equal to 16 or some other implementation defined value.
Can you please tell me why is the output not same, ``` #include <stdio.h> int main(int ac, char **av, char **env) { printf("Address of the array of environment variables: %p\n", (void *)env); printf("Address of the first environment variable: %p\n", (void *)(env[0])); return 0; } ``` Is not env and env[0] pointing to the same address. Output: ``` Address of the array of environment variables: 0x7ffcd47f6288 Address of the first environment variable: 0x7ffcd47f7312 ```
They are not the same thing.envis the array of pointers to strings, which exists somewhere in memory.env[0]is the address of the first string, just likeenv[1]is the address of the second string, which is different to the address of the array where those addresses are stored.
I have created a pointer variable to point to an active variable. I have two variables, I want to toggle the active variable between these two variables. Managed to do this inside the main. Now I want to extend this to another function ``` int main() { int x = 0; int y = 0; int *active=&y; if(active == &x) active = &y; else active = &x; } ``` I dont want to swap the values of the variables, x, y. x, y are coordinates of a cartesian plane.
You can pass the reference of the pointer variable to the function, and in the formal parameter list create a pointer which holds the memory address of the pointer variable ``` void flip(int **act, int *x, int *y){ if(*act == x){ *act = y; }else{ *act = x; } } int main() { int x = 0; int y = 0; int *active=&y; flip(&active, &x, &y); } ```
Self explanatory question. Can we get multiple UDP packets in one socket recv call when using Multicast?
When usingrecvfromorrecvon a UDP socket, you will only ever receive one complete packet at a time. This applies to both unicast and multicast packets.
``` #include<stdio.h> struct a { float n; int e; }; struct b { struct a *c; }h; int main() { h.c->n=4; printf("%f",h.c->n); return 0; } ``` Yes it is small code but I have been trying to access the element e which is instruct a through the struct b. The code is compiled without any error but in the output screen, it is blank. Please suggest me a good way to access the element in the struct a. Please note that the struct a has been declared inside the struct b as a pointer.
This would crash because your pointercwas never allocated. ``` h.c->n=4; // pointer `c` has not been pointing to anything valid ``` To make it work, you need something like this: ``` struct a aa; // must allocate an item of struct `a` first aa.n = 4; aa.e = 0; h.c = &aa; // then make pointer `c` to point that that item printf("%f",h.c->n); // before trying to access that pointer ```
I triedlocate kmalloc_sizes.hbut didn't find the file. And I usedapt-fileto search but couldn't find the package. How can I get this header file?
The file you're looking for is actually calledkmalloc_sizes.h. You can get it by installing the Linux kernel headers: ``` sudo apt-get install linux-headers-$(uname -r) ``` Ref:https://askubuntu.com/questions/75709/how-do-i-install-kernel-header-files
I have a piece of code where there is: ``` disable_irq(irq_clk); local_irq_save(flags); ``` I found that the disable_irq() disables a specific interrupt, on the other hand local_irq_save() disables all the interrupt. So I wonder the meaning of the above code.
This makes sense, because interrupts are disabled at different levels. ``` disable_irq(irq_clk); ``` This code disables (masks) interrupt ininterrupt controller. If you have disabled interrupt at this level, the interrupt wouldn't be passed to internal interrupt controller pipeline. It would not be prioritized, it would not be routed to the destination CPU. ``` local_irq_save(flags); ``` This code disables all interrupts at the level of CPU IRQ interface. Interrupts are passed to CPU IRQ interface after they have passed priority & routing pipeline of the interrupt controller and have been asserted to the CPU.
I debug a complex application which crashes and I suspect that a memory between threads is not synchronized correctly. Here is a simplified example which demonstrates a potential problem: ``` DWORD WINAPI ThreadFun(LPVOID lpParam) { T* t = (T*)lpParam; WaitForSingleObject(t->startProcessing, INFINITE); //fill buffer with some data for (int i = 0; i < bufSize; ++i) { t->buf[i] = i; } return 0; } //Main thread void T::Process(int* p) { buf = p; SetEvent(startProcessing); } ``` There is a logic time relation - buf is set before calling SetEvent but does it guarentee that a memory will be synchronized between threads ? Should I use win api mutexes ?
SetEventandWaitForSingleObjectdo provide the guarantee that writes before theSetEventare visible afterWaitForSingleObjectreturns. There is no need to provide anything else here.
I want to modify this code, such that the structure contains more then one name and one fn (this is a function).
So presumably you have something like this already: ``` struct builtin { const char *name; int (*fn)( char ** ); }; ``` You can just add more fields, either the hard way: ``` struct builtin { const char *name; int (*fn)( struct builtin * ); const char *another_name; int (*another_fn)( char ** ); }; ``` or the slightly easier way: ``` struct builtin { const char *name[2]; int (*fn[2])( char ** ); }; ``` But after all that, and even after my questions under your post, I struggle to believe this is really what you want to achieve. EDIT: itwasn'treally what was wanted... Try this: ``` struct builtin builtins[NBR_BLTN] = { { .name = "echo", .fn = exec_echo }, { .name = "fish", .fn = exec_fish }, // etc. }; ```
I need to count number of digits in binary-coded decimal, for example 00111001. I can't use typical /10 because it gets stuck on 2 last 0's and doesn't count them. ``` #include <stdio.h> #include <stdlib.h> void main(void) { int bcd, digits; printf("Input BCD number: "); scanf_s("%d", &bcd); for (digits = 0; (bcd / 10) != 0; digits++) bcd /= 10; printf("Number of digits is %d", digits+1); getchar; } ``` So if I input 1111 it displays '4' that is correct, but when I type 0011 it displays '2', so how do I fix that?
when I type 0011 it displays '2', so how do I fix that? Use"%n"to record the offset of the scan. ``` int n1; int n2; if (scanf_s(" %n%d%n", &bcd, &n1, &n2) == 1) { printf("Input %d\nNumber of digits is %d\n", bcd, n2 - n1); } ```
I need to copy the content of one file to another and print this another's file content on screen. The program creates the file and copies the content with no problem but it does not print anything on screen. Thanks for your time. ``` void organizeContent(FILE *file) { FILE *file_student = fopen("student.txt", "w+"); int ch; while((ch = fgetc(file)) != EOF) fputc(ch, file_student); fflush(file_student); int ch2; while((ch2 = fgetc(file_student)) != EOF) { fputc(ch2, stdout); return; } ```
After the firstwhileloop thefile_studentstream will be at the end of the file.fcloseandfopenthe file again orrewindit before reading it back.
Let's suppose I have: ``` myArray[7] = {TRUE,FALSE,FALSE,TRUE,TRUE,FALSE,FALSE} uint8 mybitfield; ``` What is the most efficient way to "push" those values to an uint8 bitfield with0=FALSE,1=TRUE So thatmybitfieldis represented as: ``` [1,0,0,1,1,0,0,0] ``` (The Least Significant Bit is not considered and will be always 0). Thanks!
As already noted, you have to iterate over the bits individually, for example: ``` int myArray[7] = {TRUE,FALSE,FALSE,TRUE,TRUE,FALSE,FALSE}; uint8_t bitfield = 0; for (int i = 0; i < 7; ++i) { bitfield |= myArray[i] ? 1 : 0; bitfield <<= 1; } ``` This results in0b10011000, i.e., the array has the most significant bit first and an implicit zero for the least significant bit.
I am trying to do an implementation of the command 'echo' in C. I would like to have the entire sentence after the command 'echo' read into argv[1] in the command line instead of having each word passed as a separate argument. Is that possible in C?
You can't do this directly, because the shell is splitting the arguments even before your program starts. Maybe you want something like this: ``` #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { char sentence[500] = { 0 }; for (int i = 1; i < argc; i++) { strcat(sentence, argv[i]); if (i < argc - 1) strcat(sentence, " "); } printf("sentence = \"%s\"", sentence); } ``` Disclaimer: no bounds checking is done for brevity. Example of invoking: ``` > myecho Hello World 1 2 3 sentence = "Hello World 1 2 3" ```
I want to know how can I set timeout onzstr_send()andzstr_recv()in czmq library. I know that this can be done withzmq_setsockopt (requester, ZMQ_RCVTIMEO, &timeout, sizeof(timeout))inlibzmq, but not inczmq What is the syntax forlibczmq?!
yep! find it... zsock_set_rcvtimeo()andzsock_set_sndtimeo()are the answers for setting timouts. czmq does not have good docs for its good APIs! :| There are lots of APIs inzsock_option()which has no documentation.
I'm using C with no access to libraries or anything like that since this is kernel code for an operating system. So I can not use sizeOf or any built in function like that. name[] is a character array that holds the name of a file, but the file name can be up to 6 characters long, and I want to determine how long the file name actually is. Right now, my code looks like this: ``` int length = 0; while(name[length] != 0x0) { length++; } ``` I also tried it with the 0x0 replaced with '\0' but it still didn't work. Ideally, it would iterate through the char array and stop once it reaches the end of the file name, but I'm pretty sure that it keeps going past it.
Probably the array doesn't contain the zero char ('\0') immediately after the last char of your string. You can solve this directly by adding the '\0' while you are filling-up an array, or by initializing the whole array by '\0' before filling-up.
Let's suppose I have: ``` myArray[7] = {TRUE,FALSE,FALSE,TRUE,TRUE,FALSE,FALSE} uint8 mybitfield; ``` What is the most efficient way to "push" those values to an uint8 bitfield with0=FALSE,1=TRUE So thatmybitfieldis represented as: ``` [1,0,0,1,1,0,0,0] ``` (The Least Significant Bit is not considered and will be always 0). Thanks!
As already noted, you have to iterate over the bits individually, for example: ``` int myArray[7] = {TRUE,FALSE,FALSE,TRUE,TRUE,FALSE,FALSE}; uint8_t bitfield = 0; for (int i = 0; i < 7; ++i) { bitfield |= myArray[i] ? 1 : 0; bitfield <<= 1; } ``` This results in0b10011000, i.e., the array has the most significant bit first and an implicit zero for the least significant bit.
I am trying to do an implementation of the command 'echo' in C. I would like to have the entire sentence after the command 'echo' read into argv[1] in the command line instead of having each word passed as a separate argument. Is that possible in C?
You can't do this directly, because the shell is splitting the arguments even before your program starts. Maybe you want something like this: ``` #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { char sentence[500] = { 0 }; for (int i = 1; i < argc; i++) { strcat(sentence, argv[i]); if (i < argc - 1) strcat(sentence, " "); } printf("sentence = \"%s\"", sentence); } ``` Disclaimer: no bounds checking is done for brevity. Example of invoking: ``` > myecho Hello World 1 2 3 sentence = "Hello World 1 2 3" ```
I want to know how can I set timeout onzstr_send()andzstr_recv()in czmq library. I know that this can be done withzmq_setsockopt (requester, ZMQ_RCVTIMEO, &timeout, sizeof(timeout))inlibzmq, but not inczmq What is the syntax forlibczmq?!
yep! find it... zsock_set_rcvtimeo()andzsock_set_sndtimeo()are the answers for setting timouts. czmq does not have good docs for its good APIs! :| There are lots of APIs inzsock_option()which has no documentation.
I'm using C with no access to libraries or anything like that since this is kernel code for an operating system. So I can not use sizeOf or any built in function like that. name[] is a character array that holds the name of a file, but the file name can be up to 6 characters long, and I want to determine how long the file name actually is. Right now, my code looks like this: ``` int length = 0; while(name[length] != 0x0) { length++; } ``` I also tried it with the 0x0 replaced with '\0' but it still didn't work. Ideally, it would iterate through the char array and stop once it reaches the end of the file name, but I'm pretty sure that it keeps going past it.
Probably the array doesn't contain the zero char ('\0') immediately after the last char of your string. You can solve this directly by adding the '\0' while you are filling-up an array, or by initializing the whole array by '\0' before filling-up.
I am trying to do an implementation of the command 'echo' in C. I would like to have the entire sentence after the command 'echo' read into argv[1] in the command line instead of having each word passed as a separate argument. Is that possible in C?
You can't do this directly, because the shell is splitting the arguments even before your program starts. Maybe you want something like this: ``` #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { char sentence[500] = { 0 }; for (int i = 1; i < argc; i++) { strcat(sentence, argv[i]); if (i < argc - 1) strcat(sentence, " "); } printf("sentence = \"%s\"", sentence); } ``` Disclaimer: no bounds checking is done for brevity. Example of invoking: ``` > myecho Hello World 1 2 3 sentence = "Hello World 1 2 3" ```
I want to know how can I set timeout onzstr_send()andzstr_recv()in czmq library. I know that this can be done withzmq_setsockopt (requester, ZMQ_RCVTIMEO, &timeout, sizeof(timeout))inlibzmq, but not inczmq What is the syntax forlibczmq?!
yep! find it... zsock_set_rcvtimeo()andzsock_set_sndtimeo()are the answers for setting timouts. czmq does not have good docs for its good APIs! :| There are lots of APIs inzsock_option()which has no documentation.
I'm using C with no access to libraries or anything like that since this is kernel code for an operating system. So I can not use sizeOf or any built in function like that. name[] is a character array that holds the name of a file, but the file name can be up to 6 characters long, and I want to determine how long the file name actually is. Right now, my code looks like this: ``` int length = 0; while(name[length] != 0x0) { length++; } ``` I also tried it with the 0x0 replaced with '\0' but it still didn't work. Ideally, it would iterate through the char array and stop once it reaches the end of the file name, but I'm pretty sure that it keeps going past it.
Probably the array doesn't contain the zero char ('\0') immediately after the last char of your string. You can solve this directly by adding the '\0' while you are filling-up an array, or by initializing the whole array by '\0' before filling-up.
For some reason, whether I trystrchrorstrrchr, I get the same value returned. I have no idea why. Here is the segment of code giving me trouble: ``` printf("Enter a data point (-1 to stop input):\n"); fgets(input, 50, stdin); char *name = strrchr(input, ','); if(name) { printf("%s", name); } ``` The input isJane Austen, 6, and I am trying to separate it into two strings: one before the comma and one after the comma. However, my use ofstrrchr(input, ',');orstrchr(input, ',');seems pointless, as my output is ALWAYS, 6. Can someone explain why?
It sounds like you wantstrtokinstead: ``` char *name = strtok(input, ","); char *value = strtok(NULL, ","); ```
Is there any piece of code I can write or any other way to check which version of the C language my compiler is compiling? I was wondering if there was a way for me to see if the compiler in question is C89, C99, C11, C18 etc. Perhaps utilizing__STDC_VERSION__.
You can look at the__STDC_VERSION__macro, which hast the format YYYYMM and from that deduce whether you run C89, C99, C11 or C18. See alsoWhat is the __STDC_VERSION__ value for C11?
I want to code a matrix calculator, and for that I need to ask the user for it's size,but when I'm declaring a 2d array it won't let me put a variable as a size, so what can I do? ``` int main() { int n; print_enter_matrix_size(); scanf("%d", &n); int matrix[n][n]; return 0; } ```
You can use dynamics arrays. For that you can use malloc to declare the size you want, Try this:allocate matrix in C
OK, I acknowledge that I should check for NULL pointer when mallocing, but what about calloc? Are there any memory leaks possible? ``` int **initializeMatrix(int *rows, int *cols) { int **matrix = malloc((*rows) * sizeof(int*)); checkNullPointer(matrix); for(int i = 0; i < *rows; i++) { matrix[i] = calloc(*cols, sizeof(int)); } return matrix; } void checkNullPointer(int **ptr) { if (ptr == NULL) printErrorMessage(memoryErrorMessage, 101); } ```
You do indeed need to check the return value ofcalloc(it will beNULLif memory could not be allocated), but note that callingfreeon aNULLpointer is a no-op, so there is no immediate memory leak per se. Of course, when cleaning up after encountering aNULLreturn, you'll need to callfreeon all non-NULLpointers emanating from successfulcalloccalls. Personally I'd callcallocon the row allocation too to make that process simpler.
I'm using an if function that needs to check if the string is a NULL but i don't know how to ask for that. I know thatif(a == 'NULL') \\int ashould check to see if the int is NULL but how do I ask if a string is empty or null. I want to sayif(s1[0] == NULL) \\char s1[]or something similar to this? I want to make a code like this? ``` char s2[10]; int a; (...) if(s2[0] == NULL) \\what I am asking about printf("null or empty string\n"); else printf("string with items\n"); ``` I would like to know what I should put for the if statement to ask if the string is NULL.
``` int checkIfNullOrEmpty(const char *str) { return !str || !str[0]; } ```
I was solving a code of maximum and minimum using functions. I wrote the code like this: ``` #include <stdio.h> int maxmin(int x, int y); int main () { int a, b, c; scanf("%d%d", &a, &b); c = maxmin(a, b); if (maxmin == 1) { printf("%d is maximum,%d is minimum", a, b); } else printf("%d is maximum,%d is minimum", b, a); return 0; } int maxmin(int x, int y) { int XisMax = 0; if (x > y) { XisMax=1; } else { XisMax=0; } return XisMax; } ``` So my output shows this results: ``` Input:9,10; 10 is maximum,9 is minimum Input:10,9; 9 is maximum,10 is minimum ``` What is the mistake here? What should I do? PS:I have an exam on functions so solutions using functions will be helpful.
if (maxmin==1) change toif (c==1) your problem is solve. Have a Good day
I have a really simple question: ``` const char *y = "string_test"; x = &y; ``` What type is x ? Thanks in advance for your answers !
Assuming you had a typo in your question, and the code is: ``` const char *y = "string_test"; x = &y; ``` x shall be defined as: ``` const char** x; // x is a pointer(Address of) a pointer to a constant char/string ```
I would like to know if it is possible to define a function type usingtypedef, I tried this syntax: ``` typedef int (*) (void *, void *) order; ``` But it doesn't work. Error message :expected identifier or '(' before ')' token
The alias name should be placed where a variable name would be if it was a variable declaration. Here: ``` typedef int (*order) (void *, void *); // ^~~~~ ``` Or, if you want a function type rather than a pointer-to-function: ``` typedef int order(void *, void *); ```
I would like to init JVM in Apache module viaap_hook_pre_configfun but when I run XAMPP, this error occurs: XAMPP: Starting Apache...fail.httpd: Syntax error on line 158 of /opt/lampp/etc/httpd.conf: Cannot load modules/mod_hotcup.so into server: /opt/lampp/modules/mod_hotcup.so: undefined symbol: JNI_CreateJavaVM It's strange because it compiles normally. Any ideas what is missed? I use Ubuntu 18, Java 11. Here's source codemod_hotcup.c
Your problem comes from the arguments order when invokingld: Libraries to link must after the code to link. Instead of ``` ld -Bshareable -o mod_hotcup.so mod_hotcup.o ``` It should be ``` ld -Bshareable -o mod_hotcup.so mod_hotcup.o -L${LIBPATH} -ljvm ```
So I'm trying to keep asking the user for a number until a number is entered and then print the result but I can't get scanf to be called after the first iteration. Any help would be appreciated. ``` int main(void) { int x; int entered_an_number = 0; while(!(entered_an_number)) { printf("Please enter a number: \n"); if(scanf("%d", &x) == 1) { entered_an_number = 1; } } printf("You entered: %d \n", x); return 0; } ```
The short answer, like the answer to mostscanfquestions, isdon't usescanf. Usefgetsto read a line of input and then scan inside that input, e.g.: ``` char input[128]; fgets(input, sizeof input, stdin); if(sscanf(input, "%d", &x) == 1) { entered_an_number = 1; } ```
I'm using DB2 10.5 Linux and I Need to create a C UDF that can get more than 150 arguments ( plus the null indicators ). It is possible to pass the whole row likeSELECT MYSCHEMA.MYUDF(*) FROM TABLEor is there a way to pass the arguments in an array like PARAMETER STYLE MAIN in procedures ? I haven't found any example or documentation for this.
is not possible to have more than 90 parameters, however I was able to solve the problem using BLOB as input. then create the blob on query with (columns are INT) ``` HEXTORAW(HEX(COLUM_NAME_1))||HEXTORAW(HEX(COLUM_NAME_2)) ``` then in C using a packed structure. works much faster and reduces the code lines in on the C udf.
I have a really simple question: ``` const char *y = "string_test"; x = &y; ``` What type is x ? Thanks in advance for your answers !
Assuming you had a typo in your question, and the code is: ``` const char *y = "string_test"; x = &y; ``` x shall be defined as: ``` const char** x; // x is a pointer(Address of) a pointer to a constant char/string ```
I would like to know if it is possible to define a function type usingtypedef, I tried this syntax: ``` typedef int (*) (void *, void *) order; ``` But it doesn't work. Error message :expected identifier or '(' before ')' token
The alias name should be placed where a variable name would be if it was a variable declaration. Here: ``` typedef int (*order) (void *, void *); // ^~~~~ ``` Or, if you want a function type rather than a pointer-to-function: ``` typedef int order(void *, void *); ```
I would like to init JVM in Apache module viaap_hook_pre_configfun but when I run XAMPP, this error occurs: XAMPP: Starting Apache...fail.httpd: Syntax error on line 158 of /opt/lampp/etc/httpd.conf: Cannot load modules/mod_hotcup.so into server: /opt/lampp/modules/mod_hotcup.so: undefined symbol: JNI_CreateJavaVM It's strange because it compiles normally. Any ideas what is missed? I use Ubuntu 18, Java 11. Here's source codemod_hotcup.c
Your problem comes from the arguments order when invokingld: Libraries to link must after the code to link. Instead of ``` ld -Bshareable -o mod_hotcup.so mod_hotcup.o ``` It should be ``` ld -Bshareable -o mod_hotcup.so mod_hotcup.o -L${LIBPATH} -ljvm ```
So I'm trying to keep asking the user for a number until a number is entered and then print the result but I can't get scanf to be called after the first iteration. Any help would be appreciated. ``` int main(void) { int x; int entered_an_number = 0; while(!(entered_an_number)) { printf("Please enter a number: \n"); if(scanf("%d", &x) == 1) { entered_an_number = 1; } } printf("You entered: %d \n", x); return 0; } ```
The short answer, like the answer to mostscanfquestions, isdon't usescanf. Usefgetsto read a line of input and then scan inside that input, e.g.: ``` char input[128]; fgets(input, sizeof input, stdin); if(sscanf(input, "%d", &x) == 1) { entered_an_number = 1; } ```
I'm using DB2 10.5 Linux and I Need to create a C UDF that can get more than 150 arguments ( plus the null indicators ). It is possible to pass the whole row likeSELECT MYSCHEMA.MYUDF(*) FROM TABLEor is there a way to pass the arguments in an array like PARAMETER STYLE MAIN in procedures ? I haven't found any example or documentation for this.
is not possible to have more than 90 parameters, however I was able to solve the problem using BLOB as input. then create the blob on query with (columns are INT) ``` HEXTORAW(HEX(COLUM_NAME_1))||HEXTORAW(HEX(COLUM_NAME_2)) ``` then in C using a packed structure. works much faster and reduces the code lines in on the C udf.
I am new to C. I just want to know why initializing the array of int with int is working and why initializing an array of char with char is not working. Oram I wrong thinking that "1" is a char? ``` #include <stdio.h> int main() { int incoming_message_test[2] = {1, 2}; // why does this work? char incoming_message[2] = {"1", "2"}; // why does this not work? return 0; } ```
You must change"1", "2"with'1', '2'
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.Closed3 years ago.Improve this question I saw this example in an If statementy<>3and I was wondering what it does.
I have to check if this exercise is correct It is not. ``` if (((x < y) && (y < z)) && (y != 3)) printf(“%f < %d < %d \n”, x, y, z); ``` Is correct, assumingfloat xandint y, z. <>in some languages means "does not equal". But in c, the operator is!=. Also note the difference between logical AND (&&) and bitwise AND (&). You should use the logical operators for multiple criteria in a conditional statement.
I want to pass this two dimensional array of pointers to a function: array: ``` *cmd[maxCmdSize][maxArgSize] ``` function: ``` void performCmd(char *cmd[maxCmdSize][maxArgSize]) ``` How to achieve this without declaring the size of the dimensions in the function?
How to achieve this without declaring the size of the dimensions in the function? Youcannotomit the second dimension of the array. So you need to have your prototype like this: ``` void performCmd(int *cmd[][maxArgSize]); ``` and call the method like this: ``` performCmd(cmd); ```
I'm compiling with a command: ``` gcc grep.c -std=c99 -g -Winit-self -pedantic -w -o main2 && ./main2 lib text.txt ``` and I wish to receive warnings for initialized but not used variables and functions.
If you use-Wunused-variableit will warn for unused variables. But I recommend using-Wall -Wextra. Then you will get that for free with a bunch of other stuff. When it comes to unused functions I refer to this:GCC -Wunused-function not working (but other warnings are working)
I don't seem to understand what's happening here ``` #include <stdio.h> int var = 5; int main(){ int var = var; printf("%d",var); return 0; } ``` Why does this program print a garbage value when the value of var is assigned to be 5?
the local var has priority on the global var. So the compiler translate it as (local) var = (local) var
``` int main(void) { int a = 65; char c = (char)a; printf("%c\n", c); // output: A printf("%f\n", (float)a); // output: 65.000000 printf("%f\n", 5/2); // output: 65.000000 why??? return 0; } //why printf("%f\n", 5/2); prints same number as a number above???? ``` it supposed to print 2.5, i want to know why it doesn't prints this number and what's happens bts? i tried to find answers on google but i'm not sure how to question this problem
you have the UB in that code. in the third printf - you pass integer but printf expects double - UB cast it and it will work correctlyhttps://godbolt.org/z/M3ysha
I am trying to run a simple program below on my mac using CodeBlocks IDE: ``` 1. #include <stdio.h> 2. int main() 3. { 4. // printf() displays the string inside quotation 5. printf("Hello, World!"); 6. return 0; 7. } ``` but I get the following error: error: expected identifier or '(' As the machine is trying to compile, I think gcc compiler is working fine.
Remove the line numbers, that's the problem.
I try code reading cp command in FreeBSD. I'm reading cp.c of FreeBSD. I don't understand below code. ``` if (to.p_path == to.p_end) {         *to.p_end++ = '.';         *to.p_end = 0; } ``` What purpose this code? What does effect any situation? Original Source Code is there.https://svnweb.freebsd.org/base/release/12.0.0/bin/cp/cp.c?revision=341707&view=markup
Basically, this reads as ``` if o.p_path == "": o.p_path = "." ``` If I understand it right, it makescp /somepath/somefileto work likecp /somepath/somefile .
I've been trying to change the active partition of an LTO8 tape in Windows (7 & Server 2012 R2) using the following code snippet (which gcc compiles without any warnings): ``` DWORD partition= 2; if(SetTapePosition(hTape, TAPE_LOGICAL_BLOCK, partition, 0, 0, FALSE) != NO_ERROR) <irrelevant error code here> ``` which returns without any errors. But it doesn't change the partition. I can use the same function and handle to seek to various blocks within the first (default) partition, so I don't think that's the problem. The tape is definitely partitioned, and I have no problem changing to the second partition under linux using the mt command.
Turns out the issue is with Quantum's device driver; if I force load HP's device driver, I can change the active partition without any issue.
I'm compiling with a command: ``` gcc grep.c -std=c99 -g -Winit-self -pedantic -w -o main2 && ./main2 lib text.txt ``` and I wish to receive warnings for initialized but not used variables and functions.
If you use-Wunused-variableit will warn for unused variables. But I recommend using-Wall -Wextra. Then you will get that for free with a bunch of other stuff. When it comes to unused functions I refer to this:GCC -Wunused-function not working (but other warnings are working)
I don't seem to understand what's happening here ``` #include <stdio.h> int var = 5; int main(){ int var = var; printf("%d",var); return 0; } ``` Why does this program print a garbage value when the value of var is assigned to be 5?
the local var has priority on the global var. So the compiler translate it as (local) var = (local) var
``` int main(void) { int a = 65; char c = (char)a; printf("%c\n", c); // output: A printf("%f\n", (float)a); // output: 65.000000 printf("%f\n", 5/2); // output: 65.000000 why??? return 0; } //why printf("%f\n", 5/2); prints same number as a number above???? ``` it supposed to print 2.5, i want to know why it doesn't prints this number and what's happens bts? i tried to find answers on google but i'm not sure how to question this problem
you have the UB in that code. in the third printf - you pass integer but printf expects double - UB cast it and it will work correctlyhttps://godbolt.org/z/M3ysha
I am trying to run a simple program below on my mac using CodeBlocks IDE: ``` 1. #include <stdio.h> 2. int main() 3. { 4. // printf() displays the string inside quotation 5. printf("Hello, World!"); 6. return 0; 7. } ``` but I get the following error: error: expected identifier or '(' As the machine is trying to compile, I think gcc compiler is working fine.
Remove the line numbers, that's the problem.
I try code reading cp command in FreeBSD. I'm reading cp.c of FreeBSD. I don't understand below code. ``` if (to.p_path == to.p_end) {         *to.p_end++ = '.';         *to.p_end = 0; } ``` What purpose this code? What does effect any situation? Original Source Code is there.https://svnweb.freebsd.org/base/release/12.0.0/bin/cp/cp.c?revision=341707&view=markup
Basically, this reads as ``` if o.p_path == "": o.p_path = "." ``` If I understand it right, it makescp /somepath/somefileto work likecp /somepath/somefile .
I've been trying to change the active partition of an LTO8 tape in Windows (7 & Server 2012 R2) using the following code snippet (which gcc compiles without any warnings): ``` DWORD partition= 2; if(SetTapePosition(hTape, TAPE_LOGICAL_BLOCK, partition, 0, 0, FALSE) != NO_ERROR) <irrelevant error code here> ``` which returns without any errors. But it doesn't change the partition. I can use the same function and handle to seek to various blocks within the first (default) partition, so I don't think that's the problem. The tape is definitely partitioned, and I have no problem changing to the second partition under linux using the mt command.
Turns out the issue is with Quantum's device driver; if I force load HP's device driver, I can change the active partition without any issue.
I need to store a 64-bit memory address in a variable, alongshould be large enough to hold such value. For example: ``` long arr[2]; //store the memory address of arr[1] in arr[0] arr[0] = (long)(arr + 1); printf("arr[0]: 0x%012x Actual address: %p\n", arr[0], (void *)arr); ``` Output: ``` arr[0]: 0x00007c6a2c20, Actual address: 0x7ffe7c6a2c20 ``` The value stored inarr[0]seems to be truncated. What am I missing here?
If you want to store a 64 bit values, you can useuint64_ttype of variable. However, since the values you want to store are addresses, probably you need to useuintptr_t, make sure the available size of that type in your platform and you can use that.
I have a following code: ``` void prepareInput(char* s){ while ( *(s++) ){ if(*s == ' ' || *s == '\n') *s = '\0'; } return; } ``` What will*(s++)return that will cause while loop to stop?
Same as other cases, when that expression evaluates to FALSE. In other words, it's the same aswhile ( (*(s++)) != 0 ){...... Basically, it's trying to find the null-terminator for thestringand the loop will go on until it finds the null terminator (having a value0).
I am trying to find "python.exe" in szExeFile after aProcess32NextWcall. I tried doing a ``` if(strcmp(lppe->szExeFile,"python.exe") == 0){ //do stuff } ``` but the check always fails despite the process running. I have also tried using strncmp but it does not change anything. What am I doing wrong?
Process32NextW()seems to usePROCESSENTRY32Wstruct with wide character strings. Trywcscmp()instead ofstrcmp().
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed3 years ago.Improve this question Essentially, this is my problem. ``` FILE *fp = "/my/textfile/location"; fseek(fp, 0L, SEEK_END); int size = ftell(fp); char *output_string[size]; printf("%d", size); // gives me 25 printf("%ld", sizeof(output_string)); // gives me 200. ``` Why does sizeof(output_string) give me 200 when the int returned from ftell is 20?
``` char *output_string[size]; ``` This is array of pointer, if you are running in 64-bits machine, one pointer is 64-bits, which is 8 bytes. if size is 25, then : ``` sizeof(output_string) = 25 * sizeof(char *) = 25 * 8 = 200 ```
So far i have the following code: ``` char* s; s = new char[10]; __asm { mov ebx, s mov byte ptr[ebx], 0x48 ;'H' mov byte ptr[ebx + 1], 0x65 ;'e' mov byte ptr[ebx + 2], 0x6C ;'l' mov byte ptr[ebx + 3], 0x6C ;'l' mov byte ptr[ebx + 4], 0x6F ;'o' mov byte ptr[ebx + 5], 0x0A ; 'new line' mov byte ptr[ebx + 6], 0; mov eax, ebx push eax call DWORD ptr printf pop ebx } ``` I'd like to declare a char array in asm not using DB, how would that look like?
possible also this way: ``` call do_print db "Hola...Hello", 0Ah,0 do_print: call DWORD ptr printf pop rcx ``` while making call to do_print we put to the stack return address what is in fact start address of our buffer "Hello..", so simple in assembler, changed to pop rcx instead pop [esp]
I have a C programm compiled with gcc in linux 32 bits without stack protectors. This program have one argument and this is a string with hexadecimal values (for send to stack for buffer overflow). My run example is: ``` ./myprogram.out `python -c "print 'A'*91+'\x20\xee\xff\xbf"` ``` My problem is with \x20 value. This is interpreted as ASCII 32 (whitespace) and it is interpeted as end of parameter and the value save in the stack is 00 (null value, end string). Example of values in stack (hexadecimal): ....41 41 41 41 00 EE FF BF..... For me, \x20 is a part of a memory address to save in the stack for this reason i need to save 20 in hexadecimal in the stack.
You need to quote the result of `` so that it isn't split by the shell. BTW assuming an sh variant,$()is usually preferable to ``. Both at the same time results in ``` ./myprogram.out "$(python -c "print 'A'*91+'\x20\xee\xff\xbf'")" ```
I need to store a 64-bit memory address in a variable, alongshould be large enough to hold such value. For example: ``` long arr[2]; //store the memory address of arr[1] in arr[0] arr[0] = (long)(arr + 1); printf("arr[0]: 0x%012x Actual address: %p\n", arr[0], (void *)arr); ``` Output: ``` arr[0]: 0x00007c6a2c20, Actual address: 0x7ffe7c6a2c20 ``` The value stored inarr[0]seems to be truncated. What am I missing here?
If you want to store a 64 bit values, you can useuint64_ttype of variable. However, since the values you want to store are addresses, probably you need to useuintptr_t, make sure the available size of that type in your platform and you can use that.
I have a following code: ``` void prepareInput(char* s){ while ( *(s++) ){ if(*s == ' ' || *s == '\n') *s = '\0'; } return; } ``` What will*(s++)return that will cause while loop to stop?
Same as other cases, when that expression evaluates to FALSE. In other words, it's the same aswhile ( (*(s++)) != 0 ){...... Basically, it's trying to find the null-terminator for thestringand the loop will go on until it finds the null terminator (having a value0).
I am trying to find "python.exe" in szExeFile after aProcess32NextWcall. I tried doing a ``` if(strcmp(lppe->szExeFile,"python.exe") == 0){ //do stuff } ``` but the check always fails despite the process running. I have also tried using strncmp but it does not change anything. What am I doing wrong?
Process32NextW()seems to usePROCESSENTRY32Wstruct with wide character strings. Trywcscmp()instead ofstrcmp().
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed3 years ago.Improve this question Essentially, this is my problem. ``` FILE *fp = "/my/textfile/location"; fseek(fp, 0L, SEEK_END); int size = ftell(fp); char *output_string[size]; printf("%d", size); // gives me 25 printf("%ld", sizeof(output_string)); // gives me 200. ``` Why does sizeof(output_string) give me 200 when the int returned from ftell is 20?
``` char *output_string[size]; ``` This is array of pointer, if you are running in 64-bits machine, one pointer is 64-bits, which is 8 bytes. if size is 25, then : ``` sizeof(output_string) = 25 * sizeof(char *) = 25 * 8 = 200 ```
So far i have the following code: ``` char* s; s = new char[10]; __asm { mov ebx, s mov byte ptr[ebx], 0x48 ;'H' mov byte ptr[ebx + 1], 0x65 ;'e' mov byte ptr[ebx + 2], 0x6C ;'l' mov byte ptr[ebx + 3], 0x6C ;'l' mov byte ptr[ebx + 4], 0x6F ;'o' mov byte ptr[ebx + 5], 0x0A ; 'new line' mov byte ptr[ebx + 6], 0; mov eax, ebx push eax call DWORD ptr printf pop ebx } ``` I'd like to declare a char array in asm not using DB, how would that look like?
possible also this way: ``` call do_print db "Hola...Hello", 0Ah,0 do_print: call DWORD ptr printf pop rcx ``` while making call to do_print we put to the stack return address what is in fact start address of our buffer "Hello..", so simple in assembler, changed to pop rcx instead pop [esp]
I have the unfortunate task of bringing some code written in C into C++. I've come across an uninitialised enum in a struct with the following form. ``` enum theEnum { A = 1, B = 2, C = 3, } struct theCStruct{ enum theEnum enuminstance; } theCStruct structInstance; ``` I know that in C++ this would be undefined, but as I'm finding out uninitialised variables in C structs default to 0 (at least for ints) rather than undefined. In this case what will the default value of the enum be in C?
uninitialised variables in C structs default to 0 (at least for ints) rather than undefined. That is a myth, unless thestructinstance hasstaticor_Thread_localstorage duration or is at global scope. The two languages are identical in this respect. As a rule of thumb, don'tport, butinterop. C has an extremely good API on common operating systems.
I have created a library in C and want to link it when compiled. Do I have to save in a certain folder in my computer's file system or can I create my own file structure within my application to save it? Update: My error turned out to be not properly including a header file. My files and linker were fine but it was simple syntax error.
You can save it wherever you want. Just make sure that the compiler knows the location. In the case ofgccfor example, you can use: ``` gcc -L path/to/libdir -l:mylib.a ... ``` (assumingmylib.ais inpath/to/libdir) Or even: ``` gcc path/to/libdir/mylib.a ... ```
This question already has answers here:How should character arrays be used as strings?(4 answers)Closed3 years ago. I have made this function to extract the first 2 characters of a string: ``` string get_salt(string hash) { char pre_salt[2]; for (int i = 0; i < 2; i++) { pre_salt[i] = hash[i]; } string salt = pre_salt; printf("%s\n", salt); return(salt); } ``` But when I run it with a string that has "50" (is the example I'm using) as the first 2 characters, I get this output: ``` 50r®B ``` And to be honest I have no idea why is it adding the 3 extra characters to the resulting string.
You are missing the string's NUL terminator '\0' so it keeps printing until it finds one. Declare it like: ``` char pre_salt[3]={0,0,0}; ``` And problem solved.
I am writing a program using GTK in C. I am using GtkListStore to display some data coming from a database. After a particular signal I want to remove all the rows in the GtkListStore. I used gtk_list_store_clear() function, but it raises Segmentation Fault. What is wrong with my code? ``` //Globally declared GtkListStore *liststore2; //Inside main() function liststore2 = GTK_LIST_STORE(gtk_builder_get_object(builder, "liststore2")); //Inside signal handler function gtk_list_store_clear(liststore2); //Error comes from here ```
If you destroy the builder object (usingg_object_unref(builder)) before the signal handler runs, liststore2 may point to freed memory. That happens if liststore2 is free-standing (i.e., not ref'ed by something else, for example a GtkTreeView) gtk_builder_get_objectdoesnotincrement the reference count on object
I was wondering if there is a way to visualize (inside Visual Studio) how much of the heap memory I'm using during the execution of my program. Thanks
Use the Memory Usage Diagnostic Tool in Visual Studio:https://learn.microsoft.com/en-us/visualstudio/profiling/memory-usage?view=vs-2019 The Memory Usage tool lets you take one or more snapshots of the managed and native memory heap to help understand the memory usage impact of object types. You can collect snapshots of .NET, native, or mixed mode (.NET and native) apps. Here's a great blog article on its usage as well:https://devblogs.microsoft.com/visualstudio/analyze-cpu-memory-while-debugging/
I stumbled into this and I don't know what it does exactly ``` int i; for ( i = 1; i <= 20; i++ ) { printf( "%10d", (1+rand()%6) ); if ( i % 5 == 0 ) { printf( "\n" ); } } ``` Above is part of a program that tosses a dice for 20 times. The thing i don't understand is this line: ``` printf( "%10d", (1+rand()%6) ); ``` My problem is "%10d" Is this a visual thing because outputs order of appearance change with it. I know in float values it shows decimal point but what about in integers as int, also can anyone tell me the difference between this: ``` prinf("%.2f",value); ``` and this: ``` prinf("%6.2f",value); ``` They both print 1000.30, so what is 6 for?
"%10d"means to pad with spaces on the left, as needed, so decimal output is at least 10characters.
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed3 years ago.Improve this question I am trying to figure out which practice is the best between : ``` #define TEST //#define TEST commented if not used or simply deleted ``` ``` #define TEST 1 #define TEST 0 //if not used ``` For readability, I prefer to define a "Boolean" and check it in aifbut I guess it is not efficient since it doesn't use#ifdefand it needs to be checked everytime in a if
While you can't use an#ifdeffor your second case, you absolutely can use an#ifso there would be no additional runtime cost for TEST 0. This btw. also means you can have multiple different values for TEST, maybe corresponding to different log levels or things like that (Posted my comment as an answer, as suggested by Bathsheba)
My project requirement is to reduce text segment of object files used in my project. I tried reducing redundant logic but the change results is minimum amount of bytes . My code uses switch cases ,nested if/else ,along with const arrays and for/while loops .It also contains semaphores,mutex etc. Can you please suggest best solution to reduce maximum instruction used in text segment?
Optimize for size. If you are using GCC, use the flag -Os, which instructs GCC to "optimize for size." It enables all -O2 optimizations which do not increase the size of the executable, and then it also toggles some optimization flags to further reduce executable size.
I want to add more * for each line but it appears only 1 * for each line. so confusing Here is my code ``` #include <stdio.h> int main() { int number; scanf("%d",&number); for(int i = 1 ; i <= number ; i++) { printf("*\n"); } return 0; } ``` ``` This is my output 5 * * * * * ``` ``` This is output I want 5 * ** *** **** ***** ```
Nest a j loop printing from 1 to i stars. After said loop, but inside the outer, put a newline. ``` #include <stdio.h> int main() { int number; if (scanf("%d",&number) == 1 && number > 0) { for(int i = 1 ; i <= number ; i++) { for (int j=1; j<=i; ++j) fputc('*', stdout); fputc('\n', stdout); } } return 0; } ```
I'm trying tocompare a llvm Type and a Type*. I'm using the LLVM C APIs. Is there any possible method to do this? I haveType*because I did LLVMTypeOf api to get the type from an LLVM Value. So if I can get theType from a Value, it would also fix the issue.
Types are unique in LLVM world, so you could compare their addresses.
I am using char array variable which is declared like this : ``` char our_thread[8]="thread1"; ``` I am using it into a function which creates threads : ``` kthread_create(thread_fn,NULL,our_thread); ``` The thread will be named "thread1" in the list of processes . I want to change thread1 char array variable into a dynamic variable in order that every time the thread is created will have another name instead of "thread1". Thank you.
The question is a bit broad, but anyway maybe this helps: ``` char our_thread[20]; for (int i = 0; i < 100; i++) { sprintf(out_thread, "thread%d", rand() % 100); printf("thread name %s\n", our_thread); } ``` You should be able to figure out the rest. Read the documentation ofrandandsprintf.
I'm trying tocompare a llvm Type and a Type*. I'm using the LLVM C APIs. Is there any possible method to do this? I haveType*because I did LLVMTypeOf api to get the type from an LLVM Value. So if I can get theType from a Value, it would also fix the issue.
Types are unique in LLVM world, so you could compare their addresses.
I am using char array variable which is declared like this : ``` char our_thread[8]="thread1"; ``` I am using it into a function which creates threads : ``` kthread_create(thread_fn,NULL,our_thread); ``` The thread will be named "thread1" in the list of processes . I want to change thread1 char array variable into a dynamic variable in order that every time the thread is created will have another name instead of "thread1". Thank you.
The question is a bit broad, but anyway maybe this helps: ``` char our_thread[20]; for (int i = 0; i < 100; i++) { sprintf(out_thread, "thread%d", rand() % 100); printf("thread name %s\n", our_thread); } ``` You should be able to figure out the rest. Read the documentation ofrandandsprintf.
I came across a passage: The definition of concurrent execution in POSIX requires that "functions that suspend the execution of the calling thread shall not cause the execution of the other threads to be indefinitely suspended". Can someone please explain this to me (especially what is calling thread - I understand what calling function is).
The calling threadis thethread of executionwhere a blocking function is called. If you havetwothreads, then one can call a blocking function likesleepto sleep for an hour and the other thread may not be stopped for the duration of one hour too because of the call that happened in the first one.
I came across a passage: The definition of concurrent execution in POSIX requires that "functions that suspend the execution of the calling thread shall not cause the execution of the other threads to be indefinitely suspended". Can someone please explain this to me (especially what is calling thread - I understand what calling function is).
The calling threadis thethread of executionwhere a blocking function is called. If you havetwothreads, then one can call a blocking function likesleepto sleep for an hour and the other thread may not be stopped for the duration of one hour too because of the call that happened in the first one.
I came across a passage: The definition of concurrent execution in POSIX requires that "functions that suspend the execution of the calling thread shall not cause the execution of the other threads to be indefinitely suspended". Can someone please explain this to me (especially what is calling thread - I understand what calling function is).
The calling threadis thethread of executionwhere a blocking function is called. If you havetwothreads, then one can call a blocking function likesleepto sleep for an hour and the other thread may not be stopped for the duration of one hour too because of the call that happened in the first one.
This question already has answers here:Python pi calculation?(3 answers)Closed3 years ago. Well, I searched a lot to find a solution to calculating pi recursively in python, but i did not find any solution on entire stackoverflow and internet, Although I found a solution for C language inCalculating PI recursively in C ``` double pi(int n){ if(n==1)return 4; return 4*pow(-1,n+1)*(1/(double)(2*n-1)))+pi(n-1); } ``` As I know nothing about c language and how it's syntax is, I wanted to ask how can I do the same in python3.
Re-written in python: ``` def get_pi(n): if n == 1: return 4 return 4 * (-1)**(n+1) * (1/(2*n-1)) + get_pi(n-1) ```
I'm trying to use ADC with DMA using STM32F407. I want to set memory adress ofADCValueto DMA stream x memory 0 address register. But i get this error: ``` type name is not allowed ``` This part is inmain ``` unsigned short ADCValue[1]; DMA2_Stream0->M0AR= uint32_t(&ADCValue); ``` and definition of register ``` __IO uint32_t M0AR; /*!< DMA stream x memory 0 address register */ ```
You're casting the wrong way. It should be: ``` DMA2_Stream0->M0AR = (uint32_t)&ADCValue; ``` But since it is an array, the&is not necessary either. An array will automatically decay to a pointer when used this way. So this will do: ``` DMA2_Stream0->M0AR = (uint32_t)ADCValue; ```
I'm trying to simulatecpon UNIX using C. Here's my code. ``` #include <stdio.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> int main(int argc, char const *argv[]) { int src, dest; char buff[256]; int bits_read; src = open(argv[1], O_RDONLY); dest = open(argv[2], O_WRONLY | O_TRUNC | O_CREAT, 0644); if (dest < 0) perror("Er"); while ((bits_read = read(src, buff, sizeof(buff))) > 0) if (bits_read != write(dest, buff, sizeof(buff))) perror("Er"); close(src); close(dest); return 0; } ``` I'm getting the following output: Er: Undefined error: 0 I can see that the new file contains some repeated lines at the end.
The last line is not sizeof(buf) long.Use ``` if (bits_read != write(dest, buff, bits_read)) ```
Are both null and NULL constants the exact same thing in C/C++? I've noticed as I write my code in Visual Studio that null and NULL don't get the same syntax highlighting, and the compile outcome is not the same as having null instead of NULL in some sections of the code.
They might be, they might not be. Both C and C++ defineNULL, but in slightly different ways. nullis not part of either standard; it is neither a keyword nor a reserved word, so you can use it as a variable name, class name &c.. The preferred way of denoting pointer null-ness in C++ isnullptrwhich has type especially designed for pointer nullness.
I tried googling them separately, but one thing stuck out the most. Is it just that IAT is for PE files and GoT is for ELF?
Is it just that IAT is for PE files and GoT is for ELF? This is the main difference. Another difference is that the GOT in ELF files may also contain entries describing symbols defined in the ELF file itself. This is typical for 32-bit shared libraries. IATs in PE files contain only entries that describe symbols defined in other DLL files.
I've made a function, but I'm struggling with calling it. This is the prototype of the function: ``` char *test(int argc, char **argv); ``` I've tried calling it this way but it doesn't work : ``` int main() { char tab[3][3] ={ "Yo", "Hi"}; test(2, tab); return (0); } ```
For me this works: ``` char* test(int index, char** char2Darray) { return char2Darray[index]; } int main() { char* tab[2] ={ "Yo", "Hi"}; test(1, tab); return (0); } ``` I think there are two problems in your code : the tab what you provided has only two itemyour tab is a pointer which pointing to char[3] types and not char*
I'm new in C and I would like to know how can I correct this error I can keep getting please: "expression must have integral type" ``` switch (detect_format(format)) { case "%d": printf("teqs"); break; default: break; } ``` note :detect_format(format)returns a string.
As per the standard,C11, chapter 6.8.4.2: The controlling expression of aswitchstatement shall have integer type Astringis not allowed. That said, the case labels, also need to be integer constant expression, something likecase "%d":is also illegal. If you want to take a decision based on the returnedstring, you will need to usestrcmp()and use the result as the controlling expression of aswitchstatement.
I want to define a function, that returns either astructwith multiple values of variant type or a singleint *depending on arguments, a user passes over the command line.I know, that I could just simply always return astructand retrieve the specific values from thestructrelated to users input data, but I was wondering if there is any possibility to state that a function will return either A or B.
No, a function return type has to be determined and fixed during compile time, it cannot be changed during run-time (i.e., based on a user input). You can however, make use of an array of function pointers to call different functions based on the user input.
I am not able to understand why the following C program returns a value 34? ``` int main(void) { char c; char c1='a', c2='b'; c= c1*c2; printf("%d", c); } ``` Any help is greatly appreciated!
Ascii value of "a" is 97, of "b" is 98. Since thechar(which can besigned charorunsigned chardepending on implementation) can hold maximum value of 127 forsigned char(or 255 forunsigned char), you get: 97*98modulo128 = 34 well, in C notation: ``` (97*98) % 128 == 34 ``` PS: replacing 128 with 256 gives 34 as well.
I am learning networking on Windows using C. I came acrossIN6_ADDRstructure that represents an IPv6 address as a union of 2 arrays: ``` typedef struct in6_addr { union { UCHAR Byte[16]; USHORT Word[8]; } u; } IN6_ADDR, *PIN6_ADDR, *LPIN6_ADDR; ``` I can't wrap my head around why would someone desire a union of 2 arrays instead of just 1 array. What is the reason for such declaration? Note that both arrays are 128 bits long.
IPv6 addresses are generally written in a format that uses 2-byte groups, e.g. ``` 2001:0db8:85a3:0000:0000:8a2e:0370:7334 ``` Each of those groups corresponds to an element of theWordarray. But sometimes it's also useful to process each byte of the address. In this case, you would use theBytearray, rather than having to shift and mask elements ofWord.
Is there a way to calculate the maximum value representable byunsigned intwithout usinglimits.h(so noUINT_MAX) or without using ``` unsigned int z = 0; z = z - 1; ```
The simplest way to do this is to simply assign -1 to anunsigned int. You could also assign~0uto it. If that's not acceptable, while inefficient, you could do something like this: ``` unsigned int i = 0; while (i+1 > 0) i++; printf("i=%u\n", i); ```
I'm new in C and I would like to know how can I correct this error I can keep getting please: "expression must have integral type" ``` switch (detect_format(format)) { case "%d": printf("teqs"); break; default: break; } ``` note :detect_format(format)returns a string.
As per the standard,C11, chapter 6.8.4.2: The controlling expression of aswitchstatement shall have integer type Astringis not allowed. That said, the case labels, also need to be integer constant expression, something likecase "%d":is also illegal. If you want to take a decision based on the returnedstring, you will need to usestrcmp()and use the result as the controlling expression of aswitchstatement.
I want to define a function, that returns either astructwith multiple values of variant type or a singleint *depending on arguments, a user passes over the command line.I know, that I could just simply always return astructand retrieve the specific values from thestructrelated to users input data, but I was wondering if there is any possibility to state that a function will return either A or B.
No, a function return type has to be determined and fixed during compile time, it cannot be changed during run-time (i.e., based on a user input). You can however, make use of an array of function pointers to call different functions based on the user input.
I am not able to understand why the following C program returns a value 34? ``` int main(void) { char c; char c1='a', c2='b'; c= c1*c2; printf("%d", c); } ``` Any help is greatly appreciated!
Ascii value of "a" is 97, of "b" is 98. Since thechar(which can besigned charorunsigned chardepending on implementation) can hold maximum value of 127 forsigned char(or 255 forunsigned char), you get: 97*98modulo128 = 34 well, in C notation: ``` (97*98) % 128 == 34 ``` PS: replacing 128 with 256 gives 34 as well.
I am learning networking on Windows using C. I came acrossIN6_ADDRstructure that represents an IPv6 address as a union of 2 arrays: ``` typedef struct in6_addr { union { UCHAR Byte[16]; USHORT Word[8]; } u; } IN6_ADDR, *PIN6_ADDR, *LPIN6_ADDR; ``` I can't wrap my head around why would someone desire a union of 2 arrays instead of just 1 array. What is the reason for such declaration? Note that both arrays are 128 bits long.
IPv6 addresses are generally written in a format that uses 2-byte groups, e.g. ``` 2001:0db8:85a3:0000:0000:8a2e:0370:7334 ``` Each of those groups corresponds to an element of theWordarray. But sometimes it's also useful to process each byte of the address. In this case, you would use theBytearray, rather than having to shift and mask elements ofWord.
I am translating some code from C to Python 3, and checking that the functions give the correct output. In the manual for the C code, this is what it says for thepb_get_version()function: I then try to implement this in Python. I load the DLL, define the function, and print its output. ``` import ctypes spinapi = ctypes.CDLL("spinapi64") pb_get_version = spinapi.pb_get_version version = pb_get_version() print("Using SpinAPI Library version {}".format(version)) % Using SpinAPI Library version 331435824 ``` The output is not in the YYYMMDD as I expect it... Could this be a translation error from the DLL (C) to Python? Is there a simple way to translatechar*to python?
By default,ctypesassumes that the function returns anint. You must specify that the function returns achar*for it to work. Try the following before calling the function: ``` pb_get_version.restype = ctypes.c_char_p ```
The following code should prompt the user for prices and add that to a total. If the user inputs-1the adding loop must terminate and the program should print a total and exit. But for some reason this is not happening. ``` #include <stdio.h> int main() { int price; int sum; int exit; do { printf(" Enter a price(-1 to exit)"); scanf("%d", & price); sum = sum + price++; printf("the sum of prices is % d ", sum); } while (exit != -1); return 0; } ``` Q: Why does my program not add numbers until -1 is given?
You should useif-elsestatement to resolve it. Like shown below: ``` while(price != -1) { printf(" \nEnter a price(-1 to exit)"); scanf("%d", &price); if (price == -1) { break; } else{ sum = sum + price; printf(" \ntotal sum till now is %d", sum); } } ```
I am trying to convert an long date to a readable format as ``` void ConvertToDateTime(unsigned long dateTime, char *result) { uint8_t day = dateTime % 100; uint8_t month = (dateTime / 100) % 100; uint8_t year = dateTime / 10000; sprintf(result, "%02u/%02u/%04u", day, month, year); } ``` The caller method... ``` char *readableDateTime = (char*)""; ConvertToDateTime(atoi(datestring), readableDateTime); ``` While debugging the datetime parameter is20191112(yyyymmdd) but theresultis null|empty string|nadaif you prefer. What am I doing wrong here?
Your code writes to a 1-byte readonly area of memory. This is more likely to crash the program than do anything useful. Use: ``` char readableDateTime[100] = ""; ``` Also, an 8-bit unsigned integer can only hold values 0..255. Note that 2019 % 256 is 227. Use at leastuint16_tforyear.
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.Closed3 years ago.Improve this question We put a range from keyboard from what number to what number we want to search the ''Sweet number''. One number is sweet if each of the digits is an even number. So I started and don't know how to go on ``` int min,max,i,sweetnumber; scanf("%d%d",&min,&max); for(i=min;i<=max;i++) { // and now what ? i don't know if the number is three-digit or four-digit or five digit so i can check a digit by digit .. Someone help ! } ```
It seems you need something like the following ``` for ( i = min; i <= max; i++ ) { int tmp = i; while ( tmp != 0 && tmp % 10 % 2 == 0 ) tmp /= 10; if ( tmp == 0 ) printf( "%d is a sweet number\n", i ); } ```
I am building a client/server protocol using libwebsockets library. In the poll thread, each callback on incoming packets triggers a certain method to either save data, respond accordingly, and so on. However, if there are other incoming packets that would trigger LWS_CALLBACK_CLIENT_RECEIVE, the processing of the previous task is left undone. Is there a way to finish the tasks before dealing with the packets received? Should LWS_CALLBACK_CLIENT_RECEIVE start new threads to handle the processing of data?
This was a typical case of multi-threading: one thread receives the packets, fills a buffer and goes back to listening for incoming packets. Working threads will empty the buffer.