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 gives me 9 which has the hex value of 0x39 add 0x70 to it and you'll get 0xa9 which is the least significant byte of 0xc2a9
```
#include <stdio.h>
main()
{
printf("©\n");
putchar('©');
putchar('\n');
}
```
I expect the output to be:
```
©
©
```
rather than:
```
©
�
```
|
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?
Thanks in advance!
|
```
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 /10;
}
```
|
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] = string[1];
hLength[1] = string[2];
printf("%s", hLength);
system("pause");
return 0;
```
Output now is "50:50010000214601360121470136007EFE09D21901"But i want only "50"And dont know where is problem.
|
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 my code I want to test my first map with her textures and sounds, And when I type in my command line something like this: ./game_name "mymap.rce" or ./game_name "mymap.zip" my game must start with map what I typed and this map must have textures and sounds which I compressed with her.
You can download demohere.
To run demo you can type this for example: ./rce demo1.rce
|
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 gives me 9 which has the hex value of 0x39 add 0x70 to it and you'll get 0xa9 which is the least significant byte of 0xc2a9
```
#include <stdio.h>
main()
{
printf("©\n");
putchar('©');
putchar('\n');
}
```
I expect the output to be:
```
©
©
```
rather than:
```
©
�
```
|
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?
Thanks in advance!
|
```
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 /10;
}
```
|
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] = string[1];
hLength[1] = string[2];
printf("%s", hLength);
system("pause");
return 0;
```
Output now is "50:50010000214601360121470136007EFE09D21901"But i want only "50"And dont know where is problem.
|
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 my code I want to test my first map with her textures and sounds, And when I type in my command line something like this: ./game_name "mymap.rce" or ./game_name "mymap.zip" my game must start with map what I typed and this map must have textures and sounds which I compressed with her.
You can download demohere.
To run demo you can type this for example: ./rce demo1.rce
|
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* rear;
int value;
}Queue;
int init_Queue(Queue &q) //expected')' as the compiler warned me.
{
return 1;
}
```
Should I use a pointer instead of a reference as a parameter??
|
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 Programming languagein 1978.
Theenvpwas addedlater from the UNIX development and is an alternative for using theenvironpointer. I found a reference to it in a book from 1986, but it's certainly even older. It doesn't need a count, because it's null terminated. Note that it isnot portableand therefore the use ofgetenv()should be preferred.
|
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 exist some internal database or count of all files in a folder?
|
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 (on FAT12 and FAT16)Data clusters
You'll need to walk the directory tree to get a count.
|
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 this category:
Backup programs must unmount the volume before they write to the volume. Otherwise, the program writes will collide with file system writes. Such collisions will result in corruption or in system instability.
Writing to a live volume might be possible if you jump trough all their hoops but the risk of corruption is probably too high, you might want to investigateobscureand/or undocumented NTFS IO control codes instead.
|
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 like :
```
struct mystruct str = malloc(sizeof(mystruct));
for(int i = 0;i<size_of_array;i++){
str->myarray[i] = array[i];
}
```
is this possible?
|
```
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 memory and memcpy the datainstance->myarray = malloc(sizeof(int) * 5);
memcpy(instance->myarray, array, sizeof(int) * 5);
|
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 this category:
Backup programs must unmount the volume before they write to the volume. Otherwise, the program writes will collide with file system writes. Such collisions will result in corruption or in system instability.
Writing to a live volume might be possible if you jump trough all their hoops but the risk of corruption is probably too high, you might want to investigateobscureand/or undocumented NTFS IO control codes instead.
|
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 like :
```
struct mystruct str = malloc(sizeof(mystruct));
for(int i = 0;i<size_of_array;i++){
str->myarray[i] = array[i];
}
```
is this possible?
|
```
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 memory and memcpy the datainstance->myarray = malloc(sizeof(int) * 5);
memcpy(instance->myarray, array, sizeof(int) * 5);
|
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=(char**)realloc(tokenv,(tokencnt++)*sizeof(char*));
}
printf(*the size of tokenv*);
```
|
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:gMotionPos");
requestPos.nodesToRead = &idPos;
requestPos.nodesToReadSize = 1;
UA_ReadResponse responsePos = UA_Client_Service_read(client, requestPos);
UA_ReadRequest_deleteMembers(&requestPos);
```
I want to clearUA_ReadRequest requestPos;, so I useUA_ReadRequest_deleteMembers(&requestPos);, but compiler said: "****.exe caused a breakpoint. Occur ". I can't understand this error.
|
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 understand.
|
```
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 am using Visual Studio Community 2017 and its developer command line, so my compiler iscl.
When I compile the program withgcc, I get no error, so I suspect it's related to the compiler, but how?
|
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 invalid syntax.
TLDR: nested functions are illegal in C.
|
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 the individual characters in "hello", how can I do so if argv[1] gives me the whole string rather than individual characters?
|
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 understand.
|
```
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;
}
```
should I add a temp variable in there instead to move it?
|
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 to do this in Erlang/Elixir/C?
|
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 according to your skill and requirements! If you are unable even foundNIF official documentationandMagickWand API documentationI have some doubts the last one is the best choice for you.
|
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;
}
```
should I add a temp variable in there instead to move it?
|
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 to do this in Erlang/Elixir/C?
|
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 according to your skill and requirements! If you are unable even foundNIF official documentationandMagickWand API documentationI have some doubts the last one is the best choice for you.
|
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 assign element by element using a for loop. I want to do it in one statement.
|
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];
const char* firstCharTempHeader = tempheader2[0];
strcmp(firstCharTempHeader , "/");
```
Gives errors of :
comparison between pointer and integer
initialization makes pointer from integer without a cast
I feel like i am missing something fundamental here...
If this is a duplicate, please mark it. I cant find anything but i might not be searching the right thing
|
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;
b += 1;
}
return 0;
}
```
Compilation and execution :
```
pi@raspberrypi:/tmp $ gcc -pedantic -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
2 3
32 3
6 8
9 10
pi@raspberrypi:/tmp $
```
|
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 main(void)
{
return system("git clone https://github.com/manleyManlious22/TestData");
}
```
|
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 you were in a terminal. Any command which works in your shell should work there.
|
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 11110101 and I don't understand why. In my understanding shifting a positive number to the right will insert 0 and not 1.
|
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 implementation-defined.)(~p) >> 4 & 255produces 111101012.111101012is 245.
|
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 tables, but I can't seem to find a way to pull this data per font.
Here is how I'm pulling the data in osx:
```
CTFontRef lCTFont = CTFontCreateWithName((CFStringRef)lNSFontName, 800.0f, NULL);
CFDataRef lKernTable = CTFontCopyTable(lCTFont, kCTFontTableKern, kCTFontTableOptionNoOptions);
CFDataRef lGPOSTable = CTFontCopyTable(lCTFont, kCTFontTableGPOS, kCTFontTableOptionNoOptions);
```
|
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 declare and also define the value on stack.
int i;
Is there some standard for this specified for Java? If not, what do compiler implementations typically do?
|
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)
b = 500;
c = 900;
printf("b = %d c = %d\n", b, c);
return 0;
}
```
The answer after execution of this problem is b=100 and c=900. But i have not understood how.
|
```
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;
b += 1;
}
return 0;
}
```
Compilation and execution :
```
pi@raspberrypi:/tmp $ gcc -pedantic -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
2 3
32 3
6 8
9 10
pi@raspberrypi:/tmp $
```
|
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 main(void)
{
return system("git clone https://github.com/manleyManlious22/TestData");
}
```
|
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 you were in a terminal. Any command which works in your shell should work there.
|
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 11110101 and I don't understand why. In my understanding shifting a positive number to the right will insert 0 and not 1.
|
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 implementation-defined.)(~p) >> 4 & 255produces 111101012.111101012is 245.
|
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 tables, but I can't seem to find a way to pull this data per font.
Here is how I'm pulling the data in osx:
```
CTFontRef lCTFont = CTFontCreateWithName((CFStringRef)lNSFontName, 800.0f, NULL);
CFDataRef lKernTable = CTFontCopyTable(lCTFont, kCTFontTableKern, kCTFontTableOptionNoOptions);
CFDataRef lGPOSTable = CTFontCopyTable(lCTFont, kCTFontTableGPOS, kCTFontTableOptionNoOptions);
```
|
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 declare and also define the value on stack.
int i;
Is there some standard for this specified for Java? If not, what do compiler implementations typically do?
|
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)
b = 500;
c = 900;
printf("b = %d c = %d\n", b, c);
return 0;
}
```
The answer after execution of this problem is b=100 and c=900. But i have not understood how.
|
```
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 declare and also define the value on stack.
int i;
Is there some standard for this specified for Java? If not, what do compiler implementations typically do?
|
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)
b = 500;
c = 900;
printf("b = %d c = %d\n", b, c);
return 0;
}
```
The answer after execution of this problem is b=100 and c=900. But i have not understood how.
|
```
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 slower. I just can't find the rationale behind it.
Anyone here know what made the developers decide to force allocation for this?
|
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 implementers can change there implementation without the user code caring. It's basically the "C" version of theC++ PIMPL pattern.
|
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){
Vector normVec;
//calls norm function which also takes a pointer of vector type as argument
float norm = norm(&vec);
normVec.x = vec->x/norm;
normVec.y = vec->y/norm;
normVec.z = vec->z/norm;
return normVec;
}
```
I get this error:
error: called object ‘norm’ is not a function or function pointer.How can I get this function running smoothly?
|
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 $i; done;
/usr/share/man/man3/strcpy.3.gz
/usr/share/man/man3/strlcpy.3bsd.gz
No manual entry for strscpy
```
|
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("%d", &n);
sum += n;
i++;
} while (n != -1);
av = (float)sum / i;
printf("%f", av);
return 0;
}
```
|
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;
sum += n;
i++;
}
```
|
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 know that it is the same asp, as that also gives me the address ofx, but why is this written as(void*)p?
|
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 size. However, any object pointer type is convertible tovoid *. So, to be sure that all%pvariables are processed correctly byprintf, they are required to bevoid *.
|
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 alternative is to just do all this manually without calling any string library functions.
Yes, you will need loops.
|
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_metadata(FILE *image, int *pixel_array_offset, int *width, int *height) {
FILE* img = fopen(*image, "rb");
}
```
|
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 file I/O functions onimageright off the bat (fread,fgets,fscanf, etc.).
|
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 thatpointerpoints to and get thenamemember from it.” For this to work,pointermust be a pointer to a structure. It could have been declared asstruct foo *pointer.
(*pointer).namesays “Get the structure thatpointerpoints to. Get thenamemember from it.” It also must be apointerto a structure.
(The only difference between the last two is that the second uses one operator in source code. The operations actually performed are the same.)
|
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_metadata(FILE *image, int *pixel_array_offset, int *width, int *height) {
FILE* img = fopen(*image, "rb");
}
```
|
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 file I/O functions onimageright off the bat (fread,fgets,fscanf, etc.).
|
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 thatpointerpoints to and get thenamemember from it.” For this to work,pointermust be a pointer to a structure. It could have been declared asstruct foo *pointer.
(*pointer).namesays “Get the structure thatpointerpoints to. Get thenamemember from it.” It also must be apointerto a structure.
(The only difference between the last two is that the second uses one operator in source code. The operations actually performed are the same.)
|
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,648? Go for 8 bytes? But if you are not interested in negative numbers, then isn't it wastage of 4 bytes?
If you use unsigned int, all 32bits represent your number as you don't need to spare 1 bit for sign. Hence, with unsigned int, you can go from 0 to 4,294,967,295 i.e. 2^32
Same applies for other data types.
|
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;
char str_pos;
printf("The character at index %d is %c",pos,str_pos, "\n");
```
|
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 presume that variables are initialized before you're printing them.
|
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 *. If thesa_familymember isAF_INET6, that indicates an IPv6 address and the socket address is actually astruct sockaddr_in6.
|
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 do I do this?
|
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 here? It seems to be thatfirst & 0b01is zero, so should pass the condition.
|
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 0.
Add parenthesis to get the desired behavior:
```
(first & 0b10) == 0
```
|
```
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 8 bits toBuffer[1], giving you 0x0806
|
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);
num = 0;
scanf("%d", &num);
arr[i-1] = num;
}
for (i = 1; i <= 5; i++) {
if (arr[i - 1] >= 75) {
printf("%d\n", arr[i - 1]);
}
}
return 0;
}
```
|
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);
return 0;
}
void printbool(bool a)
{
a = TRUE;
}
```
|
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 exploit pronefputs(s,stdout); OK. Not as heavy as printf but will add the new line
|
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);
```
As you can see I need to somehow toi convert the integervalinto openssl's BIGNUM. How I can do that? One approach is to convert it asunsigned char *byte array and use theBN_bin2bnfunction but will that give me the desired functionality?
|
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 getting garbage values in this hello.txt file when I run this program and enter the string as input?
|
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 the end ofa.
Please check the return values opopen(),scanf(), andwrite(), to make sure all steps are executed without error. See the manual pages for their return values.
|
```
#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 a = 5;
testFunction(&a);
printf("In main() a should be 2: %d", a);
return 0;
}
```
How can i send the pointer from a given to a function inside a function to another function?
So that the statements inside the code above are all true
Current output is:
```
In a should be 5: 5
In a should be 0: 0
In F2 a should be 0: 6422316
In F2 a should be 2: 2
In main() a should be 2: 0
```
|
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);
num = 0;
scanf("%d", &num);
arr[i-1] = num;
}
for (i = 1; i <= 5; i++) {
if (arr[i - 1] >= 75) {
printf("%d\n", arr[i - 1]);
}
}
return 0;
}
```
|
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);
return 0;
}
void printbool(bool a)
{
a = TRUE;
}
```
|
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 exploit pronefputs(s,stdout); OK. Not as heavy as printf but will add the new line
|
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);
```
As you can see I need to somehow toi convert the integervalinto openssl's BIGNUM. How I can do that? One approach is to convert it asunsigned char *byte array and use theBN_bin2bnfunction but will that give me the desired functionality?
|
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 getting garbage values in this hello.txt file when I run this program and enter the string as input?
|
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 the end ofa.
Please check the return values opopen(),scanf(), andwrite(), to make sure all steps are executed without error. See the manual pages for their return values.
|
```
#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 a = 5;
testFunction(&a);
printf("In main() a should be 2: %d", a);
return 0;
}
```
How can i send the pointer from a given to a function inside a function to another function?
So that the statements inside the code above are all true
Current output is:
```
In a should be 5: 5
In a should be 0: 0
In F2 a should be 0: 6422316
In F2 a should be 2: 2
In main() a should be 2: 0
```
|
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 string = %s\n", s2);
printf("Target string = %s\n", s1);
```
I thought the output would be null. But it just shows a 'S'.
|
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 string to get consistent results.
```
char s1[10] = "";
```
|
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 requires an instruction likeCVTSI2SD(Convert Doubleword Integer to Scalar Double-Precision Floating-Point Value), as seenhere. The compiler produces that instruction at compile time, but running the instruction (obviously) occurs at runtime.
|
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/UnixAssembler/cmake-build-debug/UnixAssembler.exe
The actual exe is located inc/Users/natan/Desktop/UnixAssembler/cmake-build-debug/UnixAssembler.exe, so I don't know why It's looking in thiscygdrivefolder.
I'm not sure what to try from here onwards. Any ideas?
|
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", *(arraypointer+1));
arraypointer++;
}
return 0;
}
```
|
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 = (unsigned char*)par;
*pbAdr2 = (unsigned char*)par;
printf("Data2: %x, %x", *pbAdr1, *pbAdr2 ); //displays 0, 6957f0 ==> why 0 for *pbAdr1?
}
```
|
*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", (void*)par);
// . . .
printf("Data2: %p, %p", (void*)*pbAdr1, (void*)*pbAdr2 );
```
|
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 only got invoked if a C source file started with a directive and the null directive placed at the very beginning of a C file was a good way to make sure the file was preprocessed (i.e., that later directives worked) without starting with a concrete directive.
|
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 sayingConditional jump or move depends on uninitialised value(s),Uninitialised value was created by a heap allocation
I can't figure out what's going wrong. We defined anodestruct outside themainfunction. So I think we can usesizeof(struct node), isn't it?
|
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)
while gcc tells meduplicate 'const' declaration specifier [-Wduplicate-decl-specifier]. Shouldn't each const I use have a different effect? One to make the pointed-to data immutable, the other for the received pointer not to be retarged?
|
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 variable or something similar but I do not know what kind of variable it is (integer, string, Boolean, etc).
Anyone have any idea??
|
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 not?
For the sake of simplicity assume Linux as the underlying OS.
|
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 those methods.This questionseems to be a good place to start, since you claim to be working on Linux.
|
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], SIZE, f1);
printf("wrote %zu elements out of %d requested\n", r1, SIZE);
fclose(f1);
}
}
```
|
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 don't know if that is very useful going forward.
I would also like to clarify that I am not printing the maximum value, rather I am supposed to print the maximum option. For example, is option 1 = 2000 and option 2 = 3000, I want to be able to print out "option 2 is the larger one".
I should also say that following with the rest of the assignment this selection is typically only done with mathematical operations+*-%/andpow()
|
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_ELEMENTS];
```
Then for the element at indexiin the array, the next element in the list is
```
array[array[i].next]
```
and the previous element is
```
array[array[i].prev]
```
Instead of usingNULLto mean a null pointer, use-1to mean a "null" index.
|
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 implementation-defined.
The result is implementation-defined, and you should look up how it is defined there.
Assuming twos complement and signed right shift,-25is11100111, shifting it by 3 will lead to11111100which is-4.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.