question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
Its a simple input that I want to make for char*. Why is this not working?
It throws me an exception that I can't resolve..
```
#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
char* GetCharSeq()
{
char *s = (char*)malloc(100);
scanf_s("%s", s);
return s;
}
int main()
{
char* charseq;
charseq = GetCharSeq();
return 0;
}
```
|
You haveundefined behaviorin your code. You have it because you provide to few arguments to thescanf_sfunction.
For every string argument, you need to provide not only the destination string but also the size of the string. So change your call to
```
scanf_s("%s", s, 100);
```
|
Why I see nothing when I run my code ?
I use DOSBox.
```
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <dos.h>
#include <conio.h>
#include <bios.h>
#include <ctype.h>
#include <math.h>
int main() {
int gdriver = DETECT,gmode = 0;
initgraph(&gdriver,&gmode,"C:\\TC\\BGI");
struct time t;
moveto(5,10);
outtext("Hello");
moveto(6,11);
outtext("World**strong text**");
moveto(1,24);
outtext("Press: 1-About_Author, 2-Current_Time,ESC to EXIT");
closegraph();
return 0;
}
```
|
Your code is right. The problem is with the path you are giving to search for the display driver files"C:\\TC\\BGI". This generally happen because thetcis not root of the mounted drive or the.exefile path you are using is notc:\\TC. Replace the path with"..//bgi". This will redirect frombin(the current working directory) to bgi.
|
I have a snippet of code, in C for reading entries from a passwd-style database:
```
do {
if (fscanf(db, "%s:%s:%d", uname, passwd, &gid) == EOF) {
return NULL;
}
} while (strcmp(uname, username));
```
However, when running it, it gives a segmentation fault. After running it in the debugger, I found that thestrcmppart is the part raising the segfault. Data types:
dbisFILE *, opened already.unameandpasswdarechar *, both initialised to NULLusernameischar [64]gidisint
How can I fix this problem, and alternatively how can I parse the database without needing to use this ugly hack?
|
If both the string variablesunameandpasswdare just pointers, that doesn't point anywhere, what do you think happens whenfscanftries to use those pointers and write the string into memory?
That will lead toundefined behavior, as will the dereferencing done in thestrcmpcall.
You should use arrays for theunameandpasswdvariables as well.
|
here is my CMakeLists.txt:
```
cmake_minimum_required(VERSION 3.3)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c11")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
add_executable(ex ex.c)
target_link_libraries(ex xdo)
```
the full code ishere
of course, the libxdo.so and xdo.h is exist
|
the checked answer is wrong, the right solution is:
```
#define __USE_XOPEN
#include "unistd.h"
#include <xdo.h>
```
|
So I've bee stuck with this problem for a while. Towards the end of my code whenever I call a function it can no longer return to the main function and causes a hard-fault error. I checked that it does reach the end of the function using breakpoints.
If I copy the code from the function into the main function it works with no problem, but makes the code less readable and repetitive.
Any idea why this happens and a way to fix it.
I am using the STM32F051C6 and programming in c in Eclipse.
|
This sounds like your stack overflows. Usually the stack size is defined in your linker file, try increasing it.
Check for recursive function calls which would fill your stack easily.
This could also be a memory issue like unknowingly overwriting your stack. Check for array and pointer accesses inside your function that cannot return.
|
This question already has answers here:How do I print the percent sign(%) in C? [duplicate](4 answers)Closed7 years ago.
I was just completing my assignment when I noticed that the text after the%symbol in double quotes is not printing. Here is a very easy example to show this:
```
//program
#include<stdio.h>
int main()
{
printf("remainder of 5%2 is : %d",5%2);//here %2 is not printing
return 0;
}
```
output:
```
remainder of 5 is : 1
```
Only the%2is not printed byprintf()rest everything is fine.
|
Use%%to print%:
```
printf("remainder of 5%%2 is : %d",5%2);
```
|
I have a third-party library written by C and I want to use it in my Android project by JNI.
The issue is that a error occured when I compile it like below:
error: undefined reference to 'pthread_testcancel'
and the code is
```
#if !defined(WIN32) && !defined (WINCE) && !defined(ITRON) && !defined(BTRON) && !defined(TENGINE) && !defined(PROCESS_BASE)
pthread_testcancel();
#endif
```
And only this method compile failed, some other methods are all ok likepthread_kill,pthread_join,pthread_create...
Anybody can help me to resolve it? Thanks very well.
|
Android's NDK doesn't supportpthread_canceldue to the complexity alsoimplementation of it is error prone and harmful to performance(of all code). so you can have look onpthread_cancel()alternatives in Android NDK.
|
IF "for loop" is like this,
```
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
```
Then,
Input can be given either as,
```
1
2
3
4
5
```
Hitting Enter Every time for the next Input.
OR
```
1 2 3 4 5
```
With space character between different input values.
Now, How does this thing work?
I mean if loop is running,
then how does it recognizes that Input is given for the next loop cycle wihtout hitting the Enter key.
|
How does this thing work?
This works becausescanf()reads only till aspaceornewlineortabis encountered.
So, when you give input1 2 3 4 5, at the first iterationscanf()reads1and aspaceis encountered andscanf()terminates keeping the value1to a[0]. At the next iteration2` is read the same way.
|
I am trying to create a header file, within the header file I want to create a string to pass an IP address into my network file (/etc/network/interfaces)
Currently I have a header file set up and it includes the following:
```
char Board_IP[] = "192.168.40.3";
int n1, n2, n3, n4;
sscanf(ip, "%d.%d.%d.%d", &n1, &n2, &n3, &n4).
```
Then in my network file:
```
address n1.n2.n3.n4
```
Whenever I try to restart my network, I always receive an error saying:
Reconfiguring network interfaces...Error: an inet prefix is expected rather than "n1.n2.n3.n4/255.255.255.224"
I know this is probably a simple question, but I am fairly new to this and would greatly appreciate some help.
Thank You!
|
Try using theinet.ptonfunction (the "reversed" function isinet.ntopif needed afterwards).
|
```
#include <stdio.h>
int main(void)
{
int a[]= {15, 14, 34, 46, 69, 86, 10, 0, 4};
int *p = a; // p point to the first element of array a[0]
printf("%x\n%x\n",&p+1, &a[0]);
return 0;
}
```
that code will print as example
```
bff0e554
bff0e554
```
so &p+1 return the address of the first element of array.
As i understand, &p return the address of that pointer and &p+1 should print the address of pointer + 1 please tell me what i missed !!
|
&ptakes the address ofp, not the value ofp. That for you&p + 1 == ais pure coincidence and depends on your stack alignment. Your compiler could have sorted the both variables in another order or put a gap in between.
|
Header file math.h is for mathematical functions like cos,sin, tan..
But how to write the ln function and not log?
|
The C functionlogis the natural logarithm, which mathematicians usually write as "ln".
The C functionlog10is the logarithm base 10, which is sometimes written "log".
|
I have a snippet of code, in C for reading entries from a passwd-style database:
```
do {
if (fscanf(db, "%s:%s:%d", uname, passwd, &gid) == EOF) {
return NULL;
}
} while (strcmp(uname, username));
```
However, when running it, it gives a segmentation fault. After running it in the debugger, I found that thestrcmppart is the part raising the segfault. Data types:
dbisFILE *, opened already.unameandpasswdarechar *, both initialised to NULLusernameischar [64]gidisint
How can I fix this problem, and alternatively how can I parse the database without needing to use this ugly hack?
|
If both the string variablesunameandpasswdare just pointers, that doesn't point anywhere, what do you think happens whenfscanftries to use those pointers and write the string into memory?
That will lead toundefined behavior, as will the dereferencing done in thestrcmpcall.
You should use arrays for theunameandpasswdvariables as well.
|
here is my CMakeLists.txt:
```
cmake_minimum_required(VERSION 3.3)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c11")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
add_executable(ex ex.c)
target_link_libraries(ex xdo)
```
the full code ishere
of course, the libxdo.so and xdo.h is exist
|
the checked answer is wrong, the right solution is:
```
#define __USE_XOPEN
#include "unistd.h"
#include <xdo.h>
```
|
So I've bee stuck with this problem for a while. Towards the end of my code whenever I call a function it can no longer return to the main function and causes a hard-fault error. I checked that it does reach the end of the function using breakpoints.
If I copy the code from the function into the main function it works with no problem, but makes the code less readable and repetitive.
Any idea why this happens and a way to fix it.
I am using the STM32F051C6 and programming in c in Eclipse.
|
This sounds like your stack overflows. Usually the stack size is defined in your linker file, try increasing it.
Check for recursive function calls which would fill your stack easily.
This could also be a memory issue like unknowingly overwriting your stack. Check for array and pointer accesses inside your function that cannot return.
|
This question already has answers here:How do I print the percent sign(%) in C? [duplicate](4 answers)Closed7 years ago.
I was just completing my assignment when I noticed that the text after the%symbol in double quotes is not printing. Here is a very easy example to show this:
```
//program
#include<stdio.h>
int main()
{
printf("remainder of 5%2 is : %d",5%2);//here %2 is not printing
return 0;
}
```
output:
```
remainder of 5 is : 1
```
Only the%2is not printed byprintf()rest everything is fine.
|
Use%%to print%:
```
printf("remainder of 5%%2 is : %d",5%2);
```
|
I have a third-party library written by C and I want to use it in my Android project by JNI.
The issue is that a error occured when I compile it like below:
error: undefined reference to 'pthread_testcancel'
and the code is
```
#if !defined(WIN32) && !defined (WINCE) && !defined(ITRON) && !defined(BTRON) && !defined(TENGINE) && !defined(PROCESS_BASE)
pthread_testcancel();
#endif
```
And only this method compile failed, some other methods are all ok likepthread_kill,pthread_join,pthread_create...
Anybody can help me to resolve it? Thanks very well.
|
Android's NDK doesn't supportpthread_canceldue to the complexity alsoimplementation of it is error prone and harmful to performance(of all code). so you can have look onpthread_cancel()alternatives in Android NDK.
|
I have a character in a char-Array which I get with fputs(). But it contains a char which is getting count by the function strlen(). I decide to give me out the int value of this char to see where the problem is.
As char I can see nothing. Thought its a Whitespace but not sure. Would like if someone could tell me what it is and explain why it is there.
```
printf("%d",(int) input[6]); //--> give me the value of 10 out.
```
|
The value10is the ASCII value for the newline character (LF, or linefeed). Closely related is character13, which is CR, or carriage return, which, on Windows systems, often precedes the LF character. I would suggest getting a copy of the ASCII table (they're all over the web) and referencing it from time to time.
Character10can be represented by'\n'in C code, as well as'\012','\x0a', and'\u000a'Character13(carriage return) can be represented by'\r','\015','\x0d', and'\u000d'.
|
Is destructor called in such piece of code when a is destroyed?
```
extern "C" {
int func()
{
A a(); // a is object of class A
}
}
```
|
extern "C"is alink-timedirective. It does not change how the language itself works.
No destructor is called in your case sinceA a();is declaring a function prototype for a function that takes no arguments and returns anA. It doesnotcreate an instance ofA. (Seemost vexing parse).
If you had writtenA a;instead, then the default constructor would have been called, along with the destructor onceagoes out of scope.
|
```
#include<string.h>
#include<stdio.h>
void main()
{
char *a="12345"; //Add number of that string
}
```
How can i add number of that string
example :
```
sum=1+2+3+4+5
sum=15
```
How can i do that?
|
```
int sum = 0;
char *a = "12345";
while (*a) {
sum += *a - '0';
a++;
}
printf("sum=%d\n", sum);
```
|
Discovering gateway devices process using miniupnp is as follows:
CallupnpDiscover(...)to find all available devices which support UPnP protocol.CallUPNP_GetValidIGD(...)to get first gateway from this list.
Is there any solution to getallgateways from list, obtained in step 1?
|
Made aforkof miniupnpc. Added routineGetValidConnectedIGDs, which returns list of all gateway devices found.
|
The function:
```
int PEM_write_RSAPrivateKey(FILE *fp, RSA *x, const EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u);
```
The way I call the function :
```
PEM_write_RSAPrivateKey(pFile, pRSA,NULL,0,NULL,NULL,(void*)passphrase);
```
In openssl's documents,it says the last parameter is passphrase,but I find the context in the output file is not encrypted。
|
Obviously, because you set the cipher to NULL you won't get any encryption.
Go with something like:
```
PEM_write_RSAPrivateKey(pFile,pRSA,EVP_des_ede3_cbc(),passphrase, passphraseLength,NULL,NULL);
```
And of course change the cipher as you please, better option would be to use AES-128-CBC, but it's up to your specific goal and performance requirements.
Don't forget to initialize the OpenSSL library with something likeOpenSSL_add_all_algorithms()
|
Is it possible anyhow to increment ASCII value of a char in C? Let's say I have following code
```
int main(){
char *a = "This is my test string";
/* *(a+12) += 21; This isnt going */
printf("%c = %c\n", *(a+12), *(a+12)+21);
printf("%s\n", a);
return 0;
}
```
What I want, for example, is to increment theecharacter with 21 which would bezand make it permanent inside that array. So when I useprintfon the array, it printszon that place instead ofe.
How would we go about this?
|
Changechar *a = "This is my test string";to `char a[] = "This is my test string";
|
I'm trying to read from an output file and write to an input file, but my program isn't working quite well. I have no idea how to fix it. I have this:
```
int i;
FILE *file;
char filename[500];
printf("Please enter the name of the file you would like to write to\n", &filename);
scanf("%s", filename);
file = fopen(filename, "w");
printf("Writing to file %s\n", filename);
fprintf("%d / %d", *num, *denom);
fclose(file);`
```
Can someone help me understand what I am doing wrong for this write file of the code?
|
change
```
fprintf("%d / %d", *num, *denom);
```
to
```
fprintf(file, "%d / %d", *num, *denom);
```
|
Is destructor called in such piece of code when a is destroyed?
```
extern "C" {
int func()
{
A a(); // a is object of class A
}
}
```
|
extern "C"is alink-timedirective. It does not change how the language itself works.
No destructor is called in your case sinceA a();is declaring a function prototype for a function that takes no arguments and returns anA. It doesnotcreate an instance ofA. (Seemost vexing parse).
If you had writtenA a;instead, then the default constructor would have been called, along with the destructor onceagoes out of scope.
|
```
#include<string.h>
#include<stdio.h>
void main()
{
char *a="12345"; //Add number of that string
}
```
How can i add number of that string
example :
```
sum=1+2+3+4+5
sum=15
```
How can i do that?
|
```
int sum = 0;
char *a = "12345";
while (*a) {
sum += *a - '0';
a++;
}
printf("sum=%d\n", sum);
```
|
Discovering gateway devices process using miniupnp is as follows:
CallupnpDiscover(...)to find all available devices which support UPnP protocol.CallUPNP_GetValidIGD(...)to get first gateway from this list.
Is there any solution to getallgateways from list, obtained in step 1?
|
Made aforkof miniupnpc. Added routineGetValidConnectedIGDs, which returns list of all gateway devices found.
|
The function:
```
int PEM_write_RSAPrivateKey(FILE *fp, RSA *x, const EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u);
```
The way I call the function :
```
PEM_write_RSAPrivateKey(pFile, pRSA,NULL,0,NULL,NULL,(void*)passphrase);
```
In openssl's documents,it says the last parameter is passphrase,but I find the context in the output file is not encrypted。
|
Obviously, because you set the cipher to NULL you won't get any encryption.
Go with something like:
```
PEM_write_RSAPrivateKey(pFile,pRSA,EVP_des_ede3_cbc(),passphrase, passphraseLength,NULL,NULL);
```
And of course change the cipher as you please, better option would be to use AES-128-CBC, but it's up to your specific goal and performance requirements.
Don't forget to initialize the OpenSSL library with something likeOpenSSL_add_all_algorithms()
|
OSX man page says aboutPOSIX_SPAWN_SETEXECbit inposix_spawnsystem call:
```
POSIX_SPAWN_SETEXEC
Apple Extension: If this bit is set, rather than returning to the caller,
posix_spawn(2) and posix_spawnp(2) will behave as a more featureful execve(2).
```
Anyone knows what exactly is the difference between a regularposix_spawn()and aposix_spawn()after a call toposix_spawnattr_setflagswhich enabledPOSIX_SPAWN_SETEXEC?
|
WhenPOSIX_SPAWN_SETEXECis set, instead of spawning a new process,posix_spawnreplaces the process just asexecvewould do.
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed7 years ago.Improve this question
I have the code below:
```
char temp[1024];
bzero(temp, 1024);
for(i=0;i<4;i++){
temp[i] = '9';
}
int balance = atoi(temp);
```
When I print temp, it displays 9999. However, balance is assigned to nothing.If I use:
```
printf("%c", balance); // it prints nothing!
```
What's wrong with the code?
|
You are using the wrong format specifier with
```
printf("%c", balance);
```
which should be
```
printf("%d", balance);
```
becausebalanceis defined asint.
|
```
int main()
{
int a = (1,2,3);
int b = (++a, ++a, ++a);
int c= (b++, b++, b++);
printf("%d %d %d", a,b,c);
}
```
I am beginner in programming. I am not getting how does this program shows me output of6 9 8.
|
The,used in all the three declarations
```
int a = (1,2,3);
int b = (++a, ++a, ++a);
int c = (b++, b++, b++);
```
arecomma operator. It evaluates the first operand1and discard it, then evaluates the second operand and return its value. Therefore,
```
int a = ((1,2), 3); // a is initialized with 3.
int b = ((++a, ++a), ++a); // b is initialized with 4+1+1 = 6.
// a is 6 by the end of the statement
int c = ((b++, b++), b++); // c is initialized with 6+1+1 = 8
// b is 9 by the end of the statement.
```
1 Order of evaluation is guaranteed from left to right in case of comma operator.
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed7 years ago.Improve this question
I have the code below:
```
char temp[1024];
bzero(temp, 1024);
for(i=0;i<4;i++){
temp[i] = '9';
}
int balance = atoi(temp);
```
When I print temp, it displays 9999. However, balance is assigned to nothing.If I use:
```
printf("%c", balance); // it prints nothing!
```
What's wrong with the code?
|
You are using the wrong format specifier with
```
printf("%c", balance);
```
which should be
```
printf("%d", balance);
```
becausebalanceis defined asint.
|
```
int main()
{
int a = (1,2,3);
int b = (++a, ++a, ++a);
int c= (b++, b++, b++);
printf("%d %d %d", a,b,c);
}
```
I am beginner in programming. I am not getting how does this program shows me output of6 9 8.
|
The,used in all the three declarations
```
int a = (1,2,3);
int b = (++a, ++a, ++a);
int c = (b++, b++, b++);
```
arecomma operator. It evaluates the first operand1and discard it, then evaluates the second operand and return its value. Therefore,
```
int a = ((1,2), 3); // a is initialized with 3.
int b = ((++a, ++a), ++a); // b is initialized with 4+1+1 = 6.
// a is 6 by the end of the statement
int c = ((b++, b++), b++); // c is initialized with 6+1+1 = 8
// b is 9 by the end of the statement.
```
1 Order of evaluation is guaranteed from left to right in case of comma operator.
|
Why is there no dscanf function for reading from file descriptors?
We have fprintf, sprintf and dprintf for printing but for scanning there is only fscanf and sscanf.
|
It is not possible to writedscanf.
The scanf family requires that the stream is buffered, or else that it is capable of putting back a character that was read. POSIX file descriptors are neither.
Consider this stream
```
1234xyz
```
How would you scan a number off it? You cannot read it byte by byte and stop just beforex. That would require clairvoyance. You also cannot readxand decide you don't need it, because you cannot put it back.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed7 years ago.Improve this question
I am trying to understand what the*addspart of this function does:
|
I think you should read more aboutpointers
*addsin this*is not associated withaddsbut with the return type.
It is more like this..
```
struct list* adds(struct data *head, void fun)
```
Now it is easy to make out thataddsis a function that returns apointer to struct list.
This is the way of declaring apointer to a function
```
void (*free_fun)(void *)
```
Start reading from the namefree_fun. free_fun is a*, sopointer, to a function, that take arguments(void *)and returnsvoid.
|
My professor suggested that we should also pass a integer size as the parameter :
```
int abc(const int data[], int size, int value) {
int i= 0, ans= -1;
while (i < size && ans == -1) {
if (data[i] == value)
ans= i;
i++;
}
return ans;
}
```
However, I don't think it is necessary to add the integer size in the parameter.
I think the function can be changed to:
```
int abc(const int data[], int value) {
int i= 0, ans= -1;
while (data[i]!=NULL) {
if (data[i] == value)
ans= i;
i++;
}
return ans;
}
```
(I know that we are just passing the pointer of the first element of the array in to the function!)
Is the first version has more advantage than the second version?
|
data[i]being anintvalue should not be compared againstNULL. That's just not correct.
Youshouldpass the size as a separate parameter.
|
```
if (!strcmp(yn, "y")) {
isCooked[x] = 1;
printf("How much %s (in grams) will you cook? ", food[choice - 1]);
} else {
isCooked[x] = 0;
printf("How much %s (in grams) will you eat raw? ", food[choice - 1]);
}
scanf("%f", &grams);
userGrams[x] = grams;
```
Where should I put my if-else statement if I want to control the user input of grams? I want to put restrictions on my program, like the user should only input minmimum of 20g and the maximum of 200g.
|
You can usewhileloop and anifstatement -
```
while(scanf("%f", &grams)==1){ // loop until scanf returns 1
if(grams>=20 && grams<=200){ // validate your input
userGrams[x] = grams; //assign value
break; //break out of loop
}
else{
printf("Invalid Input !! ");
}
}
```
|
My professor suggested that we should also pass a integer size as the parameter :
```
int abc(const int data[], int size, int value) {
int i= 0, ans= -1;
while (i < size && ans == -1) {
if (data[i] == value)
ans= i;
i++;
}
return ans;
}
```
However, I don't think it is necessary to add the integer size in the parameter.
I think the function can be changed to:
```
int abc(const int data[], int value) {
int i= 0, ans= -1;
while (data[i]!=NULL) {
if (data[i] == value)
ans= i;
i++;
}
return ans;
}
```
(I know that we are just passing the pointer of the first element of the array in to the function!)
Is the first version has more advantage than the second version?
|
data[i]being anintvalue should not be compared againstNULL. That's just not correct.
Youshouldpass the size as a separate parameter.
|
```
if (!strcmp(yn, "y")) {
isCooked[x] = 1;
printf("How much %s (in grams) will you cook? ", food[choice - 1]);
} else {
isCooked[x] = 0;
printf("How much %s (in grams) will you eat raw? ", food[choice - 1]);
}
scanf("%f", &grams);
userGrams[x] = grams;
```
Where should I put my if-else statement if I want to control the user input of grams? I want to put restrictions on my program, like the user should only input minmimum of 20g and the maximum of 200g.
|
You can usewhileloop and anifstatement -
```
while(scanf("%f", &grams)==1){ // loop until scanf returns 1
if(grams>=20 && grams<=200){ // validate your input
userGrams[x] = grams; //assign value
break; //break out of loop
}
else{
printf("Invalid Input !! ");
}
}
```
|
Here's the code that I'm trying to run
```
#include<stdio.h>
#include<string.h>
int overFlow(char* value){
char string[8];
strcpy(string, value);
return 0;
}
int main(int argc, char** argv){
char string[10];
strcpy(string, argv[1]);
overFlow(string);
return 0;
}
```
with a simple text file that has this
```
hello
```
but when I execute "./program < textfile" I get a seg fault.
Any help would be great. Thanks.
|
When you execute your program with following command:
```
./program < textfile
```
You don't pass any arguments to program. So arg count is 1, and this array : argv just has program name
And this line fails:
```
strcpy(string, argv[1]);
```
|
For simplicity, let's only talk about Debian Linux.
I read the man page forlocale(7), but it only talks about how to use locales.
I'm wondering where is the file that defines what formats the localees_ES.utf8will use. For example, I want to see where%cis defined as%Y %m %dor where%Ais defined asLunesfores_ES.utf8.
I was poking around in/usr/lib/locale, but didn't find my answer there.
|
The easy way to set-up all things is running the command:dpkg-reconfigure localesas root.
You can find your default locales in the file:/etc/locale.gen
For a list of valid supported locales look at:/usr/share/i18n/SUPPORTED
If you want to set a locale, uncomment the locale line in/etc/locale.genthen run the command:$ sudo locale-gen
I am running Debian Jessie.
|
This question already has answers here:Reading from stdin(2 answers)Command Line argument in C not printing correctly(2 answers)Closed7 years ago.
I need to input a file in a c program for Linux
```
a.out < inputfile
```
The problem is that i don't know how to receive a file
it can't be like:
```
FILE *fp;
char filename[100];
fopen = (fp,"r");
...
```
I need as input the file, no the name.
Is there anyway to do this?
|
Use stdin as your file pointer. It's already declared and open You don't need an fopen
|
How to merge contents from several files (not limited no. and file name can be provided through command line arguments) in to a separate file or print in console window.
|
This is a rather easy test: for each command line argument, open the file, repeatedly read a character from the file until you getEOF, write said character and loop. close the file. add some error checking and return 0 unless some error occurred. It should take less than 1 hour to code, test and finalize.
|
I have to write a string on a file,an address like : "Via Leopardi 38".
I think that a loop and a char by char printing is the best system,because it has no problems related to the non-null terminated strings.
The problem is that when the loop arrives to the null char(the space between "Via" and "Leopardi" the loop ends and it writes only "Via".
Is there a different test condition for the loop I could use?
```
FILE *fo = open(filename,"w");
for (j=0;isalnum(phonebook[i].addr[j])!=0;j++) {
fprintf(fo,"%c",phonebook[i].addr[j]);
}
```
|
Whitespace is not alphabet nor digits, soisalnum(phonebook[i].addr[j])will return0and tle loop ends.
Try usingphonebook[i].addr[j]!=0as the condition.
|
I am new to c programming language. I am trying to reverse elements in char array. Actually, I almost reversed but there is something that I can't make it.
Here is code:
```
void q2_reverseTheArray(char word[100]){
int lentgh=sizeof(word);
int j;
for(j=length+1; j>=0; j--){
printf("%c", word[j]);
}
```
The code reverse the array but it adds another letter.
|
here you have a working example:
```
#include <stdio.h> // printf
#include <stdlib.h> // malloc, free
#include <string.h> // strlen
int main() {
char* s = "hello";
size_t l = strlen(s);
char* r = (char*)malloc((l + 1) * sizeof(char));
r[l] = '\0';
int i;
for(i = 0; i < l; i++) {
r[i] = s[l - 1 - i];
}
printf("normal: %s\n", s);
printf("reverse: %s\n", r);
free(r);
}
```
your code was wrong inlength + 1it should saylength - 1.
and you have to pay attention to the terminating'\0'.
|
I have an array of functions that needs to be allocated at run-time to be called in sequence. Which function pointer goes in which spot is determined programatically, e.g.:
```
void ((drawFunctions*)(...))[0] = drawTriangle;
...
for(...)
drawFunctions[i](...);
```
I want to malloc an array of function pointers because I don't know until run-time how many will be needed. How would you do this?
|
A typedef would probably make the syntax a little more bearable:
```
typedef void (*drawFunctionPointer)(void);
drawFunctionPointer *drawFunctions = malloc(sizeof(drawFunctionPointer) * numFunctions);
```
|
I'm given code for an algorithm as such:
```
1 sum =0;
2 for(i=0; i<n; i++)
3 for(j=1; j<= n; j*=3)
4 sum++;
```
I'm told this algorithm runs inO(nlogn)where log is in base 3.
So I get that the second line runsn times, and since line 3 is independent of line 2 I would have to multiply the two to get the Big O, however, I'm not sure how the answer is nlogn(log in base 3), is their a guaranteed way to figure this out everytime? It seems like with nested loops, there's a different case that can occur each time.
|
What you have been told is correct. The algorithm runs inO(nlog(n)). The third line:for(j=1; j<= n; j*=3)runs inO(log3(n))because you multiply by 3 each time. To see it more clearly solve the problem: how many times you need to multiply 1 by 3 to get n. Or3^x = n. The solutionis x = log3(n)
|
I am not very familiar with assembly language or disassembly binary codes, could someone tell me, if "x <<= 0;" or "x >>= 0;" will actually generate instructions?
|
Ifxis an integer type,x >>= 0andx <<= 0should not generate any code. Yet there are specific circumstances where the compiler could and indeed should generate code:
If you turn optimizations off (clang -O0orgcc -O0), the compiler may generate code and in the case ofclang, will. But it is not required to.Ifxis avolatilequalified type, the compiler isrequiredto generate code to read its value and write back the value read. The actual shifting will do nothing to the value, so the code generated may be identical to that generated forx = x;.
|
This question already has answers here:What should main() return in C and C++?(19 answers)Closed7 years ago.
I am using Sublime to program in C but when the code is compiled it keeps returning[Finished in 1.1s with exit code 10]. What does that mean? What is going on?
```
#include <stdio.h>
void main()
{
int x;
scanf("%d", &x);
printf("%d", x);
}
```
|
```
#include <stdio.h>
int main()
{
int x;
scanf("%d", &x);
printf("%d", x);
return 0;
}
```
main( ) does not take void as a return type.In C programming language we use int as a return type of main .Exit codes are nothing but Windows System Error Codes .I think you are using windows Operating system and for windows Operating system
exit code 10 means :The environment is incorrect.
May be your installation process was not correct .
Reinstall it and run the program .
|
This is a simple program :
```
int main() {
return 0;
}
```
The exit code is0.
If I write:
```
int main() {
return 700;
}
```
The exit code is188.
Why is188instead of700the exit code here?
|
While the main function in C returns anint,operating systems don't necessarily useintas the error code.
700in binary is1010111100.Truncating this value to eight bits yields10111100.This equals188in decimal.
That means your OS uses eight bits for error codes.1
1Or possibly nine bits because the 8thbit (we start counting from 0, mind you) is0here. This is highly improbably due to9not being a power of2, though, as is convention for data widths.
|
Let's say I initialize an array like this:
```
char array[] = {0, 0, 0, 0, 0};
```
Then I modify that array by writing some data to it so in the end it looks like this:
```
array[] = {1, 42, 32, 16, 89};
```
If I want to re-initialize the same array back to zeros so I can use that same array again, would it be correct to do so in this way?:
```
memset(array, 0, 5);
```
Thanks
|
yes, butmemset(array, 0, sizeof(array));would be better, that you do not need to keep track of the size of the array if you change the size to e.g. 6 later.
|
I have an array of functions that needs to be allocated at run-time to be called in sequence. Which function pointer goes in which spot is determined programatically, e.g.:
```
void ((drawFunctions*)(...))[0] = drawTriangle;
...
for(...)
drawFunctions[i](...);
```
I want to malloc an array of function pointers because I don't know until run-time how many will be needed. How would you do this?
|
A typedef would probably make the syntax a little more bearable:
```
typedef void (*drawFunctionPointer)(void);
drawFunctionPointer *drawFunctions = malloc(sizeof(drawFunctionPointer) * numFunctions);
```
|
I'm given code for an algorithm as such:
```
1 sum =0;
2 for(i=0; i<n; i++)
3 for(j=1; j<= n; j*=3)
4 sum++;
```
I'm told this algorithm runs inO(nlogn)where log is in base 3.
So I get that the second line runsn times, and since line 3 is independent of line 2 I would have to multiply the two to get the Big O, however, I'm not sure how the answer is nlogn(log in base 3), is their a guaranteed way to figure this out everytime? It seems like with nested loops, there's a different case that can occur each time.
|
What you have been told is correct. The algorithm runs inO(nlog(n)). The third line:for(j=1; j<= n; j*=3)runs inO(log3(n))because you multiply by 3 each time. To see it more clearly solve the problem: how many times you need to multiply 1 by 3 to get n. Or3^x = n. The solutionis x = log3(n)
|
I am not very familiar with assembly language or disassembly binary codes, could someone tell me, if "x <<= 0;" or "x >>= 0;" will actually generate instructions?
|
Ifxis an integer type,x >>= 0andx <<= 0should not generate any code. Yet there are specific circumstances where the compiler could and indeed should generate code:
If you turn optimizations off (clang -O0orgcc -O0), the compiler may generate code and in the case ofclang, will. But it is not required to.Ifxis avolatilequalified type, the compiler isrequiredto generate code to read its value and write back the value read. The actual shifting will do nothing to the value, so the code generated may be identical to that generated forx = x;.
|
This question already has answers here:What should main() return in C and C++?(19 answers)Closed7 years ago.
I am using Sublime to program in C but when the code is compiled it keeps returning[Finished in 1.1s with exit code 10]. What does that mean? What is going on?
```
#include <stdio.h>
void main()
{
int x;
scanf("%d", &x);
printf("%d", x);
}
```
|
```
#include <stdio.h>
int main()
{
int x;
scanf("%d", &x);
printf("%d", x);
return 0;
}
```
main( ) does not take void as a return type.In C programming language we use int as a return type of main .Exit codes are nothing but Windows System Error Codes .I think you are using windows Operating system and for windows Operating system
exit code 10 means :The environment is incorrect.
May be your installation process was not correct .
Reinstall it and run the program .
|
This is a simple program :
```
int main() {
return 0;
}
```
The exit code is0.
If I write:
```
int main() {
return 700;
}
```
The exit code is188.
Why is188instead of700the exit code here?
|
While the main function in C returns anint,operating systems don't necessarily useintas the error code.
700in binary is1010111100.Truncating this value to eight bits yields10111100.This equals188in decimal.
That means your OS uses eight bits for error codes.1
1Or possibly nine bits because the 8thbit (we start counting from 0, mind you) is0here. This is highly improbably due to9not being a power of2, though, as is convention for data widths.
|
Let's say I initialize an array like this:
```
char array[] = {0, 0, 0, 0, 0};
```
Then I modify that array by writing some data to it so in the end it looks like this:
```
array[] = {1, 42, 32, 16, 89};
```
If I want to re-initialize the same array back to zeros so I can use that same array again, would it be correct to do so in this way?:
```
memset(array, 0, 5);
```
Thanks
|
yes, butmemset(array, 0, sizeof(array));would be better, that you do not need to keep track of the size of the array if you change the size to e.g. 6 later.
|
How can I allocate withmallocand array of structures within and array of structures?
for expample:
```
struct car_t{
int price;
float kmsDriven;
};
struct garage_t{
int locationX;
int locationY;
struct car_t * car;
}
```
There's an array of garages, which every one of them has an array of cars.
|
You will have to use a loop:
```
#define N 42
#define M 17
struct garage_t *a = malloc(sizeof *a * N);
for (int i = 0; i < N; i++) {
a[i].car = malloc(sizeof (*a[i].car) * M);
}
```
|
I have been struggling with this. What I have found here on stackoverflow, and other places was to just do:
```
memcpy(&a, &b, sizeof(b));
```
But for me, that did not work. So I thought, I share what worked for me without any unexpected behavior.
|
Assume you have:
```
#define N 42
struct struct_name *a = malloc(sizeof *a * N); // allocate N objects
struct struct_name *b = malloc(sizeof *b * N); // allocate N objects
```
then the correctmemcpycall to copy the array of structure objects is:
```
memcpy(a, b, sizeof *a * N);
```
|
Given this c code:
```
char** names=(char**)malloc(count*sizeof(char*));
```
I want to convert it to NASM assembly code. Here is what I tried, but the code crashes:
```
mov eax, dword count
mov ebx, [eax*4] ;; i did times 4 because we clear stack by 4 bits or bytes?
push ebx
call _malloc
mov names, eax
add esp, 4
```
What doessizeof(char*)mean? which char pointer is the code addressing?
|
The reason it crashes is becausemov ebx, [eax*4]is accessing memory at addresseax * 4which is unlikely to be valid, and definitely not what you want anyway. To multiply by 4, you can uselea ebx, [eax*4]orshl eax, 2thenpush eax.
PS: Learn to use a debugger.
|
I could easily print what I wanted in a loop, but I'm new to functions and I need to save or return the sum of the dividers that have no remainder to a number which is an input of the user.
Example:
Input -6
Output -1+2+3=6
How I started:
```
int NumberOfDividers(int number)
{
int i,num, count = 0;
num = number;
for ( i = 0; i < num; i++)
{
if ((num % i) == 0) //so now I know i is one of the dividers i want to save.
}
}
```
So ifiis one of the dividers I want, how can I save it into a variable? Or an array?
|
To return the sum of the proper divisors, do:
```
int sum_of_proper_divisors (int number)
{
int sum = 0;
int i;
for (i = 1; i < number; i++)
{
if ((number % i) == 0)
sum += i;
}
return sum;
}
```
You just need to use the return keyword to return the value.
|
I'm trying to align multiple variables in a table like output.
I am currently using padding but I can not see how to correctly align the output.
I print the variables:
```
printf("\n %15s", name);
printf("%15d", level);
```
Then I call the next function repeatedly, all is fine unless there is more than one digit.
```
printf("%11dhr %.1fmn",t,t2);
```
|
Having the variables defined asint t;andfloat t2;(ordouble t2;), as it is now%.1fprintst2withonedigit after the decimal point. This is theprecision specifier.
For alignment, you want also to include thewidth specifier(minimum number of characters to be printed, padded with spaces if less are available). This should include the decimal point and the precision digits. So if the integer part oft2will fit when printed in 2 characters, you will need to set the width to 4. For the given example, this should work:
```
printf("%11dhr %4.1fmn", t, t2);
```
|
This question already has answers here:Does strtok work with strings (as the delimiter)? [closed](2 answers)Closed7 years ago.
I need some clarification about the functionstrtok()
Lets say my delimiter is a string that is"SEP"
And I have a string that is like this:char str[100] = "var1SEPvar2SEPvar3SEPvar4";
Would doingstrtok(str, "SEP");
Give mevar1, var2, var3, var4
?
|
Yes, the result will be as you are expecting provided that the var1, var2, var3 and var4 contain neither character from the string"SEP".
That is the function does not search the word"SEP"in the source string. It considers each character in the string"SEP"like a delimiter character.
Otherwise you should use standard C functionstrstrto search string"SEP"yourself using the function.
|
How can I allocate withmallocand array of structures within and array of structures?
for expample:
```
struct car_t{
int price;
float kmsDriven;
};
struct garage_t{
int locationX;
int locationY;
struct car_t * car;
}
```
There's an array of garages, which every one of them has an array of cars.
|
You will have to use a loop:
```
#define N 42
#define M 17
struct garage_t *a = malloc(sizeof *a * N);
for (int i = 0; i < N; i++) {
a[i].car = malloc(sizeof (*a[i].car) * M);
}
```
|
I have been struggling with this. What I have found here on stackoverflow, and other places was to just do:
```
memcpy(&a, &b, sizeof(b));
```
But for me, that did not work. So I thought, I share what worked for me without any unexpected behavior.
|
Assume you have:
```
#define N 42
struct struct_name *a = malloc(sizeof *a * N); // allocate N objects
struct struct_name *b = malloc(sizeof *b * N); // allocate N objects
```
then the correctmemcpycall to copy the array of structure objects is:
```
memcpy(a, b, sizeof *a * N);
```
|
Given this c code:
```
char** names=(char**)malloc(count*sizeof(char*));
```
I want to convert it to NASM assembly code. Here is what I tried, but the code crashes:
```
mov eax, dword count
mov ebx, [eax*4] ;; i did times 4 because we clear stack by 4 bits or bytes?
push ebx
call _malloc
mov names, eax
add esp, 4
```
What doessizeof(char*)mean? which char pointer is the code addressing?
|
The reason it crashes is becausemov ebx, [eax*4]is accessing memory at addresseax * 4which is unlikely to be valid, and definitely not what you want anyway. To multiply by 4, you can uselea ebx, [eax*4]orshl eax, 2thenpush eax.
PS: Learn to use a debugger.
|
I could easily print what I wanted in a loop, but I'm new to functions and I need to save or return the sum of the dividers that have no remainder to a number which is an input of the user.
Example:
Input -6
Output -1+2+3=6
How I started:
```
int NumberOfDividers(int number)
{
int i,num, count = 0;
num = number;
for ( i = 0; i < num; i++)
{
if ((num % i) == 0) //so now I know i is one of the dividers i want to save.
}
}
```
So ifiis one of the dividers I want, how can I save it into a variable? Or an array?
|
To return the sum of the proper divisors, do:
```
int sum_of_proper_divisors (int number)
{
int sum = 0;
int i;
for (i = 1; i < number; i++)
{
if ((number % i) == 0)
sum += i;
}
return sum;
}
```
You just need to use the return keyword to return the value.
|
I'm trying to align multiple variables in a table like output.
I am currently using padding but I can not see how to correctly align the output.
I print the variables:
```
printf("\n %15s", name);
printf("%15d", level);
```
Then I call the next function repeatedly, all is fine unless there is more than one digit.
```
printf("%11dhr %.1fmn",t,t2);
```
|
Having the variables defined asint t;andfloat t2;(ordouble t2;), as it is now%.1fprintst2withonedigit after the decimal point. This is theprecision specifier.
For alignment, you want also to include thewidth specifier(minimum number of characters to be printed, padded with spaces if less are available). This should include the decimal point and the precision digits. So if the integer part oft2will fit when printed in 2 characters, you will need to set the width to 4. For the given example, this should work:
```
printf("%11dhr %4.1fmn", t, t2);
```
|
This question already has answers here:Does strtok work with strings (as the delimiter)? [closed](2 answers)Closed7 years ago.
I need some clarification about the functionstrtok()
Lets say my delimiter is a string that is"SEP"
And I have a string that is like this:char str[100] = "var1SEPvar2SEPvar3SEPvar4";
Would doingstrtok(str, "SEP");
Give mevar1, var2, var3, var4
?
|
Yes, the result will be as you are expecting provided that the var1, var2, var3 and var4 contain neither character from the string"SEP".
That is the function does not search the word"SEP"in the source string. It considers each character in the string"SEP"like a delimiter character.
Otherwise you should use standard C functionstrstrto search string"SEP"yourself using the function.
|
Given this c code:
```
char** names=(char**)malloc(count*sizeof(char*));
```
I want to convert it to NASM assembly code. Here is what I tried, but the code crashes:
```
mov eax, dword count
mov ebx, [eax*4] ;; i did times 4 because we clear stack by 4 bits or bytes?
push ebx
call _malloc
mov names, eax
add esp, 4
```
What doessizeof(char*)mean? which char pointer is the code addressing?
|
The reason it crashes is becausemov ebx, [eax*4]is accessing memory at addresseax * 4which is unlikely to be valid, and definitely not what you want anyway. To multiply by 4, you can uselea ebx, [eax*4]orshl eax, 2thenpush eax.
PS: Learn to use a debugger.
|
I could easily print what I wanted in a loop, but I'm new to functions and I need to save or return the sum of the dividers that have no remainder to a number which is an input of the user.
Example:
Input -6
Output -1+2+3=6
How I started:
```
int NumberOfDividers(int number)
{
int i,num, count = 0;
num = number;
for ( i = 0; i < num; i++)
{
if ((num % i) == 0) //so now I know i is one of the dividers i want to save.
}
}
```
So ifiis one of the dividers I want, how can I save it into a variable? Or an array?
|
To return the sum of the proper divisors, do:
```
int sum_of_proper_divisors (int number)
{
int sum = 0;
int i;
for (i = 1; i < number; i++)
{
if ((number % i) == 0)
sum += i;
}
return sum;
}
```
You just need to use the return keyword to return the value.
|
I'm trying to align multiple variables in a table like output.
I am currently using padding but I can not see how to correctly align the output.
I print the variables:
```
printf("\n %15s", name);
printf("%15d", level);
```
Then I call the next function repeatedly, all is fine unless there is more than one digit.
```
printf("%11dhr %.1fmn",t,t2);
```
|
Having the variables defined asint t;andfloat t2;(ordouble t2;), as it is now%.1fprintst2withonedigit after the decimal point. This is theprecision specifier.
For alignment, you want also to include thewidth specifier(minimum number of characters to be printed, padded with spaces if less are available). This should include the decimal point and the precision digits. So if the integer part oft2will fit when printed in 2 characters, you will need to set the width to 4. For the given example, this should work:
```
printf("%11dhr %4.1fmn", t, t2);
```
|
This question already has answers here:Does strtok work with strings (as the delimiter)? [closed](2 answers)Closed7 years ago.
I need some clarification about the functionstrtok()
Lets say my delimiter is a string that is"SEP"
And I have a string that is like this:char str[100] = "var1SEPvar2SEPvar3SEPvar4";
Would doingstrtok(str, "SEP");
Give mevar1, var2, var3, var4
?
|
Yes, the result will be as you are expecting provided that the var1, var2, var3 and var4 contain neither character from the string"SEP".
That is the function does not search the word"SEP"in the source string. It considers each character in the string"SEP"like a delimiter character.
Otherwise you should use standard C functionstrstrto search string"SEP"yourself using the function.
|
This question already has an answer here:Warning given a value of unsigned long long variable in C(1 answer)Closed7 years ago.
I declared a variable of type long long and I assigned to itLLONG_MIN, but I'm not allowed to do it.
ft_long_long_to_ascii_base.c:23:14: error: integer constant is so large that it is unsigned [-Werror]
```
if (val == -9223372036854775808)
```
|
Rather than guess whatLLONG_MINmay be, use the macro supplied
```
#include <stdint.h>
if (val == LLONG_MIN)
```
|
I want to get the height for a certain latitude/longitude pair from the NASA SRTM dataset (http://dds.cr.usgs.gov/srtm/version2_1/SRTM3/Eurasia/).
As a starter I want to get all heights from a HGT file:
```
int totalPx = 1201; //3 degree
char buffer[2];
for (int i=0; i<totalPx; i++)
{
for (int j=0; j<totalPx; j++)
{
int pos = (i * totalPx + j) * 2;
m_openedFile.seek(pos); //m_openedFile is a Qt QFile
m_openedFile.read(buffer, 2);
short h = 0 | (buffer[0] << 8) | (buffer[1] << 0);
if (h < 0)
printf("%d", h);
}
}
```
This seems to work for some coordinates (e.g. the height values look plausible) but there are also many negative height values. How can I correctly read the SRTM/HGT file?
Regards,
|
Beware of sign extension when convertingchartoint
```
// char buffer[2];
unsigned char buffer[2];
short h = buffer[0] << 8 | buffer[1];
```
|
I have a library with c code, and I want to compile it to a .so lib with NDK, but when I run ndk-build command, it needs header file and there is no header file in that library, only dot c.
There are so many source files, and how can I achieve this with it?
Is there a way to compile it without header-file?
Or maybe generate them in batches?
Thanks
|
You cannot compile a c/cpp file without having access to the header files it requires. Some default header files are usually provided by the corresponding stdlibc which ships with the compiler you use. Others you have to provide yourself by installing their libraries in appropriate paths or giving their path explicitly during compilation.
Generally header files are included by the pre-processor, prior to compilation, as they provide some functionality which is required by the code within the c file (except when they are pointless includes).
|
According tognu(https://gcc.gnu.org/onlinedocs/gcc-4.9.2/gcc/Function-Attributes.html) noclone attribute is defined as:
This function attribute prevents a function from being considered for cloning—a mechanism that produces specialized copies of functions and which is (currently) performed by interprocedural constant propagation.
What does above definition imply aboutwhenandwherewe should use this function attribute?
|
I know two use cases of this attribute, both are very specific to gcc. These are:
If you take address of a label (GNU extension), the address will
differ between the function specializations if function body is
cloned. You should use the attribute if you expect addresses to be
the same.__builtin_return_addressmay return different return addresses, while without cloning they would be the same.
I advise not to use this attribute and let optimizer do its job.
|
How to get only the integer part of float? So, I have a float array: x[4] = {5.0, 13.0, 25.0, 41.0}; I'm putting it in xmm0 and then I'm making sqrt of it. I need one more command which will help to take only int part of this sqrt. For example sqrt of 5 will be 2.236068 and I need just 2.0 in an answerCode:
```
__asm
{
movups xmm0, x
sqrtps xmm0, xmm0
//here need some command
movups x, xmm0
}
```
|
Usingroundpsis the easiest. The rounding mode table is somewhere else but you need rounding mode 3 (towards zero).
Converting to an integer and back only works if the input is guaranteed to be in some range (about 0 to 4.6e18 because of the square root). You could do this withcvttps2dqandcvtdq2ps. That will only require SSE2,roundpsrequires SSE4.1. You can usecvtps2dqonly if the rounding mode is set to truncate, which it usually isn't, so you'd have to change+restore it.
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question
INPUT
Integers (0 ≤ Integer < 10^1,000,000)
OUTPUT
Find input mod 3 and input mod 11
EXAMPLE
```
main(){
int num;//problem here i try long long not pass because it not enough.
scanf("%d",&num);
printf("%d ",num%3);
printf("%d",num%11);
}
```
|
"Normal types in C can usually only store up to 64 bits, so you'll have to store big numbers in an array, for example, and write mathematical operations yourself. But you shouldn't reinvent the wheel here - you could try the GNU Multiple Precision Arithmetic Library for this purpose."
-AndiDog
Source:Store and work with Big numbers in C
|
When accessing a pointer variable of a pointer object, how does the syntax work? Do I need two*?
Here's an example to explain my situation better:
```
void function(ofObject *object) //passing by ref so that I can change it
{
int n;
n=*object.*x; //object is a pointer, but so is the class member x;
}
```
If I just put the*at the beginning, then*object.xwould simply return the address ofobject.x, wouldn't it? Or would it? Am I just overthinking this?
|
The*operator has lower precedence than the.operator, so*object.xwill be a compiler error since it's the same as*(object.x). This is what the->operator exists for.object->xis the same as(*object).x. IfofObject::xis a pointer, you can then dereference it using the*operator as normal. So putting it all together, to dereference a pointer member through a pointer, you can use*object->x.
|
I tried to solve a problem but I don't know if it's the good solution.
Build a mask of type unsigned long with the 14 least significant bits (from the right) set to 1;
```
#include <stdio.h>
#include <stdlib.h>
unsigned long mask;
int main()
{
int i;
for(i=0;i<14;i++)
mask|=(1<<i);
printf("%li",mask);
return 0;
}
```
|
It is better
```
#include <stdio.h>
#include <stdlib.h>
unsigned long mask;
int main()
{
int num = 14;
mask = (1 << num) - 1;
printf("%lu", mask);
return 0;
}
```
Herenumis total number of least significant bits.
How it Works
Binary representation of 2^14 = 16348 is0000000000000000 0100000000000000(In 32 bit)
and
binary representation of 2^14-1 = 16347 is0000000000000000 0011111111111111
So 14 least significant bits set to 1.
|
I'm trying to write a simple code that reads 20 numbers and then prints them in reverse order.
The code is the following.
```
int main(){
int array[20];
int i;
for (i=0; i<20; i++) scanf("%d", &array[i]);
for (i=20; i > 0; i++) printf("%d\n", array[i]);
}
```
I can't figure out why after I insert the numbers instead of printing them it gives me a segmentation fault (11)
|
You have 3 problems with the secondfor-loop:
it starts at 20 (which would get the 21th element)you want to decrement i instead of incrementI believe you also want to display the first element at position 0 (so>=0instead of>0)
for (i = 19; i >= 0; i--) printf("%d\n", array[i]);
|
I want to use-fopenmpin MINX 3, and when I write down the command:gcc -fopenmp test.c -o test.outit shows me this error:
cc1: error: unrecognized command line option "-fopenmp"
the GCC version of Minix 3 that i am using is GCC 4.1.1. I have to use an old version of Minix, and this is the only version of GCC that it has.
Can the problem be that the version of GCC doesn't have-fopenmp??
|
If you go toGCC's webpage, you will find that the first version of the compiler supporting OpenMP was GCC 4.2, with OpenMP 2.5.
OpenMP 3.0 (with tasking support) was added in GCC 4.4.
OpenMP 4.0 (with dependent tasks) was added in GCC 4.9.
|
I'm working on a C project, with client/server syslog communication with a Rpi. I have been asked to use syslog ng and I'd like to access to timestamp.
From what I foundhere:
Where the timestamp comes from depends on the type of log data you’re sending through.
Plus :
If your data is forwarded by a syslog service, there is a timestamp embedded in the header that we can pull out and use.
So it's possible to pull out the timestamp. But how ?
|
If you use syslog-ng, it handles two different time stamps:
the one, when the message was actually receivedthe one included in the syslog message
These are accessible through macros. You can read more about it athttps://www.balabit.com/sites/default/files/documents/syslog-ng-ose-3.7-guides/en/syslog-ng-ose-v3.7-guide-admin/html-single/index.html#reference-macros
|
what's the behavior the following condition :
```
if (VALUE & 0xFF00) {
// execute code
}
```
shouldVALUEbe equal to0xFF00or any positive result like0xF000led to execute the condition body?
|
In the range of 16-bit integer values, any value between 0x0100 and 0xFFFF will lead to the body of theifbeing executed. Values between 0x0000 and 0x00FF do not have any of bits 8 to 15 set, so the condition evaluates to false and the block of code is not executed.
For larger numbers, any valuevsuch thatv % 65536has a remainder in the range 0x0100..0xFFFF will lead to the body of theifbeing executed.
Basically, if at least one of the bits in positions 8-15 is set, the code will be executed.
Note that the code is treated as if the condition was written:
```
if ((VALUE & 0xFF00) != 0)
```
Indeed, any expressionif (x)is treated as if it were writtenif ((x) != 0)for any simple type of variable: integer, floating point, pointer.
|
I have four parameters, each an integer and I want to find the smallest. What is the quickest and/or simplest way to do it? I can probably do a bubble sort but it seems overkill.
|
```
int min(int a, int b){
return a<b?a:b;
}
```
call as:
```
min(min(a,b),min(c,d))
```
|
This question already has answers here:Undefined reference to pthread_create in Linux(16 answers)Closed7 years ago.
I am writing a c code on ubuntu that creates a certain number of threads
I have already added pthreads library but when I run the code
it ends up with this error
Threads.cc:(.text+0x128): undefined reference to 'pthread_create'
Threads.cc:(.text+0x15b): undefined reference to 'pthread_join'
I am using ubuntu 15.04 virtual machine.
I have tried many suggested solutions, non of them worked!
any help would be appreciated
|
I have already added pthreads library [..]
No. You haven't. If you did you wouldn't get this problem. You probably mean to say you included<pthread.h>. But that doesn't link with pthreads library.
Addpthreadat the end of your compilation options. For example,
```
gcc -o out myfile.c -pthread
```
|
I want my configure script to run a custom compiler.autoconfknows nothing about this language, soAC_TRY_COMPILEwon't do.
If I simply run the compiler without using macros, its stderr is printed to terminal, however, I want to do the same redirections as for C compiler and be affected by--quietflag.
Standard macros do something like:
```
$CC ... 2>conftest.err
cat conftest.err >&5
```
but it's not documented.
|
There's the documented macro forconfig.logfile descriptor:AS_MESSAGE_LOG_FD
https://www.gnu.org/software/autoconf/manual/autoconf-2.69/html_node/File-Descriptor-Macros.html#AS_MESSAGE_LOG_FD
usage example:
```
echo foobar >&AS_MESSAGE_LOG_FD
```
|
To my knowledge, there is no libc equivalent togetline()that works with a file descriptor instead of working with aFILE *.
Is there a (technical) reason for that?
|
You can create a FILE stream out of a filedescriptor withfdopen.
To generically get a line out of a file descriptor, you'd need to ask the OS for one character at a time and that is very inefficient. (Thereadbuiltin in POSIX shells works like this—it reads lines very inefficiently by retrieving a byte at a time.)
FILE streams ask for data from the OS in batches, which improves efficiency, however the file descriptor might not be a rewindable file—it might be a socket or a pipe and if you ask for 100 characters and the third character of that 100 batch is the newline character, then there's no way to generically undo the read of the 97 characters after it.
|
I am using GDB to debug a Cortex-M0 processor. Using the normal default text interface, I can do it just fine.monitor reset haltis needed to restart the processor. Otherwise, I need to reset my debugging interface that the processor is attached to (OpenOCD through an ST/Link-V2).
I am trying to use the MI interpreter to automate this a bit, but have been oddly unable to figure out how this is done using the MI commands. Seems simple enough, but after reading through every page of the manual, I must have missed it.
I am using GCC-ARM 4.9.2015q3 fromhttps://launchpad.net/gcc-arm-embedded/+download.
|
You can always send a CLI command to the MI interpreter. It can be done directly (just sendmonitor reset halt) or using-interpreter-exec. The latter form is preferred, at least according to the gdb manual.
|
How do I free up memory based on these conditions?:
If used memory is < 25% of the capacity of the system, free up 50% of unused memory.
Here is my code attempt:
main method
attempt at conditional memory free-up
|
Your problem seems to be
```
if(rand() % 1 > 0) {
```
rand() % 1is always0
Change to:
```
if(rand() % 2 > 0) {
```
And there is a typo in:
```
while(current = !NULL) {
```
change to
```
while(current != NULL) {
```
Don't forget to reconnectnextnode to the previous one in the loop , use a temp node, something like:
```
temp = current;
while (current != NULL) {
next = current->next;
if (rand() % 2 > 0) {
temp->next = next;
free(current);
} else {
temp = current;
}
current = next;
}
```
|
In C I'm trying to read a line data from a file and save it.
I think i'm opening it properly but when I try to print it, it isn't working properly
example: I'm trying to read a line with:
```
20 3.1 U
```
I'm using fscanf but it is only reading the first data properly.
What I've been trying
```
fscanf(fr, "%d","%f","%s",&age, &grade, class);
```
Am I getting the parameter format wrong?
When I only do the first parameter it works fine
```
fscanf(fr, "%d",&age, &grade, class);
```
I'm trying to use printf to print
```
printf("%d","%f","%s",age, grade, class);
```
only age is printing properly
|
Your format specifiers for bothfscanfandprintfneed to be a single string.
So for example, the following might work for you:
```
fscanf(fr, "%d%f%s", &age, &grade, class);
```
and
```
printf("%d, %f, %s", age, grade, class);
```
|
I do not understand why after creating directorymkdirreturn different values. In this example i'm trying to make a directoryif notso error handleotherwisego to this directoryif notso error handle.
But it's not working as I want!
It shows me 'failed to create' but actually creates the directory.
If I read reference right it returns 0 when successes.
Code:
```
char* dirName = "Output";
FILE *output;
if(!mkdir(dirName))
if(chdir(dirName))
printf("Permission to open a new directory is denied");
else
printf("Permission to create a new directory is denied");
```
|
It looks like you need curly braces around theifstatement bodies so that theelseis bound to the correctifstatement.
|
So I'm doing communication between server and client in C. I'm having issues with searching for it on the web how to do the following.
```
./server -p 1234
./client -p 1234 -h asdffdsasdf
```
Can someone describe the basics of doing it inside the project or is it included in the Makefile??(Using Putty terminal).
Or show me a website where it is explained very well, because I dont know what to google for this.
Thanks a lot!
|
You need to use program startup arguments; seeStandard 5.1.2.2.1.
For example
```
#include <string.h>
int main(int argc, char **argv) {
if (argc >= 2) {
if (strcmp(argv[1], "-p") == 0) /* -p detected */;
}
return 0;
}
```
TLDR: just read the title
|
I'm trying to get the runtime of a given process in kernel space or user space.
Anyway here is what i'm trying to do...
```
//suppose struct task_struct *task has a direct link to pid 1
cputime_t ktime = task->cputime_expires.stime;
cputime_t utime = task->cputime_expires.utime;
cputime_t total = ktime + utime;
printk(KERN_INFO "TOTAL [%lu]",total); // 0
```
why the output is zero ?
|
We'll get process runtime fromtask->utime,task->stime, etc.
Check functionaccount_process_tick()source.
The one you have mentioned i.etask->cputime_expiresis used fortimer_settime()system call to arm a POSIX per-process timer.
|
I recently built a project on VisualStudio. I got an executable in the bin folder and I put all the dependencies x64 DLL inC:\Windows\System32and all the x32 DLL inC:\Windows\SysWOW64
When I execute my executable, I get an error messageThis program can't start because foo.dll is missing from your computer.
I tried to get the dependencies withldd.exeon Cygwin, but I don't see any references tofoo.dll. I also tried to execute from PowerShellStart-Process -PassThru sample.exe, but I still get the same error message.
Where does Windows executables look for DLLs?
I've read that a Windows executable will look for its dependencies in a certain order:
In the local folderIn System32In the %PATH%
I also read that I may need to useregsvr32.exeto register my DLL if it is located into System32.
What is the actual reality of this story?
|
Alternatively, you can simply add the DLL files to the bin folder as well.
|
I'm coding in C with microcontrollers as part of degree and am struggling to find the base address of different components. The microcontroller I am using is the MSP430FR413x and I am currently trying to figure out the base address of the LCD screen so that I can display some text. Could anyone help me either with how to find the base address or what this base address is. Thanks!
|
In the datasheet (http://www.ti.com/lit/ds/symlink/msp430fr4133.pdf) on page 70 they say, that the LCD driver's registers are at0x600. Is that what You are looking for?
|
I am trying to open an absolute path of a PCI device in C code
```
fd = open("/sys/bus/pci/devices/0000:00:01.0/resource", O_RDWR);
if (fd < 0) {
printf("Not found %s\n", path);
return -1;
}
```
But it gives me an error saying Not found /sys/bus/pci/devices/0000:00:01.0/resource
Can anyone please point me out what I am doing here?
|
You are trying to open the path for read/write, but it is only readable (that's what the-r--r--r--inls -loutput means). You'll need to changeO_RDWRtoO_RDONLY.
|
I start working with the termcaps and i saw this kind of operation.
term.c_lflag &= ~(ICANON);
I know&=is abinary AND, and i am not very confortable with it.
Why didn't simply use=or make a#define, and what the&= ~do ?
|
AssumingICANONis a bit-mask, i.e. an integer with bits set to represent some feature, that statement will make sure those bits arenotset inc_lflag.
This is often called "masking off" those bits.
The operation is a bitwise AND with the bitwise inverse (~is bitwise inverse).
So, if the value ofc_lflagis 3 (binary 112) before the operation, andICANONhas the value 2 (binary 102), it will become 1 since it's bitwise-AND:ed with the value~2which has all bits set except bit number 1 (binary ...111012).
It could also be written more verbosely as
```
term.c_lflag = term.c_lflag & ~ICANON;
```
The parentheses aroundICANONshould not be needed.
|
For a student course in c,I want to know if it is possible to use the max width flag identifiers
as an integer you get from the user
example :first iteration of the loop :
```
printf("%7d\n",Number)
```
second iteration of the loop :
```
printf("%6d\n",Number)
```
Third iteration of the loop :
```
printf("%5d\n",Number)
```
and so on... I want to know if it is possible to use something like this:
```
int i;
int userWidthInput=10;
for(i=userWidthInput; i>1;i--)
{
printf("%userWidthInputd\n",Number);
}
```
|
Why not, use like
```
printf("%*d\n",width, Number);
```
So, your code might looks as follow:
```
int i;
int userWidthInput=10;
int Number = 10;
for(i=userWidthInput; i>1;i--)
{
printf("%*d\n",i , Number);
}
```
|
I came accros this line of code:
```
#define BWAKUP ('w' << 8)
```
What does it do? Its the same as:
```
#define BWAKUP (167000)
```
In addition, another definition as :
```
#define CWAKUP (1 + BWAKUP)
```
is equivalent to :
```
#define CWAKUP (356000)
```
Right ?
|
This line define a macroBWAKUPwhich expands to the expression('w' << 8). That expression has, assuming your platform uses ASCII, the value 119 · 256 = 30464 which is not equal to167000.Similarly,CWAKUPexpands to(1 + ('w' << 8))with the numeric value 30465, again assuming your system uses ASCII.
Without more context I can't tell you what the meaning of these macros is.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.