question
stringlengths
25
894
answer
stringlengths
4
863
So I want to print the copyright symbol and putchar() just cuts off the the most significant byte of the character which results in an unprintable character. I am using Ubuntu MATE and the encoding I am using is en_US.UTF-8. Now what I know is that the hex value for © is 0xc2a9 and when I try putchar('©' - 0x70) it g...
Theputcharfunction takes anintargument andcasts it to anunsigned charto print it. So you can't pass it a multibyte character. You need to callputchartwice, once for each byte in the codepoint. ``` putchar(0xc2); putchar(0xa9); ```
Hi guys I'm new to C and pointers so I hope you'll forgive me. I have the following code: ``` char *str = NULL; *str = 'a'; printf("My string is :%s\n",str); ``` It compiles but I'm getting a segmentation error everytime. What is the cause of this and what how can I change it so that I can assign 'a' to my string? ...
``` char *str = NULL; ``` The pointer str is not allocated yet. So you can not dereference it. Then you tried to deference by ``` *str = 'a'; ``` The segmentation fault will occur. If you want str with "a" value, you can do this way: ``` char *str = "a"; printf("My string is :%s\n",str); ```
I ran it through an IDE and the remainder values came out 3, 2, 0, 1. I understand the first remainder, but not the rest. Also, how come the loop terminates? Isn't x always going to be greater than 0, therefore continuing indefinitely? Thank you. ``` int x = 1023; while (x > 0) { printf("%d", x% 10); x = x /1...
Note that in C, when both operands of a division have integer type, the division also has an integer type, and the value is the result of divisionrounded toward zero. So in the first iteration, the statementx = x /10;changesxfrom1023to102(not102.3).
I have a simple c program what i want to do is to take first two numbers from string put it in another string which will be only these two numbers and then convert it to int. strlen of hLength is 54... ``` char string[100] = ":50010000214601360121470136007EFE09D21901\n"; char hLength[3]; int length,c; hLength[0] = ...
you missed to put the null character to endhLength, add ``` hLength[2] = 0; ``` you have your output because in your casestringis afterhLength, but this is a random effect of course
I'm trying to make game like "Duke Nukem 3D". I will have many maps in my game and each map will have it'sown(and no more!) data files such as textures, sounds and so on, that's why I need to compress all these data files to one "map" file. So, let's image that I want to test my maps one by one, and after compiling m...
So, I just made my archiver(without compress). If you need it, you can find ithere.
So I want to print the copyright symbol and putchar() just cuts off the the most significant byte of the character which results in an unprintable character. I am using Ubuntu MATE and the encoding I am using is en_US.UTF-8. Now what I know is that the hex value for © is 0xc2a9 and when I try putchar('©' - 0x70) it g...
Theputcharfunction takes anintargument andcasts it to anunsigned charto print it. So you can't pass it a multibyte character. You need to callputchartwice, once for each byte in the codepoint. ``` putchar(0xc2); putchar(0xa9); ```
Hi guys I'm new to C and pointers so I hope you'll forgive me. I have the following code: ``` char *str = NULL; *str = 'a'; printf("My string is :%s\n",str); ``` It compiles but I'm getting a segmentation error everytime. What is the cause of this and what how can I change it so that I can assign 'a' to my string? ...
``` char *str = NULL; ``` The pointer str is not allocated yet. So you can not dereference it. Then you tried to deference by ``` *str = 'a'; ``` The segmentation fault will occur. If you want str with "a" value, you can do this way: ``` char *str = "a"; printf("My string is :%s\n",str); ```
I ran it through an IDE and the remainder values came out 3, 2, 0, 1. I understand the first remainder, but not the rest. Also, how come the loop terminates? Isn't x always going to be greater than 0, therefore continuing indefinitely? Thank you. ``` int x = 1023; while (x > 0) { printf("%d", x% 10); x = x /1...
Note that in C, when both operands of a division have integer type, the division also has an integer type, and the value is the result of divisionrounded toward zero. So in the first iteration, the statementx = x /10;changesxfrom1023to102(not102.3).
I have a simple c program what i want to do is to take first two numbers from string put it in another string which will be only these two numbers and then convert it to int. strlen of hLength is 54... ``` char string[100] = ":50010000214601360121470136007EFE09D21901\n"; char hLength[3]; int length,c; hLength[0] = ...
you missed to put the null character to endhLength, add ``` hLength[2] = 0; ``` you have your output because in your casestringis afterhLength, but this is a random effect of course
I'm trying to make game like "Duke Nukem 3D". I will have many maps in my game and each map will have it'sown(and no more!) data files such as textures, sounds and so on, that's why I need to compress all these data files to one "map" file. So, let's image that I want to test my maps one by one, and after compiling m...
So, I just made my archiver(without compress). If you need it, you can find ithere.
I tried to construct a function that has the reference as a parameter. But the compile gave me a error warning, saying that expected')', I don't know what is the problem.Can't we use reference as parameter in C?The following is the code segment. ``` typedef struct Qnode{ struct Qnode* first; struct Qnode* re...
C doesn't have references. That's a C++ construct. You'll need to change the function to accept a pointer. ``` int init_Queue(Queue *q) { printf("value=%d\n", q->value); return 1; } ```
I wonder what the abbreviationenvpstands for, for example here: ``` int main(int argc, char **argv, char **envp); ``` I also wonder what thevinargvinitially stood for. Was thevfor "value"? Or maybe "vector"?
The meaning is: argvstands forargumentvectorargcforargumentcount, andenvpforenvironmentpointer. We can discuss about the good or bad naming convention, but it's a historic usage that dates back to the beginning of the C language:B.W.KernighanandD.Ritchieused alreadyargcandargvformain()in their first edition ofThe C ...
I'm reading the C Programming Language (chapter 5), and I'm confused by this example: ``` int n, array[SIZE], getint(int *); ``` Why is this function call in here like that? Is this just some tricky example and invalid code?
It's not calling the function; it's declaring its prototype. It's equivalent to: ``` int n; int array[SIZE]; int getint(int*); ```
``` a[b] ``` Is equivalent to*(a + b), so... ``` a[b & c] ``` Where&has a lower operator precedence than+, would this result in*(a + b & c)or*(a + (b & c))?
TheC Standard, § 6.5.2.1,Array Subscriptingsays: The definition of the subscript operator[]is thatE1[E2]is identical to(*((E1)+(E2))) Note the brackets surroundingE2. The latter expression (*(a + (b & c))) is the correct outcome.
I am on a vxworks 6.9 platform. I want to know how many files are in a folder. The file system is DOSFS (FAT). The only way I know how to do this is to simply loop through every file in the folder and count. This gets very expensive the more files in the folder. Is there a more sensible way to do this? Does there exis...
The FAT filesystem does not keep track of the number of files it contains. What it does contain is: A boot sectorA filesystem information sector (on FAT32) including:Last number of known free clustersNumber of the most recently allocated clusterTwo copies of the file allocation tableAn area for the root directory (o...
is it possible to overwrite MFT file table in windows api. When windows is up and ready? I know we can read MFT but I ask about write.
Vista restricted raw access but you can probably still do it if you unmount the volume first. Changes to the file system and to the storage stack to restrict direct disk access and direct volume access in Windows Vista and in Windows Server 2008. I don't know the type of program you are writing but it might fit in t...
I've got a struct to say: ``` struct mystruct { int *myarray; } ``` In my main function, I want to assign to "myarray" the values of a predefined array. ``` int main(){ int array[5] = {1,2,3,4,5}; //how to "assign" array values to myarray ?; } ``` I would like avoid making a cycle of an assignment lik...
``` struct mystruct { int *myarray; } ``` heremyarrayis just a pointer to memory. There is no space reserved there, so your example will fail. You have two options: Just use the array you already have, this assumes the array is not free'd before the structure is free'd:instance->myarray = array;reserve memor...
is it possible to overwrite MFT file table in windows api. When windows is up and ready? I know we can read MFT but I ask about write.
Vista restricted raw access but you can probably still do it if you unmount the volume first. Changes to the file system and to the storage stack to restrict direct disk access and direct volume access in Windows Vista and in Windows Server 2008. I don't know the type of program you are writing but it might fit in t...
I've got a struct to say: ``` struct mystruct { int *myarray; } ``` In my main function, I want to assign to "myarray" the values of a predefined array. ``` int main(){ int array[5] = {1,2,3,4,5}; //how to "assign" array values to myarray ?; } ``` I would like avoid making a cycle of an assignment lik...
``` struct mystruct { int *myarray; } ``` heremyarrayis just a pointer to memory. There is no space reserved there, so your example will fail. You have two options: Just use the array you already have, this assumes the array is not free'd before the structure is free'd:instance->myarray = array;reserve memor...
This question already has answers here:Determine size of dynamically allocated memory in C(15 answers)Closed4 years ago. How can I get the size of a dynamically allocated array of double pointers? (pointer to pointer datatype) ``` int tokencnt=1; tokenv=(char**)malloc(sizeof(char*)); while(tokencnt<11){ tokenv=(ch...
sizeofdoes not work with alloc memory. If youmallocstuff you have to keep track of the size. The reasonsizeofdoes not work, is because it will just give you the size of the pointer not the memory it points to.
Hello Everyone i have one question I Using OPC-UA for client, I have some problem This is Problem code ``` UA_ReadRequest requestPos; UA_ReadRequest_init(&requestPos); UA_ReadValueId idPos; UA_ReadValueId_init(&idPos); idPos.attributeId = UA_ATTRIBUTEID_VALUE; idPos.nodeId = UA_NODEID_STRING(6, (char*)"::AsGlobalPV...
You have created a non-owning string nodeid. The delete members will free the memory used, even though it's not owned resulting in a memory corruption. Replace the UA_NODEID_STRING() with UA_NODEID_STRING_ALLOC().
I'm currently creating a little game, and I need to create a condition. In pseudo-code, it would look like something like this : ``` if (a < x with x included in [b -10; b +10]) { then c = 2 } ``` Is there an easy way to do this ? I know it may not be really clear, so ask me further details if you didn't unde...
``` if(a < x && x >= b-10 && x <= b + 10){ } ```
When I try to compile the following C-code with a nested function: ``` #include <stdio.h> int main() { int five() { return 5; } for (int i = 0; i < 10; i++) { printf("%d ", five()); } return 0; } ``` I obtain the following error:error C2143: syntax error: missing ';' before '{' in C I...
The compiler works "token" by "token". Afterint main() {it sees the tokensint,five,(and)which are part of a declaration of function five (returningintand accepting an unspecified, but fixed, number of arguments). This declaration is completed with the token;but the next available token is{which makes the whole thing i...
I'm writing a program in C that receives two strings as input from the user on the command line. I know that when you use ``` int main(int argc, char *argv[]) ``` it creates a pointer to the array that stores both arguments as argv[1] and argv[2]. Say the user inputs "hello" on the command line, and I want to access...
TL;DR-When in doubt, check the data type. The type forargvischar * [], which decays tochar **. Thus,argv[n]is of typechar *. You can index intoargv[n], likeargv[n][m]to get thecharelements.
I'm currently creating a little game, and I need to create a condition. In pseudo-code, it would look like something like this : ``` if (a < x with x included in [b -10; b +10]) { then c = 2 } ``` Is there an easy way to do this ? I know it may not be really clear, so ask me further details if you didn't unde...
``` if(a < x && x >= b-10 && x <= b + 10){ } ```
I am trying to figure out a way to sort 3 numbers inputted in any given order, into ascending order for a homework assignment. So far I came up with this. ``` if(*p1 > *p3){ *p3 = *p1; } if(*p1 > *p2){ *p2 = *p1; } if(*p2 > *p3){ *p3 = *p2; ...
The idiomatic way to swap two variables is indeed to add atempvariable: ``` void swap(T *a, T *b) { T temp = *a; *a = *b; *b = temp; } ``` Now, to sort three values into ascending order, a full fledged sorting algorithm would indeed be overkill. You can do this just with a few compares andswaps.
I need to overlap a series of png images in order to create a single jpeg file in Erlang/Elixir. I can't find anywhere a way to do this task on the BEAM, so I would love to use Erlang NIFs and writing down some C code using the ImageMagick APIs, but again I can't find any documentation for this task. Is there a way t...
You have three options: Use ImageMagick CLI - easy, slowest, safe (separate process)Write port wrapper using library bindings in your preferedlanguage(C, Perl, LUA, Python, ...) - harder, fast, safe (separate process)Use NIFs - even harder, fastest (if done right!), unsafe (compromise BEAM reliability) Choose accord...
If I use a for loop to find the sum ofnnumbers between0 and nmy runtime isO(n). But if I create a recursive function such as: ``` int sum(int n) { if(n == 0) return 0; return n + sum((n - 1)); } ``` Would my runtime still beO(n)?
Yes, your runtime will still beO(N). Your recursive function will "loop"Ntimes until it hits the base case. However keep in mind that your space complexity is alsoO(N). Your language has to saven + ...before evaluatingsum((n - 1)), creating a stack of recursive calls that isNlong.
I am trying to figure out a way to sort 3 numbers inputted in any given order, into ascending order for a homework assignment. So far I came up with this. ``` if(*p1 > *p3){ *p3 = *p1; } if(*p1 > *p2){ *p2 = *p1; } if(*p2 > *p3){ *p3 = *p2; ...
The idiomatic way to swap two variables is indeed to add atempvariable: ``` void swap(T *a, T *b) { T temp = *a; *a = *b; *b = temp; } ``` Now, to sort three values into ascending order, a full fledged sorting algorithm would indeed be overkill. You can do this just with a few compares andswaps.
I need to overlap a series of png images in order to create a single jpeg file in Erlang/Elixir. I can't find anywhere a way to do this task on the BEAM, so I would love to use Erlang NIFs and writing down some C code using the ImageMagick APIs, but again I can't find any documentation for this task. Is there a way t...
You have three options: Use ImageMagick CLI - easy, slowest, safe (separate process)Write port wrapper using library bindings in your preferedlanguage(C, Perl, LUA, Python, ...) - harder, fast, safe (separate process)Use NIFs - even harder, fastest (if done right!), unsafe (compromise BEAM reliability) Choose accord...
If I use a for loop to find the sum ofnnumbers between0 and nmy runtime isO(n). But if I create a recursive function such as: ``` int sum(int n) { if(n == 0) return 0; return n + sum((n - 1)); } ``` Would my runtime still beO(n)?
Yes, your runtime will still beO(N). Your recursive function will "loop"Ntimes until it hits the base case. However keep in mind that your space complexity is alsoO(N). Your language has to saven + ...before evaluatingsum((n - 1)), creating a stack of recursive calls that isNlong.
I have a 1D arrayA[3]& a 2D arrayB[4][3]. I want to assign the arrayA[3]to one of the rows of arrayB[4][3]. How to do it correctly? ``` #include<stdio.h> void main() { int A[3]={1,2,3}; int B[4][3]={0}; int row_select=2; B[row_select][] = A; } ``` But this assignment doesn't work. I don't want to assig...
memcpycould be a good option, although it's very likely it uses a loop internally. ``` memcpy(B[row_select], A, sizeof(A)); ```
I created an array of strings like this: ``` char header[4][100]; ``` I am then trying to access the first char of the 3rd element in the string array and compare it. I tried: ``` strcmp(header[2][0], "/"); ``` Gives me an error of : comparison between pointer and integer and also: ``` const char* tempheader2 ...
header[2][0]is a singlechar, not achar *likestrcmpexpects. To compare single characters, just use the regular==operator and single quotes: ``` if(header[2][0] == '/') ```
Say I havechar* b = "2 3, 32 3, 6 8, 9 10"and a methodrandMethod(int x, int y) How would i keep going through the string putting every 2 int as as inputs for randMethod(x, y)? So it would end up being something like: ``` randMethod(2, 3); randMethod(32, 3); randMethod(6, 8); randMethod(9, 10); ```
Something like that : ``` #include <stdio.h> #include <string.h> void randMethod(int x, int y) { printf("%d %d\n", x, y); } int main() { const char * b = "2 3, 32 3, 6 8, 9 10"; int x, y; while (sscanf(b, "%d %d", &x, &y) == 2) { randMethod(x, y); b = strchr(b, ','); if (b == NULL) break;...
I am learning C and am downloading a GitHub repository through code. This downloads the code to the current working directory (essentially where the C app is executed from). Is there a way to set the download directory? Meaning always always have the file download to C:\Data\ProdData\ ``` #include <stdlib.h> int ...
You should just add it to your command: ``` #include <stdlib.h> int main(void) { return system("git clone https://github.com/manleyManlious22/TestData C:\\Data\\ProdData\\"); } ``` Also, I'm not on windows so I can't check the path, but it does work on linux. With thesystemcall, you are running a command as if y...
I don't understand the outcome of the following code: ``` unsigned char p = 170; p = (~p) >> 4 & 255; ``` The Result is: 245 and I don't understand why. First the (~p) will applied what makes 10101010 to 01010101 This is a positive number so >> 4 would lead to 00000101 in my understanding. But it seems to be ...
When used in an expression, an integer narrower thanintis generally converted to anint. So, using 16-bitintfor illustration, in(~p) >> 4 & 255: pis 101010102.This is converted to anint, producing 00000000101010102.~pproduces 11111111010101012.(~p) >> 4may produce 11111111111101012. (Right-shift of negative values is ...
Currently Apple provides functions to access data in font tables, likeCTFontCopyTable. I'm using it to parse information (kerning, etc) out of a font when available. Is there any similar way of pulling the same data on Windows per font? I can see a lot ofdocumentationon the windows side when it comes to these font ta...
GetFontDatawill get the raw table data, but as other suggestions advise, you will probably want to use the system-provided text layout methods rather than trying to roll your own.
Does the variable declaration in java also allocate a space to the variable? For example: String i; I cannot useiuntil I assign a value to it. But, do I already have memory foriallocated on stack after this line? Or, does it come into existence only when I assign it some value? For example in C, this code would de...
Saying ``` String s; ``` in Java is analogous to saying ``` char* s; ``` in C. Space is allocated on the stack for apointer, but not the actual contents of theString(which are of course not known at this time)
Its my exams next week and we were given a bank of questions out of which we need to provide valid solutions with explanations of the given code. I am not able to understand this code. Attaching the code. ``` #include <stdio.h> int main() { int a = 800, b = 100, c; if(!a >= 400) ...
``` if(!a >= 400) ``` Since logical not!has higher precedence, this is equivalent to(!a) >= 400. The left side evaluates to0(because a is non-zero, so!ais0) making the entire expression is false. Also note the code indentation isn't significant to the compiler.
Say I havechar* b = "2 3, 32 3, 6 8, 9 10"and a methodrandMethod(int x, int y) How would i keep going through the string putting every 2 int as as inputs for randMethod(x, y)? So it would end up being something like: ``` randMethod(2, 3); randMethod(32, 3); randMethod(6, 8); randMethod(9, 10); ```
Something like that : ``` #include <stdio.h> #include <string.h> void randMethod(int x, int y) { printf("%d %d\n", x, y); } int main() { const char * b = "2 3, 32 3, 6 8, 9 10"; int x, y; while (sscanf(b, "%d %d", &x, &y) == 2) { randMethod(x, y); b = strchr(b, ','); if (b == NULL) break;...
I am learning C and am downloading a GitHub repository through code. This downloads the code to the current working directory (essentially where the C app is executed from). Is there a way to set the download directory? Meaning always always have the file download to C:\Data\ProdData\ ``` #include <stdlib.h> int ...
You should just add it to your command: ``` #include <stdlib.h> int main(void) { return system("git clone https://github.com/manleyManlious22/TestData C:\\Data\\ProdData\\"); } ``` Also, I'm not on windows so I can't check the path, but it does work on linux. With thesystemcall, you are running a command as if y...
I don't understand the outcome of the following code: ``` unsigned char p = 170; p = (~p) >> 4 & 255; ``` The Result is: 245 and I don't understand why. First the (~p) will applied what makes 10101010 to 01010101 This is a positive number so >> 4 would lead to 00000101 in my understanding. But it seems to be ...
When used in an expression, an integer narrower thanintis generally converted to anint. So, using 16-bitintfor illustration, in(~p) >> 4 & 255: pis 101010102.This is converted to anint, producing 00000000101010102.~pproduces 11111111010101012.(~p) >> 4may produce 11111111111101012. (Right-shift of negative values is ...
Currently Apple provides functions to access data in font tables, likeCTFontCopyTable. I'm using it to parse information (kerning, etc) out of a font when available. Is there any similar way of pulling the same data on Windows per font? I can see a lot ofdocumentationon the windows side when it comes to these font ta...
GetFontDatawill get the raw table data, but as other suggestions advise, you will probably want to use the system-provided text layout methods rather than trying to roll your own.
Does the variable declaration in java also allocate a space to the variable? For example: String i; I cannot useiuntil I assign a value to it. But, do I already have memory foriallocated on stack after this line? Or, does it come into existence only when I assign it some value? For example in C, this code would de...
Saying ``` String s; ``` in Java is analogous to saying ``` char* s; ``` in C. Space is allocated on the stack for apointer, but not the actual contents of theString(which are of course not known at this time)
Its my exams next week and we were given a bank of questions out of which we need to provide valid solutions with explanations of the given code. I am not able to understand this code. Attaching the code. ``` #include <stdio.h> int main() { int a = 800, b = 100, c; if(!a >= 400) ...
``` if(!a >= 400) ``` Since logical not!has higher precedence, this is equivalent to(!a) >= 400. The left side evaluates to0(because a is non-zero, so!ais0) making the entire expression is false. Also note the code indentation isn't significant to the compiler.
Does the variable declaration in java also allocate a space to the variable? For example: String i; I cannot useiuntil I assign a value to it. But, do I already have memory foriallocated on stack after this line? Or, does it come into existence only when I assign it some value? For example in C, this code would de...
Saying ``` String s; ``` in Java is analogous to saying ``` char* s; ``` in C. Space is allocated on the stack for apointer, but not the actual contents of theString(which are of course not known at this time)
Its my exams next week and we were given a bank of questions out of which we need to provide valid solutions with explanations of the given code. I am not able to understand this code. Attaching the code. ``` #include <stdio.h> int main() { int a = 800, b = 100, c; if(!a >= 400) ...
``` if(!a >= 400) ``` Since logical not!has higher precedence, this is equivalent to(!a) >= 400. The left side evaluates to0(because a is non-zero, so!ais0) making the entire expression is false. Also note the code indentation isn't significant to the compiler.
Is it bad practice when I assign new pointer to pointer without free? ``` char **arr = malloc(sizeof(*arr)*9); ... ... arr[5] = strdup("sys"); arr[6] = strdup("var"); arr[7] = strdup("home"); arr[8] = NULL; arr[5] = arr[6]; arr[6] = arr[7]; arr[7] = NULL; ```
Yes. Since that pointer you reassigned (e.g. arr[5]) is no longer accessible it's memory can't be free'd and it is a memory leak.
Checking the changes in recent OpenSSL releases, I now noticed that the HMAC_CTX structuremustbe allocated on the heap now. The headers only forward-declare it (in ossl_typ.h). I wonder what the idea behind is. Given that heap allocated memory creates overhead, they must have a good reason for making the library slow...
I've seen a lot of the OpenSSL structures going the same way. I would think that it's because the implementers of OpenSSL want to "hide" the implementation state away from the users of the library. That way the user can't "mess" with it in ways that the implementers don't want you to. It also means that the impleme...
I get this warning if I try to run the code: warning: expression result unused [-Wunused-value] ``` !!(((x&0xff) | ((x >> 8) & 0xff) | ((x >> 16) & 0xff) | ((x >> 24) & 0xff)) & 0xaa); return (x & 0xaaaaaaaa) != 0; ``` The code works fine. I just want to know why the warning is being generated.
This statement: ``` !!(((x&0xff) | ((x >> 8) & 0xff) | ((x >> 16) & 0xff) | ((x >> 24) & 0xff)) & 0xaa); ``` has no effect because you don't assign the result and there are no side-effects either.
I would like to pass a pointer as an argument into a function that normalizes the vector pointer that was passed as an argument. Here are the functions: ``` float norm(Vector *v) { float len; len = sqrt(pow(v->x, 2.0) + pow(v->y, 2.0) + pow(v->z, 2.0)); return len; } Vector normalize(Vector *vec){ Vec...
That is because yourfloat normvariable shadows thenorm()function.Name one of them something else. Also,vecis already a pointer, no need to take its address (&vec) when you pass it tonorm()
From thisvideo on youtube by Kees Cook from linux.conf.au 2019he mentionsstrscpyas being preferred but generally doing what users want (lessNUL-padding). However, he doesn't say what defines this (spec or header), Slide from the video, I can't findstrscpy()withman ``` $ for i in strcpy strlcpy strscpy; do man -w...
It's in thelinux source, not in the standard library.Online man page
The program is supposed to calculate the average of numbers entered until -1, but my code calculates the average with -1 included. How can I exclude -1 from being calculated to the sum and average? ``` #include <stdio.h> #include <stdlib.h> int main() { int n; int sum = 0, i = 0; float av; do { scanf("%...
In your solution, your code would read thenwhich is equal to-1and add, and then verify which was causing this problem. You could do it like this: ``` do { scanf("%d", &n); if (n != -1) sum += n; i++; } while (n != -1); ``` Or even better, like this: ``` while (1) { scanf("%d", &n); if (n == -1) break; ...
This question already has answers here:printf("%p") and casting to (void *)(7 answers)What does void* mean and how to use it?(10 answers)Closed4 years ago. ``` char x = 'G'; char *p = &x; printf ("Address of x: %p\n", p); printf ("Address of x: %p\n", (void*)p); ``` Can someone tell me what exactly(void*)pmeans? I...
The C standard says this about the%pformat specifier forprintffamily functions (§ 7.21.6.2, paragraph 12) The corresponding argument shall be a pointer to a pointer to void. Pointers to different types may differ in their internal representation, except forvoid *andchar *pointers, which are guaranteed to be the same...
If I have a string as follows: "Dragonballs are cool." but I want to change the spaces into multiple lines: "---" So this would be the end result: Dragonballs---are---cool. How would i do it? Is a loop necessary (I know how to replace single characters with another single character), or is there another way to it?
There are several ways it can be done. One way is to tokenize the string first, to find out where the spaces are, for example by usingstrtok. Then copy the different sub strings (words) one by one into a new string (character array), for example withstrcat. For each string you copy, also copy a string"---". The alte...
Usually we open file in this way ``` FILE *student_file; student_file = fopen("five_students", "rb"); ``` Now I have a function with an image pointer as argument. I want to open the image file and read the content inside. I tried to open it as following, but it doesn't work. How can I fix it? ``` void read_metadat...
If you already have the parameterimageopened when you callread_metadata(i.e. if an earlier call tofopensucceeded in the calling code), you don't need to callfopenon it again. It is already open. Also, that code shouldn't even be compiling, sincefopentakes achar *string as its first argument, not aFILE. Just use the ...
Is(*pointer)->namethe same aspointer->nameor(*pointer).name?
No. (*pointer)->namesays “Get the thing thatpointerpoints to. Get the structure that it points to and get thenamemember from it.” For this to work,pointermust be a pointer to a pointer to a structure. For example, it could have been declared asstruct foo **pointer. pointer->namesays “Get the structure thatpointerpoi...
Usually we open file in this way ``` FILE *student_file; student_file = fopen("five_students", "rb"); ``` Now I have a function with an image pointer as argument. I want to open the image file and read the content inside. I tried to open it as following, but it doesn't work. How can I fix it? ``` void read_metadat...
If you already have the parameterimageopened when you callread_metadata(i.e. if an earlier call tofopensucceeded in the calling code), you don't need to callfopenon it again. It is already open. Also, that code shouldn't even be compiling, sincefopentakes achar *string as its first argument, not aFILE. Just use the ...
Is(*pointer)->namethe same aspointer->nameor(*pointer).name?
No. (*pointer)->namesays “Get the thing thatpointerpoints to. Get the structure that it points to and get thenamemember from it.” For this to work,pointermust be a pointer to a pointer to a structure. For example, it could have been declared asstruct foo **pointer. pointer->namesays “Get the structure thatpointerpoi...
I just did this ``` printf( (n==0) ? " %d" : " %3d", n ); ``` but is there a conditional format descriptor? So, it would mean something like"if this is very short use such and such padding, but, if this is longer use such and such padding." Can do?
There's no conditional, but you can use * to specify the width in the arguments. e.g.: ``` printf(" %*d", (n==0)?1:3, n); ```
In a Windows application, I have aGetFirmwareEnvironmentVariableAfunction to read a firmware environment variable. Is there any way to write something in this variable in uefi driver and read from it later in Windows?
The function to set an NVRAM variable is called SetVariable() and is available to UEFI drivers via EFI_RUNTIME_SERVICES table. To know more about it's interface and usage, read chapter 7.2 Variable Services of theUEFI 2.6 specification.
This question already has answers here:Why Do We have unsigned and signed int type in C?(4 answers)Closed4 years ago. I am studying c language and there are two different integer types, signed/unsigned. Signed integers can present both positive and negative numbers. Why do we need unsigned integers then?
One word answer is "range"! When you declare a signed integer, it takes 4 bytes/ 32 bits memory (on a 32 bit system). Out of those 32 bits, 1 bit is for sign and other 31 bits represent number. Means you can represent any number between -2,147,483,648 to 2,147,483,647 i.e. 2^31. What if you want to use 2,147,483,64...
Keep getting the following warning: “too many arguments for format” for the printf function below. Do not know what is causing this warning. I provided the type values of pos and str_pos along with the printf function. I excluded all other code as I did not think it was necessary for this question. ``` int pos; cha...
The corect way of writing thatprintf()statement would be ``` printf("The character at index %d is %c\n", pos, str_pos); ``` You need to change “to"s.Use the format string correctly, including the newline.useposandstring_posas the argument (not part of the format string itself), in the variadic list. Also, I presum...
Is there a function that checks whether asockaddr *namedsptrpoints to an ipv4 or ipv6 address? For example I have the code below, how can I add onto it to get whether the address is ipv4 or ipv6, can I usegetaddrinfo()? ``` struct sockaddr *sptr; struct sockaddr_in *ipv4_ptr; ```
You can test thesa_familymember: ``` switch (sptr->sa_family) { case AF_INET: /* IPv4 */ break; case AF_INET6: /* IPv6 */ break; default: /* Something else */ } ``` If thesa_familymember isAF_INET, that indicates an IPv4 address and the socket address is actually astruct sockaddr_in...
I was looking in my C textbook and inside there was a page where the prompt told me to translate a polynomial into C code. We have not discussed exponent operators yet and are specifically instructed not to use them at this point and find another way with basic operators. The polynomial goes as such:5x^(2)+3x-2. How ...
Note thatax^2 + bx + ccan be written as ``` c + x*(b + x*(a)) ``` This can easily be extended to any order of polynomial.
I've got the following situation: ``` #include <stdio.h> int main(void) { int first = 0x08; printf("%d\n", first & 0b10); printf("%d\n", first & 0b10 == 0); if (first & 0b10 == 0) { printf("SET"); } else { printf("NOT"); } return 0; } ``` Two0s print out, followed byNOT. What is happening h...
This is an issue of operator precedence. The bitwise AND operator&has lower precedence than the equality operator==. So this: ``` first & 0b10 == 0 ``` Is the same as: ``` first & (0b10 == 0) ``` Which is not what you want. It compares0b10for equality with 0, which is false. Thenfirst & 0is evaluated which is ...
``` int **p = NULL; p = (int **) malloc(sizeof (int *) * 3); for (int i = 0; i < 3; i++) p[i] = (int *) malloc(sizeof (int) * 4); ``` In this code a double pointer is used as 2D array. My questions are if i want to insert 1 at every position.if i want to insert value 2 at specific location How can i do this?
Just using index operator as 2D array. if you want to insert 1 at every position. ``` for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) p[i][j] = 1; } ``` if you want to insert value 2 at specific location at row i, column j ``` p[i][j] = 2; ```
I am new to programming world, I want to convert two bytes into a word. So basically, I have a Byte array where index 0 isBuffer[0]=08and index 1 isBuffer[1]=06I want to create a word from these two bytes where wordETHType to be 0x0806
You would use bitwise operators and bit shifting. ``` uint16_t result = ((uint16_t)Buffer[0] << 8) | Buffer[1]; ``` This does the following: The value ofBuffer[0]is shifted 8 bits to the left. That gives you 0x0800A bitwise OR is performed between the prior value and the value ofBuffer[1]. This sets the low order...
It prints the wrong number/random number. What I want is to print numbers higher than75. ``` int main() { int array[5]; int num, i; for (i = 1; i <= 5; i++) { printf("Input Num %d : ", i); scanf("%d", &num); } if (num >= 75) { printf("%d\n", array[i]); } return 0; ...
Please use if within "for" loop. and please change "array" to "arr" or another name. The array will be a keyword in c++ sometime. should not use "array" to name a variable. here is my solution: ``` int main() { int arr[5]; int num, i; for (i = 1; i <= 5; i++) { printf("Input Num %d : ", i); ...
Are there any different between those both (ptrfun1andptrfun2)? ``` int fun(int num){ num *= num; return num; } int main(){ int (*ptrfun1)(int num) = fun; int (*ptrfun2)(int num) = &fun; ``` Does both point to the functionfun?
There is no difference at all. A functiondecaysto a function pointer.
In the mentioned code, how to get the updated value in the statement ofprintf("value : %d\n",a); ``` #include <stdio.h> #include <stdbool.h> #define TRUE 1; #define FALSE 0; void printbool(bool a); int main() { bool a = FALSE; printf("Hello, World!\n"); printbool(a); printf("value : %d\n",a); re...
Try this: ``` void printbool(bool *a) { *a = TRUE; } ``` In main, call function like this:printbool(&a);
``` char s[100]={0}; fgets(s, sizeof(s), stdin); ``` In the context of the code above, what is the difference between these three? printf("%s",s);printf(s);fputs(s,stdout);
printf("%s",s);correct but printf is a very heavy function and most compilers will actually replace it with puts in the compiler code if the format string ends with '\n'printf(s); very dangerous as the format string may contain%and then it will expect another parameters. If it happens it is UB. It also makes your code...
I have the following function: ``` BIGNUM * multiplyWithInt(BIGNUM *bn, int val){ //Logic Here } ``` What I try to do is to calculate the multiplicationbn*val. For Multiplication according to documentation (given from commandman bn) is the following: ``` int BN_mul(BIGNUM *r, BIGNUM *a, BIGNUM *b, BN_CTX *ctx); `...
The function you're looking for isBN_set_word. This assigns anunsigned longvalue to aBIGNUM. ``` BIGNUM *bn_val = BN_new(); BN_set_word(bn_val , val); ``` You can then passbn_valandbntoBN_mul.
I am Getting garbage values By Running this code ``` #include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> int main() { int fd,k; fd=open("hello.txt",O_WRONLY|O_CREAT|O_TRUNC); char a[1000]; scanf(" %s",a); k=write(fd,a,sizeof(a)); close(fd); } ``` why I am gett...
Becausesizeof()returns the memory size ofawhich is 1000. ais created on the stack and its contents is undefined. After thescanf()only the first part of this stack garbage is overwritten. You need to dowrite(fd, a, strlen(a)), or withstrlen(a) + 1if you want to also write the C string delimiter\0, which is added to t...
``` #include <stdio.h> void testFunction(int *a){ printf("In a should be 5: %d", *a); *a = 0; printf("In a should be 0: %d", *a); test2Function(&a); } void test2Function(int *a){ printf("In F2 a should be 0: %d", *a); *a = 2; printf("In F2 a should be 2: %d", *a); } int main(){ int ...
Instead of: ``` test2Function(&a); ``` Do: ``` test2Function(a); ``` Because you simply want to copy the pointer you already have, not take the address of the pointer itself.
It prints the wrong number/random number. What I want is to print numbers higher than75. ``` int main() { int array[5]; int num, i; for (i = 1; i <= 5; i++) { printf("Input Num %d : ", i); scanf("%d", &num); } if (num >= 75) { printf("%d\n", array[i]); } return 0; ...
Please use if within "for" loop. and please change "array" to "arr" or another name. The array will be a keyword in c++ sometime. should not use "array" to name a variable. here is my solution: ``` int main() { int arr[5]; int num, i; for (i = 1; i <= 5; i++) { printf("Input Num %d : ", i); ...
Are there any different between those both (ptrfun1andptrfun2)? ``` int fun(int num){ num *= num; return num; } int main(){ int (*ptrfun1)(int num) = fun; int (*ptrfun2)(int num) = &fun; ``` Does both point to the functionfun?
There is no difference at all. A functiondecaysto a function pointer.
In the mentioned code, how to get the updated value in the statement ofprintf("value : %d\n",a); ``` #include <stdio.h> #include <stdbool.h> #define TRUE 1; #define FALSE 0; void printbool(bool a); int main() { bool a = FALSE; printf("Hello, World!\n"); printbool(a); printf("value : %d\n",a); re...
Try this: ``` void printbool(bool *a) { *a = TRUE; } ``` In main, call function like this:printbool(&a);
``` char s[100]={0}; fgets(s, sizeof(s), stdin); ``` In the context of the code above, what is the difference between these three? printf("%s",s);printf(s);fputs(s,stdout);
printf("%s",s);correct but printf is a very heavy function and most compilers will actually replace it with puts in the compiler code if the format string ends with '\n'printf(s); very dangerous as the format string may contain%and then it will expect another parameters. If it happens it is UB. It also makes your code...
I have the following function: ``` BIGNUM * multiplyWithInt(BIGNUM *bn, int val){ //Logic Here } ``` What I try to do is to calculate the multiplicationbn*val. For Multiplication according to documentation (given from commandman bn) is the following: ``` int BN_mul(BIGNUM *r, BIGNUM *a, BIGNUM *b, BN_CTX *ctx); `...
The function you're looking for isBN_set_word. This assigns anunsigned longvalue to aBIGNUM. ``` BIGNUM *bn_val = BN_new(); BN_set_word(bn_val , val); ``` You can then passbn_valandbntoBN_mul.
I am Getting garbage values By Running this code ``` #include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> int main() { int fd,k; fd=open("hello.txt",O_WRONLY|O_CREAT|O_TRUNC); char a[1000]; scanf(" %s",a); k=write(fd,a,sizeof(a)); close(fd); } ``` why I am gett...
Becausesizeof()returns the memory size ofawhich is 1000. ais created on the stack and its contents is undefined. After thescanf()only the first part of this stack garbage is overwritten. You need to dowrite(fd, a, strlen(a)), or withstrlen(a) + 1if you want to also write the C string delimiter\0, which is added to t...
``` #include <stdio.h> void testFunction(int *a){ printf("In a should be 5: %d", *a); *a = 0; printf("In a should be 0: %d", *a); test2Function(&a); } void test2Function(int *a){ printf("In F2 a should be 0: %d", *a); *a = 2; printf("In F2 a should be 2: %d", *a); } int main(){ int ...
Instead of: ``` test2Function(&a); ``` Do: ``` test2Function(a); ``` Because you simply want to copy the pointer you already have, not take the address of the pointer itself.
I've just started to learn C programming. When coming to the String, I get confused with the function 'strcpy'. I tried switching places of first argument and the second argument. When I run the program, it just shows a 'S'. What does that mean? ``` char s2[ ]= "Hello"; char s1[10]; strcpy(s2, s1); printf("Source str...
Based on theprintfstatements, you have the arguments tostrcpymixed up. As it is now, you're copyings1tos2. The arrays1is uninitialized however, so the values it contains areindeterminate. To copys2tos1, switch the parameters: ``` strcpy(s1, s2); ``` If you leave it as is, you need to explicitly sets1to an empty s...
What is the specifier%[^s]used for? sis a variable. In which cases can I use this specifier?
The%[format specifier toscanfwill match a sequence of characters matching those that are listed between[and]. If the first character is^, then it matches charactersexcludingthose characters. In your case%[^s]means "match any character besides the characters's'.sisnota variable in this case.
I don't fully understand how the "-" operator affects the following code: ``` #define COMP(x) ((x) & -(x)) unsigned short a = 0xA55A; unsigned short b = 0x0400; ``` Could someone explain what COMP(a) and COMP(b) are and how they are calculated?
(x) & -(x)is equal to the lowest bit set inxwhen using 2's complement for representing binary numbers. This meansCOMP(a) == 0x0002;andCOMP(b) == 0x0400;
I never really understood when happens what when it comes to casting. I assume that implicit casting happens at compile time (correct me if I'm wrong), but what about this: ``` int i = 0; double d = sqrt((double)i); ``` Will this happen at compile time/run time?
It depends on optimization and architecture. For example, GCC with-O3will omit the call tosqrtaltogether for some values, as seenhere. If the variable is not known at compile-time (i.e. if it is read from a file or from user input), then there's no way around actually callingsqrtwith the double value ofi. On x86 this...
I'm trying to use valgrind with clion in my windows machine. I've gone through the steps ofsetting up WSLandvalgrindon windows. Although when I try to 'run with valgrind memcheck' in my 'UnixAssembler' project I get the following error: Error running 'UnixAssembler': File not found: /cygdrive/c/Users/natan/Desktop/U...
Solved:- Go toFile -> Settings -> Build, Execution, Deployment- Remove any Toolchains other than WSL (making WSL the default will probably work as well)- Profit
I wrote the following code: ``` char arrayD[] = "asdf"; char *arraypointer = &arrayD; while(*arraypointer != '\0'){ printf("%s \n", arraypointer+1); arraypointer++; } ``` I tried %d %c to print each character. However, with %c I get "? ? ? ?", with %s I get "sdf sd f ". etc. What am I missing here?
You're printing pointer addresses, instead of what the pointer is pointing to. Also arrayD is the address, you don't need &arrayD. Here is a complete working sample: ``` #include <stdio.h> int main() { char arrayD[] = "asdf"; char *arraypointer = arrayD; while(*arraypointer != '\0'){ printf("%c \n...
For some reason the double pointer reference of the first parameters stays always 0, aldough it seems correct for the second parameter. What am I doing wrong? Thanks. ``` unsigned short GetData(unsigned char **pbAdr1, unsigned char **pbAdr2) { printf("Data1: %x", par); //displays 6957f0 ==> OK *pbAdr1 = (unsi...
*pbAdr1is a pointer. You are providing a pointer to the%xargument forprintfwhich is expectingunsigned intand isundefined behaviour. The code might "work" if the sizeof of a pointer is the same as the size of anintbut not if they are different. I suggest you use the proper format specifer ``` printf("Data1: %p", (voi...
I have the following macro: ``` #define F(Args, ...) \ // macro definition # F(()) // looks like usage? #undef F ``` What does the line containing only#mean? IsF(())a usage of the macro?
Technically, that's not part of the macro (no continuation line before it). It's a directive that comes after the#definedirective. #on its own line is called anull directiveand it does nothing (as good as a comment). It's no longer practically useful (except as a visual marker) but in prehistoric C, the preprocessor...
I wrote a little tool to display CAN messages based on SocketCAN. Trying to compile it in Cygwin results in an error indicating that gcc can't find the mentioned header files. In which directory or package are these files?
Have you thought to look for hint on the cygwin Website ? The search feature is at:https://cygwin.com/packages/ However I doubt that cygwin posses such low level functionality ``` $ cygcheck -p can/raw.h Found 0 matches for can/raw.h ``` and you need to use Linuxhttps://github.com/linux-can/can-utils
``` struct node { int data; struct node *next; }; int main() { struct node *head = malloc(sizeof(struct node)); struct node *current = head; ... }; ``` Though this piece of code can run without any warning or error, Valgrind will give some messages sayingCondition...
You need to intialize the data and next pointer with head. I mean ``` head->data = 0; head->next = NULL; ``` It will pass Valgrind check
I am programming a module on a microcontoller for interfacing it's EEPROM to receive some user data from there. Since you can not overwrite the EEPROM easily I want to return aconstpointer toconstdata. Now my functions prototype looks like this: const struct userData const* getEEPROMDataAtIndex(uint32_t uidIndex) w...
You have declared your struct const twice. Since it doesn't make sense to make the pointer const in a return type, just remove one of the const declarations. If you wanted to make the pointer const (which doesn't really make sense in a return type) you would put const after the asterisk.
I'd like to look at the source code Apache uses to process .htaccess files. I've downloaded and grepped the Apache source files with no luck.
I'm suspicious of your ability to grep.. I just downloaded the httpd source and it mentionshtaccesseverywhere. Why not start by looking at the functionap_parse_htaccessdefined inserver/config.c.
This question already has answers here:Why should we typedef a struct so often in C?(15 answers)Closed8 months ago. I have seen this expression in the code of other developer and I cannot get the meaning of it, the code line is: ``` typedef struct _Space Space; ``` So, for the syntax I reckon that_Spaceis a kind of...
struct _Spacerefers to a definition of astruct _Spaceelsewhere. Thetypedef ... Spacemeans you can refer to astruct _Spaceas simplySpace, saving you some typing. For example, consider the difference in brevity and clarity between ``` struct _Space mySpace; // Oh god! memories ``` vs ``` Space mySpace; ```
Let's assume we have 2 programs written in C, one program allocates memory with malloc and launches the second program passing the address of allocated memory and size as arguments. Now the question, is it possible for the second program to cast the first argument to a pointer and read/write to that memory. Why, why ...
No, because on modern operating systems processes running in user mode seeVirtual Memory. The same virtual address will translate to a different physical address or page file location between processes. Fortunately, most operating systems do have APIs that allow for inter-process communication, so you can research th...
I've got an array of unsigned chars that I'd like to output to a file using the C file I/O. What's a good way to do that? Preferably for now, I'd like to output just one unsigned char. My array of unsigned chars is also non-zero terminated, since the data is coming in binary.
I'd suggest to use functionfwriteto write binary data to a file; obviously the solution works for arrays ofSIZE==1as well: ``` int main() { #define SIZE 10 unsigned char a[SIZE] = {1, 2, 3, 4, 5, 0, 1, 2, 3, 4 }; FILE *f1 = fopen("file.bin", "wb"); if (f1) { size_t r1 = fwrite(a, sizeof a[0], SIZ...
I'm doing a homework assignment in C and I've run into a little trouble. After calculating two values, I have to be able to print the highest of two valueswithoutusing logical operators, relational operators, or selection constructs. I've already used calculations that determine the larger of the two values, but I d...
I would use the functionfmax. It takes doubles as arguments, so you may have to cast your numbers into doubles.
I need a way to implement a doubly linked list using only an array and no pointers in C. There's is a mention of this in Thomas Cormen but I can't think of a way to actually implement it.
Instead of using pointers which, in C, are usually numbers that index into the address space, use integer indexes into your array as references to the previous and next members e.g. ``` struct Element { int next; int prev; // Any data you want for this element in the list }; struct Element array[MAX_EL...
how do I perform a signed right shift in c? like -25 >> 3. I tried like this: 10011001 >> 3 == 00010011 But the result is -4.
According to the standard 6.5.7p5 The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 /2E2. If E1 has a signed type and a negative value, the resulting value is ...