question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
Q: Here is my Makefile fragment below:
```
SRCS+=$(wildcard *.c *.cpp)
OBJECTS=$(addprefix $(OBJ_DIR)/, $(patsubst %.c,%.o,$(SRCS:.cpp=.o)))
# .....
$(OBJ_DIR)/%.o: %.cpp
$(CXX) -ggdb -Wall -Wextra -Werror $(INC) $(C_FLAGS) -c -o $@ $<
$(OBJ_DIR)/%.o: %.c
$(CC) -ggdb -Wall -Wextra -Werror $(INC) $(C_FLAGS) -c -o $@ $<
```
How can I refactor expression after "OBJECTS" and remove duplication of the similar rules for .cpp and .%c?
|
```
OBJECTS := $(patsubst %,$(OBJ_DIR)/%.o,$(basename $(SRCS)))
# Note that you may not need this variable at all.
COMPILE_ARGS = -ggdb -Wall -Wextra -Werror $(INC) $(C_FLAGS) -c -o $@ $<
$(OBJ_DIR)/%.o: %.cpp
$(CXX) $(COMPILE_ARGS)
$(OBJ_DIR)/%.o: %.c
$(CC) $(COMPILE_ARGS)
```
|
This question already has answers here:bit-wise operation unary ~ (invert)(5 answers)Closed8 years ago.
```
int x=10;
cout<<~x;
```
this code prints -11. if it was simple inversion then for 00001010 the bits should be 11110101, which on conversion to decimal is -117. I have tried searching but no luck pls tell what is happening here?
I am using mingw compiler, if its of any help.
|
That is working as expected. "11110101" is -11 in two's complement.
As a side note, "int" is either 16 or 32 bits, so you're actually talking about
"00000000 00001010" or "00000000 00000000 00000000 00001010" respectively.
|
Why is the first condition a=4 considered as true and b=0 is treated as false in the below if condition ?
```
#include <stdio.h>
int main()
{
int a,b;
if(a=4)
printf("a=4 --> true");
else
printf("a=4 --> false");
if(b=0)
printf("\nb=0 --> true");
else
printf("\nb=0 --> false");
printf("\n");
}
```
Output:
```
a=4 --> true
b=0 --> false
```
|
In both C and C++ language, any non-zero value is treated astrue. Inifcondition you are assigning4and0toaandbcausing the value of expressionsa = 4andb = 0to be4and0respectively.
|
How could I modify the line bellow in ANSI C without using theunsignedmark?
```
unsigned int x, y, z; // unsigned variables should not be used
/*... some operations where x, y and z gets values between 0x0 and 0xFFFFFFFF ... */
x = (unsigned int)-(int)(y * z); // line to modify
```
|
You can directly apply negation to an unsigned value. The result will be reduced modulo 2^N, which is what your existing code does anyway.
```
x = -(y * z);
```
|
Suppose I use the followingprintf()specifier string:
```
printf("%.*s", length, str);
```
which asksprintf()toprint the firstlengthcharacters instr. The question is which typelengthhas? I only see brief mentions ofinteger numberin the documentation.
So it looks like it isint. Then it looks like I cannot use the following code when a string is very long:
```
const char* startOfString = ...
const char* middleOfString = ...
printf("%.*s", (int)( middleOfString - startOfString ), startOfString);
```
It looks like I cannot output more thanINT_MAXcharacters this way.
So which type isprecision? Is itintor is itsize_tor anything else?
|
It's anint, and you cannot print more thanINT_MAXcharacters that way.
From the C standard, § 7.21.6.1, para. 5:
a field width, or precision, or both, may be indicated by an asterisk. In
this case, anintargument supplies the field width or precision.
|
I was trying to fill an array,xlow, by extracting some elements from an array called exit_2. By making the array xlow, I wanted access specific elements of it but the code gives some weird numbers.
```
#include <stdio.h>
int main()
{
int exit_1[4]={3,0,7,11},exit_2[4]={90,164,232,328},xlow[2],i;
for(i=0;i<4;++i){
if(exit_1[i]<7){
xlow[2]=exit_2[i];
}
}
printf("%d",xlow[0]);
return 0;
}
```
Thank you your help
|
```
xlow[2]=exit_2[i];
```
As you see you are initializingxlow[2].xlow[0]is still uninitialized and using uninitialized variables lead to undefined behavior.
```
int j=0;
for(i=0;i<4;++i){
if(exit_1[i]<7){
if(j>1)
break;
else
xlow[j++]=exit_2[i];
}
}
```
|
```
#include <stdio.h>
int main(void)
{
printf("What is the sum of 5 + 5?\n");
GetInt();
if int == 10;
printf("Correct.\n");
}
```
|
```
#include <stdio.h>
int main(void)
{
printf("What is the sum of 5 + 5?\n");
GetInt();
if(int == 10){
printf("Correct.\n");
}
return 0;
}
```
GetInt()is undefined, you also have some very basic syntax errors(that I've corrected) for exampleif int == 10;intis a data type you can't compare it to a number and even if you could by putting a;at the end you basically putting and empty conditional, it won't do anything.
```
#include <stdio.h>
int main(void)
{
int a;
printf("What is the sum of 5 + 5?\n");
scanf("%d", &a);
if(a == 10){
printf("Correct.\n");
}
return 0;
}
```
This is what you want, now you should really read back the basics of C.
|
I'm a bit new to structs and just wondering if these two structs are equivalent. I dont know if this is relevant, but im using these structs to build a stack.
Is this:
```
struct dataT
{
int m;
};
struct stack
{
int top;
struct dataT items[100];
} st;
```
equivalent to this?
```
struct stack
{
int top;
int items[100];
} st;
```
Arent these basically the same? The second method only uses one struct.
If im wrong, could you please tell me why it is not.
|
It will make a difference if you ever decide to change thedataTstructure. If you know that it will always be only a wrapper forint, then it is a pretty useless structure. But if it may change, then the top one will probably be easier to maintain.
|
I am building a Raspberry Pi2 cluster (aka a bramble) with MPICH2 1.4.
I also have a Launchpad, which is a board of 64+ buttons, each of which can light up with 3 different colors.
From what I understand, by sending a midi note to it, you can light any key up, and the color depends on the velocity of the midi note.
What I want to do, is I want to visualize how the data is passing from Pi to Pi by using the launchpad, but have no idea how to pass the midi note to the Launchpad using C only.
If someone could point me in the right direction, I would be forever grateful!
Thank you in advance,
-Alex
|
You could let somebody else do the work:
```
system("amidi -p hw:1 -S '90 12 34'");
```
Or write the MIDI bytes directly to/dev/midiXX(if the kernel has OSS emulation).
Or use thesnd_rawmidi_*functions to access the device directly (see theamidi sourcefor details).
|
I have the following code:
```
char* input = (char*)malloc(sizeof(char) * BUFFER) // buffer is defined to 100
int digit = atoi(input); // convert char into a digit
int digit_check = 0;
digit_check += digit % 10; // get last value of digit
```
When I run the input 1234567896 and similarly digit = 1234567896 and digit_check = 6.
However when I run the input 9999999998, digit = 1410065406 and therefore digit_check = 6 when it should be 8.
For the second example, why is there a difference between input and digit when it should be the same value?
|
Probably because 9999999998 is bigger then the maximum (signed) integer representation, so you get an overflow.
In fact this is the binary representation of 9999999998 and 1410065406:
```
10 01010100 00001011 11100011 11111110
01010100 00001011 11100011 11111110
```
As you can see if you see 1410065406 is the 32ed bit value of 9999999998
|
I need to verify that the expressiongetchar() ! = EOFis0or1.
My current code:
```
#include <stdio.h>
int main (int argc, char *argv[])
{
int c;
while (( c= getchar()) != EOF)
{
printf("%d ", c != EOF);
putchar(c);
}
printf("\n%d\n", c != EOF);
}
```
When I try to run that I get
```
98980980
1 91 81 91 81 01 91 81 01
```
I`m not sure if I got this right.
EDIT:
Ok the question was actually " How to generate EOF "
and the solution was to press ctrl+D.
|
I'm not very sure if you want this answer, but as per my understanding, what information you're looking for is
If you input anyvalid character,getchar() != EOFyields 1.If you pressCTRL+D(on linux), orCTRL+Z(on windows), it will generateEOFandgetchar() != EOFyields 0.
|
If I had a method
```
int main(int argc, char* argv[]) {
```
I am under the impression that calling arguments and receiving data through standard input are somewhat the same things. What is the difference between adding the arguments "1 2 3 4" and receiving standard input "5 6 7 8"? and when would you pick one method over the other?
|
The difference is in how you access them.
Arguments are accessible throughargv. Standard input is accessible through thestdinfile descriptor.
case 1 - command line arguments:
```
int i;
for (i=1; i < argc; i++) {
printf("%s", argv[i]); // Prints "1 2 3 4"
}
```
case 2 - standard input:
```
char buffer[121];
while (scanf("%120s", buffer) == 1) {
printf("%s", buffer); // Prints "5 6 7 8"
}
```
|
I wrote this code to get the gcd in c. It works perfectly for small numbers
but when I tried 60 and 90 for example I got 2, while getting 3 for 9 &6.
```
#include "stdio.h"
#include "stdlib.h"
int main()
{
int a,b,x,gcd;
printf("Please Enter the fraction");
scanf("%d", &a);
scanf("%d", &b);
if(b%a == 0)
gcd =a;
else
{
x=a;
while(--x>1)
{
if (a%x == 0 && b%x==0)
{
gcd =x;
}
}
}
printf("GCD = %d", gcd);
return 0;
}
```
|
You need to break the loop if the condition in the secondifis true. Just addbreak;in the body of the secondif:
```
if (a%x == 0 && b%x==0)
gcd =x;
```
should be
```
if (a%x == 0 && b%x==0)
{
gcd =x;
break;
}
```
Otherwise the loop goes on and finds the lowest-common-divisor greater than 1.
|
I want to calculate the value of the mask dynamically based on bit position.
For Example: The mask value for the 17th bit in a 32-bit value is 0x00020000 and that of the 18th bit is 0x00040000. So if I know the bit positions like 17, 18 etc., how can this be converted dynamically to mask values in C? Of course left shifting is one method (1<<17or1<<18). But I am thinking left shifting may consume too many instructions! Or is left shifting itself the best and efficient method?
|
Basically, it won't consume too many instructions. What you are doing may be fine in one operation. Here is an answer that explains this on SO:Which is faster: x<<1 or x<<10?Basically there is no difference in speed.
Please see this answer on SO too for implementations:How do you set, clear, and toggle a single bit?
|
I thought externs were to share variables between compilation units. Why does the below code work ? and how does it work exactly ? Is this good practice ?
```
#include <stdio.h>
int x = 50;
int main(void){
int x = 10;
printf("Value of local x is %d\n", x);
{
extern int x;
printf("Value of global x is %d\n", x);
}
return 0;
}
```
Prints out :
```
Value of local x is 10
Value of global x is 50
```
|
When you use theexternkeyword, the linker finds a symbol with a matching name in object files / libraries / archives. Symbols are, simply speaking, functions and global variables (local variables are just some space on the stack), thus the linker can do it's magic here.
About it being a good practice - global variables in general are not considered a good practice since they cause spaghetti code and 'pollute' the symbols pool.
|
Installation:
```
bzip2 -d valgrind-3.10.1.tar.bz2
tar -xf valgrind-3.10.1.tar
```
then:
```
./configure
make
make install
```
or simplier
```
sudo apt-get install valgrind
```
How to run valgrind on that simple program example1.c
```
#include <stdlib.h>
int main()
{
char *x = malloc(100); /* or, in C++, "char *x = new char[100] */
return 0;
}
```
Run:
```
valgrind --tool=memcheck --leak-check=yes example1
valgrind: example1: command not found
```
Output from console:
```
valgrind: example1: command not found
```
|
It looks good. You only need to add a./before your executable. Without it,valgrindfails to find it and reports'command not found'.
```
valgrind --tool=memcheck --leak-check=yes ./example1
^
```
|
The followingflexsource file generates a scanner that appears to overwrite the first two bytes of thestdinbuffer with null bytes once it's done tokenizing it. Is that expected behavior?
```
%{
const char *firstChar;
%}
%%
.* firstChar = yytext;
<<EOF>> return 0;
%%
int main(void){
yylex();
printf("%d %d\n", firstChar[0], firstChar[1]);
yylex_destroy();
return 0;
}
```
It captures the initial value ofyytextinfirstChar, and prints out the numeric values of its first two bytes after a call toyylex. Compiling and running the scanner:
```
$ flex example.l
$ gcc -o example lex.yy.c
$ echo -n "foobar" | ./example
0 0
```
|
yytextdoes not point into the 'stdinbuffer'. It points into a private buffer inside 'flex'. There is no guarantee anywhere about what 'flex' does or doesn't to to its own buffer. That's its business. You're supposed to copy data from it if you want to save it.
|
Context
Linux 64 bits
Question
Is it possible to instruct the stack to be zeroed before returning a function ?
I want not valid information left on the stack, even if overwritten right after by other values.
I explicitly want to waste some time doing so.
Is it possible in an automated mannerthat cannot be bypassedwhen compiled in a controlled environment ?
Thanks
|
One way would be to use the "-finstrument-functions" option. This allows you to hook in an entry and exit function for each regular function call entry and exit. You could clear the stack in the exit hook. As the name suggests its primarily intended for instrumentation. But nothing to stop you from using it for other purposes.
|
Can a child process change a static int shared by his parent process? Something similiar to this simple example:
```
static int changeMe = 1;
...
int main() {
if (fork()=0){
changeMe = 0;
}
wait(0);
printf(1, "changeMe value is: %d., changeMe);
}
```
I know the child creates a clone of the parent memory. But i actually want that the child will change values at its parent - Is it possible?
|
Not through fork, since you're creating a new process with a separate stack and address space. If you want to share variables, look at using threads.
|
im struggling with this so long, i can fill my array with random numbers
but they are not unique. I can't spot the problem in my code :( Can you help me? Thanks
```
int getUniqueNumber(int *p, int i)
{
int x,j,found;
do
{
x=rand()%100000 + 1;
found=0;
j=0;
while(j<=i && found==0)
{
if(p[i]==x)
found=1;
else
j++;
}
} while(found==1);
return x;
}
```
|
p[i] == xshould bep[j] == x.
|
So I'm following an online tutorial (on OS development if that matters) and I saw this line of c code void. Here's a simplified version:
```
void function1(struct regs *r) {
void (*handler)(struct regs *r); // What happened here?
// do things with void *handler
}
```
What happened in that line? It declared a variable
void *handler
but it did something like a cast? but it doesnt seem like a cast. What just happened there?
|
void (*handler)(struct regs *r);declareshandleras a pointer to a function that expects an argument of typestruct regs *and returns typevoid.
|
I am trying to use convert ASCII to Char in Android NDK but it gives me Fatal error for segement and my app force stops.
Code:
```
value = "116";
char word = atoi(value);
return (*env)->NewStringUTF(env, word);
```
Error:
```
Fatal signal 11 (SIGSEGV) at 0x00000074
```
|
You need to provideNewStringUTF()a c-string (i.e. an array ofcharwith an ending null):
```
value = "116";
char word[2];
word[0] = atoi(value); // first char converted as you want
word[1] = 0; // null termination (aka '\0')
return (*env)->NewStringUTF(env, word);
```
|
This is actually part of an assignment. Basically, we need to write a library, which will be linked against test programs the professor writes, like so:
```
gcc -o libexample.o -c libexample.c
ar rvs libexample.a libexample.o
#later
gcc -o test test.c -L . -lexample
```
The thing is that libexample uses POSIX semaphores, which needs linking with the pthread library when generating the final executable. Without changing the way test program compiles, is there a way to package the pthread library with libexample.a?
Thanks!
|
Without changing the way test program compiles, is there a way to package the pthread library with libexample.a?
No.
Are you restricted to supplying just the singlelibexample.afile?
If not (and if you are using GNU linker), a possible solution is to providelibexample.aas linker script, which will link against e.g.libexample_code.acontaining your object filesandadd-lpthread.
|
after compiling the hello.c ,when i try to run it using ./a.out ,it says the following
'.' is not recognized as an internal or external command,operable program or batch file.
here are the system variables
Path:C:\Windows\System32;C:\Windows;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Program Files\Java\jdk1.7.0_71\bin;C:\apache-maven-3.2.5\bin;C:\Program Files\MinGW\bin;
|
Rename a.out to a.exe and run it using .\a.exe or just a.exe
Make sure that the current directory contains a.exe
|
I was wondering if any of you would know the C equivelent of the powerpc instruction below.
```
rlwinm r31, r0, 0,13,13
```
Thanks.
|
Rotate left register immediate, thenandwith mask.
Rotate left is 0 here, so we can ignore this. The mask is all bits set from 13 to 13, which is just bit 13 (0x2000 as a bitmask; this command was probably chosen over justandto document that bit 13 is selected).
So in this case, we need to build a mask for bit 13 and then apply bitwiseandwith the source.
```
r31 = r0 & (1 << 13);
```
<<is the shift left operation in C, we use it here to create a mask just for bit 13.&is the and operation in C.
Documentation source:http://sametwice.com/rlwinm
|
Code:
```
void *PrintHello(void *threadid)
{
cout<<"Hello"<<endl;
sleep(3);
cout<<"Still PrintHello is alive"<<endl;
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
cout<<"Calling thread:"<<t<<endl;
pthread_create(&threads[0], NULL, PrintHello, NULL);
//pthread_join(threads[0],NULL);
cout<<"Main exits"<<endl;
pthread_exit(NULL);
}
```
Whypthread_exit(NULL)here acts likepthread_join()? i.e Why exitingmainnot destroying theprintHellothread and allowing it to continue?
|
pthread_exit()terminates only the calling thread. So when you call it frommain(), it terminates the main thread while allowing the process to continue. This is as expected.
If you callexit()(or an implicit exit from by returning) instead, it'll terminate the whole process and you will seeprintHelloterminated as well.
|
I have a small code
```
void *PrintHello(void *threadid)
{
cout<<"Hello"<<endl;
pthread_exit(NULL);
}
int main ()
{
pthread_t threads_id;
pthread_create(&threads_id, NULL, PrintHello, NULL);
int i=0;
for(;i<100;i++){cout<<"Hi"<<endl;}
pthread_join(threads_id,NULL);
return 0;
}
```
I am joining the thread sometime after creation. What will happen if the main tries to join a thread which already exited?
|
What will happen if the main tries to join a thread which already exited?
The join operation will immediately finish and return.
|
I have a big project. I want to find which all .cpp/.h files includefile1.hin them. Is there any shortcut key in Eclipse CDT to do this?
|
I'd suggest the Include Browser view. You can drag a file in there and you get a nice tree which shows all files that include your file, including indirect includes.
|
Seems like a trivial question, but I can seem to figure it out. How to make 2 outputs a certain distance appart regardless of size of first input?
For example this is my current output:
```
Dell $1200
Toshiba $2000
Sony Vaio $1000
```
The spaces are uneven when I print them out. I want the output to look like the following:
```
Dell $1200
Toshiba $2000
Sony Vaio $1000
```
Basically I want the distance to be the same between the 2 outputs regardless of the size of the first input.
This is my code:
```
printf("\nEnter a laptops name: ");
scanf("%s", &laptopName);
printf("Enter its price: ");
scanf("%d", &laptopPrice);
printf("\n");
printf("%s ", laptopName);
printf("$%d", laptopPrice);
```
|
Specify a field width (negative value to left align):
```
printf("%-20s %d", laptopName, laptopPrice)
```
|
To explain, I am not asking how to reap a process.
In C, the parent process must explicitly reap a created child, even if the child exited by performing an exit() function call.
I understand that while reaping the child, it may be necessary to obtain the exit status of the child.In fact, that is the only information that may be obtained from the child process. So, why does the OS not just store the exit status(an integer), but rather, still store all the memory associated with the child until reaped?
|
The premise of your question is wrong. The OSdoesstore just the exit status (and resource-usage-report), but most importantly of all, it also reserves the pid until you wait on it. This last part is important because, if the pid were reassigned to a new process before you waited on the original one, it would be impossible to use it as an identifier to request the exit status.
|
i have a functionisEmpty()and i want to replace it with with thisEmpty().
```
int isEmpty(char *s)
{ return s[0]=='\0';
}
```
Should i replace it like this?
```
#define isEmpty() Empty()
```
|
Given you have a functionisEmptyas defined, you need to pass a parameter to it:
```
#define Empty(s) isEmpty(s)
```
But you might want to achieve it without any function:
```
#define Empty(s) ((s)[0]=='\0')
```
|
This is actually part of an assignment. Basically, we need to write a library, which will be linked against test programs the professor writes, like so:
```
gcc -o libexample.o -c libexample.c
ar rvs libexample.a libexample.o
#later
gcc -o test test.c -L . -lexample
```
The thing is that libexample uses POSIX semaphores, which needs linking with the pthread library when generating the final executable. Without changing the way test program compiles, is there a way to package the pthread library with libexample.a?
Thanks!
|
Without changing the way test program compiles, is there a way to package the pthread library with libexample.a?
No.
Are you restricted to supplying just the singlelibexample.afile?
If not (and if you are using GNU linker), a possible solution is to providelibexample.aas linker script, which will link against e.g.libexample_code.acontaining your object filesandadd-lpthread.
|
after compiling the hello.c ,when i try to run it using ./a.out ,it says the following
'.' is not recognized as an internal or external command,operable program or batch file.
here are the system variables
Path:C:\Windows\System32;C:\Windows;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Program Files\Java\jdk1.7.0_71\bin;C:\apache-maven-3.2.5\bin;C:\Program Files\MinGW\bin;
|
Rename a.out to a.exe and run it using .\a.exe or just a.exe
Make sure that the current directory contains a.exe
|
I was wondering if any of you would know the C equivelent of the powerpc instruction below.
```
rlwinm r31, r0, 0,13,13
```
Thanks.
|
Rotate left register immediate, thenandwith mask.
Rotate left is 0 here, so we can ignore this. The mask is all bits set from 13 to 13, which is just bit 13 (0x2000 as a bitmask; this command was probably chosen over justandto document that bit 13 is selected).
So in this case, we need to build a mask for bit 13 and then apply bitwiseandwith the source.
```
r31 = r0 & (1 << 13);
```
<<is the shift left operation in C, we use it here to create a mask just for bit 13.&is the and operation in C.
Documentation source:http://sametwice.com/rlwinm
|
Code:
```
void *PrintHello(void *threadid)
{
cout<<"Hello"<<endl;
sleep(3);
cout<<"Still PrintHello is alive"<<endl;
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
cout<<"Calling thread:"<<t<<endl;
pthread_create(&threads[0], NULL, PrintHello, NULL);
//pthread_join(threads[0],NULL);
cout<<"Main exits"<<endl;
pthread_exit(NULL);
}
```
Whypthread_exit(NULL)here acts likepthread_join()? i.e Why exitingmainnot destroying theprintHellothread and allowing it to continue?
|
pthread_exit()terminates only the calling thread. So when you call it frommain(), it terminates the main thread while allowing the process to continue. This is as expected.
If you callexit()(or an implicit exit from by returning) instead, it'll terminate the whole process and you will seeprintHelloterminated as well.
|
I have a small code
```
void *PrintHello(void *threadid)
{
cout<<"Hello"<<endl;
pthread_exit(NULL);
}
int main ()
{
pthread_t threads_id;
pthread_create(&threads_id, NULL, PrintHello, NULL);
int i=0;
for(;i<100;i++){cout<<"Hi"<<endl;}
pthread_join(threads_id,NULL);
return 0;
}
```
I am joining the thread sometime after creation. What will happen if the main tries to join a thread which already exited?
|
What will happen if the main tries to join a thread which already exited?
The join operation will immediately finish and return.
|
I have a big project. I want to find which all .cpp/.h files includefile1.hin them. Is there any shortcut key in Eclipse CDT to do this?
|
I'd suggest the Include Browser view. You can drag a file in there and you get a nice tree which shows all files that include your file, including indirect includes.
|
Seems like a trivial question, but I can seem to figure it out. How to make 2 outputs a certain distance appart regardless of size of first input?
For example this is my current output:
```
Dell $1200
Toshiba $2000
Sony Vaio $1000
```
The spaces are uneven when I print them out. I want the output to look like the following:
```
Dell $1200
Toshiba $2000
Sony Vaio $1000
```
Basically I want the distance to be the same between the 2 outputs regardless of the size of the first input.
This is my code:
```
printf("\nEnter a laptops name: ");
scanf("%s", &laptopName);
printf("Enter its price: ");
scanf("%d", &laptopPrice);
printf("\n");
printf("%s ", laptopName);
printf("$%d", laptopPrice);
```
|
Specify a field width (negative value to left align):
```
printf("%-20s %d", laptopName, laptopPrice)
```
|
C'sstdbool.hadds a#definefor the type_Boolto bool.
I know a#definewas used instead of atypedefto allow#undef-ing for legacy code clashes. But why wasn'tbool_t(to match the other standard types) used in place ofbool? Is the_tused fortypedeftypes only?
I ask because the platform I am working on adds a typedef forbool_tto_Bool.
EDIT:It's been correctly pointed out that the following is probably opinion based so consider it as only my reason for the primary question above.
So I'm wondering should I use that or continue to usebool? I kind of like the way the former makes the boolean standard type form match the other standard types.
|
C introduced theboolmacro (that expands to_Bool) with the C99 Standard. They probably chose the nameboolinstead ofbool_tbecause C++ in 1998 named their boolean typebool. In C++98 all integral types (exceptwchar_talready in C90) don't use a_tsuffix.
|
How I can compare 2d arrays of char in C?
I tried this
```
Char **arr_1;
Char **arr_2;
...// malloc. Its OK.
for (I=0; I<n; I++)
{
If (strcmp (arr_1[I],arr_2[I])==0)
// do smth
}
```
But it doesn't work . I'm not good in pointers.
Arrays have some array of words.
Ubuntu gcc
Without strcmp, the program works.
Thanks
|
You can do it.
```
char arr_1[10][10];
char arr_2[10][10];
int n;
scanf("%d",&n);
for(int i=0; i<n; i++)
{
scanf(" %[^\n]",arr_1[i]);
scanf(" %[^\n]",arr_2[i]);
}
for(int I=0; I<n; I++)
{
if(strcmp (arr_1[I],arr_2[I])==0)
{
// do smth
}
}
```
|
In Linux/freeBSD kernel whenever we have to make a driver module for a device, we make a file in the /dev/ folder and use it to communicate with the other processes.
If that is so, what is the purpose of the ioctl set of functions ?
Whatever information, we want to convey with the device driver can be written to/read from this file.
Can anyone please explain it ?
I have tried reading about it on tldp.org but couldn't really understand it.
|
ioctlis used for I/O control, and as an example lets take a serial port. You open the serial port device, and can read from the serial port, and write to the serial port, but how do you set e.g. the baud-rate? Or other control options? It's not possible usingreadorwriteas those are for reading and writing data from/to the serial port, you need another function for this, which is where theioctlfunction comes in.
|
I used%eformat specifier. Tried%3.2eor%4.3e.
Example:ifvar=0.001342, then I want to print0.1342e-02. But prints1.342e-03ifvar=0.543124, then I want to print54.3124e-02. But prints5.43124e-01ifvar=0.0123653, then I want to print1.23653e-02.
That is what ever maybe the value, I just want to fix my exponent value an print the result.
|
It isnot possibleto specify the number of digitsbeforethe decimal separator with the standard floating point format specifiers.
It is the whole point of "scientific notation" to have one (or zero) digits before the decimal point and all the info about "where is the decimal point" comes from the exponent.
If you have somefixedformat (always e-2) you may produce something like:
```
printf("%f e-2", x*100.0);
```
Edit
Or, to make it morestandard scientific notation:
```
printf("%f * 10^-3", x*1e3);
```
|
i want to use a Char * across the project, the problem i am facing is below.
I created a header file as following:
File.h
```
extern char *a;
```
File1.c
```
#include "File.h"
char *a;
void foo()
{
//some manipulation on a
}
```
File2.c
```
#include"File.h"
void foo1()
{
//using "a" here gives a garbage value
}
```
I am sure that foo() is executed much before foo1().
|
Check you have allocated bytes for the char *a using malloc()? If not, it will surely print garbage value. Also memset() the pointer after allocating so that it is initialized without any garbage
|
The following code is used to parse times like 07:04:51:
```
#include <stdio.h>
int main() {
int hh, mm, ss;
scanf("%i:%i:%i\n", &hh, &mm, &ss);
printf("%i:%i:%i\n", hh, mm, ss);
}
```
Some times can be parsed and other ones don't:
```
$ echo 07:04:51 | ./test.exe
7:4:51
$ echo 08:04:51 | ./test.exe
0:0:32767
$ echo 09:04:51 | ./test.exe
0:0:32766
$ echo 10:04:51 | ./test.exe
10:4:51
$ echo 11:09:10 | ./test.exe
11:0:32764
```
What is the reason?
ideone
|
In this case it would be better to use %d instead of %i. With %i, if the value has a leading zero, the value will be read as an octal value (base 8). 08 and 09 are not valid octal values.scanf will return the number of items successfully scanned. use
```
if ( scanf("%d:%d:%d", &hh, &mm, &ss) == 3)
```
to verify that three items were scanned.
|
This code compiles and takes the input. But then it does not show the result. I looked through but dont see any error.
```
int main(int argc, char** argv) {
int a,b;
char c;
int res=0;
scanf("%d %c %d",&a,&c,&b);
//printf("%d %c %d",a,c,b);
if(c!='+' || c!='-' || c!='*' || c!='/' ){
return NAN;
}
else{
switch(c){
case '+':
res=a+b;
break;
case '-':
res=a-b;
break;
case '*':
res=(a)*(b);
break;
case '/':
res= a/b;
break;
default:
break;
}
}
printf("result is %d\n",res);
return (EXIT_SUCCESS);
}
```
|
Your if statement is wrong. It will be always true if you enter one of the 4 operators (or every other char.. )
Use AND operator ( && ) instead of OR ( ||).
```
if(c!='+' && c!='-' && c!='*' && c!='/' ){
return NAN;
}
```
|
```
for (k=0; tmp[j+k]=next[k]; k++);
```
when is this for-loop going to end and why?
Is it going to end when next[k] == 0 or when tmp[j+k] == 0?
or is there something else that I am missing?
sorry for my bad eng. and sorry for noob question.
|
Notice that the loop has no body. The work is done in the end test. The end test is implicit, because although it assigns the value ofnext[k]totmp[j+k], theexpressionalso holds the value and is either 0 (false) or non-0 (true).
So the loop ends when 0 has been copied from one array to the other.
|
Could someone please put me out of my misery and tell me why I get an Access Violation when initializing the array with ones?
```
#include <stdio.h>
void initData(float **data, size_t N)
{
int i;
*data = (float*)malloc( N * sizeof(float) );
for (i=0; i<N; i++)
{
*data[i] = 1.0;
}
}
void main()
{
float *data;
initData(&data,8);
}
```
|
Dereference (*) has a lower precedence than the square bracket operator[].
What you write is thus effectively translated to:
```
*(data[i]) = 1.0;
```
whose failure shouldn't surprise anyone.
Change it to:
```
(*data)[i] = 1.0;
```
and it won't break.
Include
stdlib.h to get rid of the warning. |
This question already has an answer here:srand function is returning same values(1 answer)Closed8 years ago.
So I'm generating some random numbers. I'm using
```
srand(time(NULL));
```
to generate random numbers. However I have this within aforloop. Im generating 10 'sets' of random numbers, but they are all the same. I was wondering how I could change this line of code to ensure the random numbers each time the program goes round the loop.
|
Already answerd : What you'll want to do is call srand() once, when the program starts (at the start of your main() function)
Then call rand() every time you want a random number
srand function is returning same values
|
The following code is used to parse times like 07:04:51:
```
#include <stdio.h>
int main() {
int hh, mm, ss;
scanf("%i:%i:%i\n", &hh, &mm, &ss);
printf("%i:%i:%i\n", hh, mm, ss);
}
```
Some times can be parsed and other ones don't:
```
$ echo 07:04:51 | ./test.exe
7:4:51
$ echo 08:04:51 | ./test.exe
0:0:32767
$ echo 09:04:51 | ./test.exe
0:0:32766
$ echo 10:04:51 | ./test.exe
10:4:51
$ echo 11:09:10 | ./test.exe
11:0:32764
```
What is the reason?
ideone
|
In this case it would be better to use %d instead of %i. With %i, if the value has a leading zero, the value will be read as an octal value (base 8). 08 and 09 are not valid octal values.scanf will return the number of items successfully scanned. use
```
if ( scanf("%d:%d:%d", &hh, &mm, &ss) == 3)
```
to verify that three items were scanned.
|
This code compiles and takes the input. But then it does not show the result. I looked through but dont see any error.
```
int main(int argc, char** argv) {
int a,b;
char c;
int res=0;
scanf("%d %c %d",&a,&c,&b);
//printf("%d %c %d",a,c,b);
if(c!='+' || c!='-' || c!='*' || c!='/' ){
return NAN;
}
else{
switch(c){
case '+':
res=a+b;
break;
case '-':
res=a-b;
break;
case '*':
res=(a)*(b);
break;
case '/':
res= a/b;
break;
default:
break;
}
}
printf("result is %d\n",res);
return (EXIT_SUCCESS);
}
```
|
Your if statement is wrong. It will be always true if you enter one of the 4 operators (or every other char.. )
Use AND operator ( && ) instead of OR ( ||).
```
if(c!='+' && c!='-' && c!='*' && c!='/' ){
return NAN;
}
```
|
```
for (k=0; tmp[j+k]=next[k]; k++);
```
when is this for-loop going to end and why?
Is it going to end when next[k] == 0 or when tmp[j+k] == 0?
or is there something else that I am missing?
sorry for my bad eng. and sorry for noob question.
|
Notice that the loop has no body. The work is done in the end test. The end test is implicit, because although it assigns the value ofnext[k]totmp[j+k], theexpressionalso holds the value and is either 0 (false) or non-0 (true).
So the loop ends when 0 has been copied from one array to the other.
|
Could someone please put me out of my misery and tell me why I get an Access Violation when initializing the array with ones?
```
#include <stdio.h>
void initData(float **data, size_t N)
{
int i;
*data = (float*)malloc( N * sizeof(float) );
for (i=0; i<N; i++)
{
*data[i] = 1.0;
}
}
void main()
{
float *data;
initData(&data,8);
}
```
|
Dereference (*) has a lower precedence than the square bracket operator[].
What you write is thus effectively translated to:
```
*(data[i]) = 1.0;
```
whose failure shouldn't surprise anyone.
Change it to:
```
(*data)[i] = 1.0;
```
and it won't break.
Include
stdlib.h to get rid of the warning. |
This question already has an answer here:srand function is returning same values(1 answer)Closed8 years ago.
So I'm generating some random numbers. I'm using
```
srand(time(NULL));
```
to generate random numbers. However I have this within aforloop. Im generating 10 'sets' of random numbers, but they are all the same. I was wondering how I could change this line of code to ensure the random numbers each time the program goes round the loop.
|
Already answerd : What you'll want to do is call srand() once, when the program starts (at the start of your main() function)
Then call rand() every time you want a random number
srand function is returning same values
|
After CallObjectMethod, I should have an object which real type is jchar, and how can I change this object to unsigned short in C++.
Now I tried cast object to jchar then cast jchar to unsigned short but got
```
error: cast from 'jobject {aka _jobject*}' to 'jchar {aka short unsigned int}' loses precision [-fpermissive]
```
|
After CallObjectMethod, I should have an object which real type is jchar
No you won't. The result of that method is anObject.If the actual Java method you're calling returns achar,you should callCallCharMethod().
and how can I change this object to unsigned short in C++.
It's only an object if you call the wrong method.
Your question doesn't make sense.
|
Is there a way to make the stack of a C program executable through compilation?
I did
```
$ gcc -o convert -g convert
```
and then run
```
$ readelf -l convert
```
to check if the stack is executable but the output was:
```
GNU_STACK 0x000000 0x00000000 0x00000000 0x00000 0x00000 RW 0x4
```
|
The correct way to make the stack executable doesn't require that stack canaries be disabled, unlike what the accepted answer suggests.
Here's the correct way:
```
gcc -z execstack ...
```
What this does is, the-zoption ofgccis passed to the linker [source]:
keyword-z is passed directly on to the linker along with the keywordkeyword. See the section in the documentation of your linker for permitted
values and their meanings.
Fromman ld[source]:
execstackMarks the object as requiring executable stack.
|
I have some code that forks a number of child "workers". Child labor :(
This works pretty good til a child dies due to some unpredictable error and the system throughput decreases.
What's a good pattern for monitoring for the children crashing, then re-forking them with the same params I fired them up with? I haven't written this type of code before and it looks like a little tricky.
|
Assuming Unix-like system, you can usewaitorwaitpidin the parent to monitor subprocesses synchronously. Alternatively, you can useSIGCHLDto monitor them asynchronously, and callwaitorwaitpidin the signal handler. You will get notified whenever a subprocesses terminates(including crashing).
To re-fork a child with the same parameters when it crashes, you would have to record the parameters for each child.
|
This is probably a simple question for you to figure out I am just having some trouble with my getAverage function, it returns a float variable type. I keep getting a "Conflicting Types" error message at the line 114, where my function is located. I am not sure if my syntax is wrong for my method or what is going on. Any help would be greatly appreciated.
Here is my function:
```
float getAverage(int nume, int deno)
{
float average;
average = (float)(nume/deno);
return average;
}
```
Edit: My function is below my main function.
|
If you call your function before it is declared the compiler will assume it returns anint. As your function returns afloatyou would get aconflicting typeserror.
|
After CallObjectMethod, I should have an object which real type is jchar, and how can I change this object to unsigned short in C++.
Now I tried cast object to jchar then cast jchar to unsigned short but got
```
error: cast from 'jobject {aka _jobject*}' to 'jchar {aka short unsigned int}' loses precision [-fpermissive]
```
|
After CallObjectMethod, I should have an object which real type is jchar
No you won't. The result of that method is anObject.If the actual Java method you're calling returns achar,you should callCallCharMethod().
and how can I change this object to unsigned short in C++.
It's only an object if you call the wrong method.
Your question doesn't make sense.
|
Is there a way to make the stack of a C program executable through compilation?
I did
```
$ gcc -o convert -g convert
```
and then run
```
$ readelf -l convert
```
to check if the stack is executable but the output was:
```
GNU_STACK 0x000000 0x00000000 0x00000000 0x00000 0x00000 RW 0x4
```
|
The correct way to make the stack executable doesn't require that stack canaries be disabled, unlike what the accepted answer suggests.
Here's the correct way:
```
gcc -z execstack ...
```
What this does is, the-zoption ofgccis passed to the linker [source]:
keyword-z is passed directly on to the linker along with the keywordkeyword. See the section in the documentation of your linker for permitted
values and their meanings.
Fromman ld[source]:
execstackMarks the object as requiring executable stack.
|
I have some code that forks a number of child "workers". Child labor :(
This works pretty good til a child dies due to some unpredictable error and the system throughput decreases.
What's a good pattern for monitoring for the children crashing, then re-forking them with the same params I fired them up with? I haven't written this type of code before and it looks like a little tricky.
|
Assuming Unix-like system, you can usewaitorwaitpidin the parent to monitor subprocesses synchronously. Alternatively, you can useSIGCHLDto monitor them asynchronously, and callwaitorwaitpidin the signal handler. You will get notified whenever a subprocesses terminates(including crashing).
To re-fork a child with the same parameters when it crashes, you would have to record the parameters for each child.
|
This is probably a simple question for you to figure out I am just having some trouble with my getAverage function, it returns a float variable type. I keep getting a "Conflicting Types" error message at the line 114, where my function is located. I am not sure if my syntax is wrong for my method or what is going on. Any help would be greatly appreciated.
Here is my function:
```
float getAverage(int nume, int deno)
{
float average;
average = (float)(nume/deno);
return average;
}
```
Edit: My function is below my main function.
|
If you call your function before it is declared the compiler will assume it returns anint. As your function returns afloatyou would get aconflicting typeserror.
|
Quick question im wondering how I could print CFNumberRef.
Im currently working on a program that comunicate with mobiledevice framework (Apple) that will print the ecid of a iDevice. And I currently have one problem, I read herelinkthat to get the ECID you have "Call the AMDeviceCopyValue function in the MobileDevice Framework " and after some help here earlier (link to last post) now I have one last question, on theiphonewiki it say that "It returns the ECID as a CFNumber(kCFNumberSInt64Type) object. ", and the question I now have is how to a print to the console CFNumber(kCFNumberSInt64Type) object??? (im working in c)
|
You can useCFShow()to print core foundation types to the console.
```
CFShow(yourCFNumberInstance);
```
You can also useNSLog()if you want to format things:
```
NSLog(CFSTR("Number is %@"), yourCFNumberInstance);
```
|
So I'm trying to figure this out with a simple program:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char a[]="lalala";
char b[]="bababa";
char c[]="nanana";
char d[3][10];
d[0][20]=*a;
d[1][20]=*b;
d[2][20]=*c;
printf("%s -- %s -- %s", d[0], d[1], d[2]);
return 0;
}
```
Whenever I run it, this is what comes out:
```
( -- ╡■ :A&w═l&wÉ∟@ -- l&wÉ∟@
```
What I'm trying to do is make it print out
lalala
bababa
nanana
Am I missing something obvious or do I need to do something more complicated to make an array for strings?
|
Try using strcpy instead of assigning them by dereferencing.
|
I noticedM_PIis unavailable onc11. By looking at/usr/include/math.hI can seeM_PIis defined if:
```
#if !defined(__STRICT_ANSI__) || ((_XOPEN_SOURCE - 0) >= 500)
...
#define M_PI 3.1415...
#endif
```
Moreover in themath.hfromglibc__STRICT_ANSI__is replaced with__USE_MISC. I am completely lost with this.
What is the story in between--std=c11and the constants defined inmath.h?
Whichlibcshould I consider on adebiandistribution ?
By the way,M_PIis defined inc99andgnu11...
|
It's simple:M_PIis not defined in standard C. Provide your own definition if you want to be standard-compliant.
C compilerscannotintroduce such constants without breaking legal C programs (the name is not reserved, and could be used as an identifier), and as such, they are only defined as an extension.
GCC 4.9 when used with-std=c99doesn't defineM_PI, butdoes when used with-std=gnu99
|
I want cast a table of int to a struct
```
int tab[10];
struct
{
int a;
int b;
}maStruct;
int main()
{
((maStruct*)(tab))->b=(int)2;
}
```
this didn't compile what's wrong in your opinion???
|
You should define yourmaStructtype properly and also add return value to your function. This code compiles:
```
int tab[10];
typedef struct maStruct
{
int a;
int b;
} maStruct;
int main()
{
((maStruct*)(tab))->b=(int)2;
return 0;
}
```
|
let's say there is a (void)function I define that prints some numbers and I want to check if it prints the correct content. I'm thinking writing the content to a file and read it back and check if it is what I wanted. But I dont know how since the function is void and returns nothing.
|
I just found out I can use freopen() to write data into a file from stdout. My bad for not making the question more clear.
|
I am attempting to implement a vec3 struct in C. I have it working, but not necessarily how I want. The current code I have is below.
```
typedef struct vec3 {
float x, y, z;
} vec3;
struct vec3 newvec3(float x, float y, float z) {
struct vec3 *values = malloc(sizeof(struct vec3));
values->x = x;
values->y = y;
values->z = z;
return *values;
}
```
In order to declare the struct I have to write.
```
vec3 test = newvec3(0.0, 1.0, 0.4);
```
What I want is.
```
vec3 test = vec3(0.0, 1.0, 0.4);
```
or something similar. I was wondering if there was a way to do this. Thanks.
|
Use
```
vec3 test = {0.0, 1.0, 0.4};
```
|
```
%%cython
from libc.stdio cimport printf
def test():
printf('abc')
```
If I runtest(), it doesn't print anything.
Currently I am doing something stupid as:
```
cdef char s[80]
sprintf(s, 'something')
print s
```
What's a better way to useprintfin cython? Why doesn't it print?
|
You can use thewurlitzerpackage to capture C-level stdout / stderr and redirect it to IPython.
For example, include the following code blocks in your Jupyter notebook:
```
%load_ext Cython
%load_ext wurlitzer
```
```
%%cython
from libc.stdio cimport printf
def test():
printf('abc')
```
```
test()
# prints "abc"
```
|
In C, people often check null pointers after using malloc. However, in C++, we will use "new". I have done some search and one explanation for the difference between malloc and new is below:https://isocpp.org/wiki/faq/freestore-mgmt#new-malloc-diff
Quote from the link above:
malloc() reports memory exhaustion by returning 0. new reports allocation and initialization errors by throwing exceptions (bad_alloc).
But how does OS (Linux or windows) react to this bad_alloc exception?
|
They don't.The OS doesn't need to "react" to anything. Your program might want to react to the condition, or it may leave the exception unhandled and terminate. Either way, the memory wasn't allocated and the OS doesn't care any more, if it cared (or even knew about it) in the first place!
|
I want to test an element forstructureif he is empty or not
but when (ex.) theG[s].a=0andG[s].b=2he never go into theif,, any help ?
```
if (G[s].a != NULL && G[s].b != NULL)
```
|
re write your logic with positive logic instead of using not null.
"not (A or B)" is the same as "(not A) and (not B)".
|
I know postfix operator increment value after using the variable.
But in this case, is it a valid statement? since it seems like i am modifying a variable after its return statement.
```
#include <iostream>
using namespace std;
int val = 0;
int foo()
{
return val++;
}
int main()
{
cout<<foo();
cout<<endl<<val;
}
```
Any elaboration will be helpful.
|
Saying thatreturn val++first returnsvaland then increments it isnot quite true. The expressionval++increments the value ofval, butevaluatesto the old value ofval.
You can think of the postfix++as a function that uses a helper variable to hold the old value:
```
int temp = val; // save old value to temp
++val; // increment actual value
return temp; // evaluate to old value
```
|
This question is related to a solution to the producer/consumer problem I'm working on. We were asked to use pthreads to solve the problem. In order to create my empty and full semaphores for the bounded buffer, I used semaphore.h, but I was told there is a method for accomplishing this without semaphore.h.
Is there a standard method for creating semaphores using the pthread API? That is, is there a simple equivalent to the following using pthreads only:
```
sem_init(&full, 0, 0);
sem_init(&empty, 0, BUFFER_SIZE);
sem_wait(&empty);
sem_post(&full);
etc.
```
Thanks for any info you can give me on this topic.
|
The<semaphore.h>functions (sem_init()/sem_open()etc. )arethe pthreads semaphore API.
Perhaps you are being guided towards using condition variables instead of sempahores to solve this problem?
|
I have code that asks the user for a number between 1 - 23.
Then I have this piece of code:
```
if (height > 23) {
if (height < 0) {
goto ask;
}
}
```
For some reason, if I type a number above 23, it asks the user for input again, if I type below 0, it accepts that number. Help?
Also, "height" is stored as an int, if that helps.
|
You must separate your validations like that:
```
if (height > 23) {
goto ask;
}
if (height < 0) {
goto ask;
}
```
You can also make one condition like that:
```
if (height > 23 || height <= 0) {
goto ask;
}
```
|
I'm writing a simple program, and it gives me an error when I pass a non-integer value to the sleep() function. Is there another function, or a different way to use sleep(), that will allow me to pause the program temporarily for less than a second (or, say, 2.5)?
mario.c:34:13: error: implicit declaration of function 'usleep' is invalid in C99 [-Werror,-Wimplicit-function-declaration]usleep(30000);^
|
usleepwill pause for a particular number of microseconds. For example:
```
usleep(500000);
```
will pause for half a second.
On some systems, and depending on compiler configuration etc, you may need to define_GNU_SOURCEbefore includingunistd.h(ideally, at the start of the source file), with:
```
#define _GNU_SOURCE
```
|
I'm trying to printf an integer that was passed by command line but the console print a long random values.
I put this into RUN "C:\Users\pc\Documents\Visual Studio 2013\Projects\Lab3\Debug\Lab3.exe randomString 4"
```
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[]){
printf("%s\n", argv[0]); // Working
printf("%s\n", (argv[1])); // working
printf("%d\n", (int)(argv[2])); // NOT Working
printf("%d\n", argc); // Working
system("pause");
return 0;
}
```
|
You can't just "cast" a char* pointer to an int and expect it to be magically converted. That is just printing the address of the first element of the array. You need to convert it to an int with a runtime function such asatoi(argv[2])See function detailshere
|
What difference is there (if any) between these two? MSDN is very unclear.
Here it sounds like they are equivalent:https://msdn.microsoft.com/en-us/library/windows/desktop/ms683197%28v=vs.85%29.aspx
But here it sounds like _pgmptr may not always give me a full path, but it doesn't really explain under what circumstances.https://msdn.microsoft.com/en-us/library/tza1y5f7.aspx
_pgmptr Seems far more attractive to me because I don't have to play buffer size guessing games with it.
|
_pgmptris initialised usingGetModuleFileNameinternally, so the answer is there's no difference - they will return the same string.
|
I saw some code like this:
```
enum
{
FIRST_DAY = 0
};
```
I know the grammar allows only one member in the enum, but in which case we define it like this? and what is the reason?
|
I can only guess, but in C this was an idiom to define named integer constants without resorting to using #define.
|
This question already has answers here:const usage with pointers in C(6 answers)Closed8 years ago.
I know that a pointer have an address and content cell which holds an address.
So what happen to the pointer in the following code:
```
int a=5;
int* const ptr=&a;
*ptr=6;
```
The address ptr holds is not changed, so how can the value that ptr points to be changed?
|
```
int *const ptr = &a;
```
Hereptris a constant pointer so you can't modify the location to which this pointer points to. But you can change the value stored in the location the pointer is pointing to.
So
```
*ptr = 6;
```
will modify the value of the variableato6.
What is not allowed is along with the existing code say you have
```
int b=5;
```
and you do
```
ptr = &b;
```
Then you are bound to get a error saying the constant pointer is being made to point to some other memory location.
|
I am trying to iterate over RGB values, to get a continuously colour plate .
Usually ,to iterate over 3 values and get them all, you do it like in binary:
```
r g b
0 0 0
0 0 1
0 1 0
```
But i have one main issue. We need to get their order to looks continuously so for instance, i go over thereds, than right to the orange, than to the yellow,green, etc.
What algorithm ,or pseudo code should i use to get them in that order ??
See this image attached, how the colors should look like:
|
Start from 255 0 0, then count up g to 255 255 0, then count down red to 0 255 0, then count up blue to 0 255 255, then count down green to 0 0 255, then count up red to 255 0 255, then count down blue to 255 0 0.
|
I have a struct defined as:
```
typedef struct ltsaNode {
int call;
int action;
ltsaNode *nextActions;
ltsaNode *sibling;
} ltsaNode;
```
And a struct pointer*wantedand anint i
I want to check if any of the structs inwantedhascallequal toi.
My current solution:
```
BOOL a = FALSE;
for(;wanted!= NULL;wanted->sibling)
{
if(wanted->call == i)
{
a=TRUE;
break;
}
}
```
Is there a better or faster way to do this ?
|
This is what you are looking for I guess.
```
BOOL a = FALSE;
for(; wanted != NULL; wanted = wanted->sibling)
{
if(wanted->call == i)
{
a = TRUE;
break;
}
}
```
|
I'm looking for function thatopen window explorerandget file the user selected. I knew how to open window explorer to this myquestion, but I was asking the wrong question. Iwant to enable read to the user selects a file.
While trying to search, I foundOpenFileDialog(). But this function looks like need GUI. Am I right? (My program runs only console)
How can I open windows explorer on the console and get the file from the user?
I'm a beginner of C. So my question may seem ridiculously easy. But if you give me the answer I really appreciate it. Thanks :)
|
You are looking for theGetOpenFileNamefunction. (OpenFileDialogis for .NET applications; if you are using C then you are not using .NET).
According to MSDN, this has been superseded by theCommon Item Dialog system, but that system is much more complicated, requires COM and isn't necessary if you are only selecting files.GetOpenFileNamewill still work for the foreseeable future.
|
I am working on a C project for a TI TMS320x DSP with the C2000 compiler. I tried to initialized a loop variable directly inside a for loop, but somehow I get a compiler error:
Code:
```
for (int TabCnt = 0; TabCnt < 10; TabCnt++)
{
x++;
}
```
Error:
```
error #20: identifier "TabCnt" is undefined
```
I figure this might be a wrong compiler setting? If I declare the variable outside of the loop, it works perfectly.
|
That's because you are using a compiler that supports only C89.
This syntax:
```
for (int TabCnt = 0; TabCnt < 10; TabCnt++)
```
is only valid since C99. The solution is either enable C99 if supported, or declare variables in the beginning of a block, e.g:
```
void foo()
{
int x = 0;
int TabCnt;
for (TabCnt = 0; TabCnt < 10; TabCnt++)
{
x++;
}
}
```
|
Suppose I write a program in C/C++ and create an array of certain size. I want to keep that permanently even if I switch off the computer and later access it. Is there a way to do that? If so do let me know and also after saving it, how to access it.
|
Save the data to a file and load it on programm start.
|
In my CUDA kernel, I need a lot of indexes, all in the range of less than 256. To save memory and memory bandwith, I plan to put these indexes incharinstead ofint.
Will this actually save me memory or does CUDA automatically use a 32 or 64 bit memory place for onechar?
(Memory coalescing is not an issue here, since the indexes are the same for all kernels.)
|
The char itself will take one byte. CUDA is not a weird system, so it's the regular 8-bit byte. Whether that's a saving depends on context. If you have those char indices in an array, there will be no padding between them and you'll save time. If each char is part of a structure and sandwiched between two integers, youwillhave padding (CUDA aligns integers).
|
I'm looking for function thatOpen window explorer in C language. I have found this [answer](How can I open Windows Explorer to a certain directory from within a WPF app?), but this is C# language.C can't have these features? I use VS 2010.
I'm a beginner of C. So my question may seem ridiculously easy. But if you give me the answer I really appreciate it. Thanks :)
|
The simplest way to open a certain directory in an explorer (here c:\program files) may be:
```
system("start \"\" \"c:\\program files\"");
```
|
In C, I want to run linux command. Namely,
```
int status;
status=system("lftp ftp://192.168.1.1 -e "mget -E /2015/Date*/*Snap/*.csv");
```
The*above is wildcard matching.
The C compiler thinks this is comment:/* and */
How do modify my call do the C compiler won't think this is comment.
|
Use the\character toescapeproblematic characters:
```
int status;
status = system("lftp ftp://192.168.1.1 -e \"mget -E /2015/Date*\/*Snap/*.csv\"");
```
Also, your original code had mismatched double-quote characters. You have to close both the inner and outer set.
|
After seeing this questionSwapping in a char * array[ ] leading to issues
User Claudiu gave a solution to swap the position of a string in an array
```
tmp = array[compare];
array[compare] = array[index];
array[index] = tmp;
```
However, i was wondering how to make that in a function by itself. using pointers, and I just can't understand the link between pointers and char arrays.
|
You can define a function:
```
void swapArrayItems(char* array[], int index1, int index2)
{
char* tmp = array[index1];
array[index1] = array[index2];
array[index2] = tmp;
}
```
And then use it as:
```
swapArrayItems(array, compare, index);
```
|
I saw some code like this:
```
enum
{
FIRST_DAY = 0
};
```
I know the grammar allows only one member in the enum, but in which case we define it like this? and what is the reason?
|
I can only guess, but in C this was an idiom to define named integer constants without resorting to using #define.
|
This question already has answers here:const usage with pointers in C(6 answers)Closed8 years ago.
I know that a pointer have an address and content cell which holds an address.
So what happen to the pointer in the following code:
```
int a=5;
int* const ptr=&a;
*ptr=6;
```
The address ptr holds is not changed, so how can the value that ptr points to be changed?
|
```
int *const ptr = &a;
```
Hereptris a constant pointer so you can't modify the location to which this pointer points to. But you can change the value stored in the location the pointer is pointing to.
So
```
*ptr = 6;
```
will modify the value of the variableato6.
What is not allowed is along with the existing code say you have
```
int b=5;
```
and you do
```
ptr = &b;
```
Then you are bound to get a error saying the constant pointer is being made to point to some other memory location.
|
I am trying to iterate over RGB values, to get a continuously colour plate .
Usually ,to iterate over 3 values and get them all, you do it like in binary:
```
r g b
0 0 0
0 0 1
0 1 0
```
But i have one main issue. We need to get their order to looks continuously so for instance, i go over thereds, than right to the orange, than to the yellow,green, etc.
What algorithm ,or pseudo code should i use to get them in that order ??
See this image attached, how the colors should look like:
|
Start from 255 0 0, then count up g to 255 255 0, then count down red to 0 255 0, then count up blue to 0 255 255, then count down green to 0 0 255, then count up red to 255 0 255, then count down blue to 255 0 0.
|
I have a struct defined as:
```
typedef struct ltsaNode {
int call;
int action;
ltsaNode *nextActions;
ltsaNode *sibling;
} ltsaNode;
```
And a struct pointer*wantedand anint i
I want to check if any of the structs inwantedhascallequal toi.
My current solution:
```
BOOL a = FALSE;
for(;wanted!= NULL;wanted->sibling)
{
if(wanted->call == i)
{
a=TRUE;
break;
}
}
```
Is there a better or faster way to do this ?
|
This is what you are looking for I guess.
```
BOOL a = FALSE;
for(; wanted != NULL; wanted = wanted->sibling)
{
if(wanted->call == i)
{
a = TRUE;
break;
}
}
```
|
I'm looking for function thatopen window explorerandget file the user selected. I knew how to open window explorer to this myquestion, but I was asking the wrong question. Iwant to enable read to the user selects a file.
While trying to search, I foundOpenFileDialog(). But this function looks like need GUI. Am I right? (My program runs only console)
How can I open windows explorer on the console and get the file from the user?
I'm a beginner of C. So my question may seem ridiculously easy. But if you give me the answer I really appreciate it. Thanks :)
|
You are looking for theGetOpenFileNamefunction. (OpenFileDialogis for .NET applications; if you are using C then you are not using .NET).
According to MSDN, this has been superseded by theCommon Item Dialog system, but that system is much more complicated, requires COM and isn't necessary if you are only selecting files.GetOpenFileNamewill still work for the foreseeable future.
|
I am working on a C project for a TI TMS320x DSP with the C2000 compiler. I tried to initialized a loop variable directly inside a for loop, but somehow I get a compiler error:
Code:
```
for (int TabCnt = 0; TabCnt < 10; TabCnt++)
{
x++;
}
```
Error:
```
error #20: identifier "TabCnt" is undefined
```
I figure this might be a wrong compiler setting? If I declare the variable outside of the loop, it works perfectly.
|
That's because you are using a compiler that supports only C89.
This syntax:
```
for (int TabCnt = 0; TabCnt < 10; TabCnt++)
```
is only valid since C99. The solution is either enable C99 if supported, or declare variables in the beginning of a block, e.g:
```
void foo()
{
int x = 0;
int TabCnt;
for (TabCnt = 0; TabCnt < 10; TabCnt++)
{
x++;
}
}
```
|
Suppose I write a program in C/C++ and create an array of certain size. I want to keep that permanently even if I switch off the computer and later access it. Is there a way to do that? If so do let me know and also after saving it, how to access it.
|
Save the data to a file and load it on programm start.
|
In my CUDA kernel, I need a lot of indexes, all in the range of less than 256. To save memory and memory bandwith, I plan to put these indexes incharinstead ofint.
Will this actually save me memory or does CUDA automatically use a 32 or 64 bit memory place for onechar?
(Memory coalescing is not an issue here, since the indexes are the same for all kernels.)
|
The char itself will take one byte. CUDA is not a weird system, so it's the regular 8-bit byte. Whether that's a saving depends on context. If you have those char indices in an array, there will be no padding between them and you'll save time. If each char is part of a structure and sandwiched between two integers, youwillhave padding (CUDA aligns integers).
|
I'm looking for function thatOpen window explorer in C language. I have found this [answer](How can I open Windows Explorer to a certain directory from within a WPF app?), but this is C# language.C can't have these features? I use VS 2010.
I'm a beginner of C. So my question may seem ridiculously easy. But if you give me the answer I really appreciate it. Thanks :)
|
The simplest way to open a certain directory in an explorer (here c:\program files) may be:
```
system("start \"\" \"c:\\program files\"");
```
|
In C, I want to run linux command. Namely,
```
int status;
status=system("lftp ftp://192.168.1.1 -e "mget -E /2015/Date*/*Snap/*.csv");
```
The*above is wildcard matching.
The C compiler thinks this is comment:/* and */
How do modify my call do the C compiler won't think this is comment.
|
Use the\character toescapeproblematic characters:
```
int status;
status = system("lftp ftp://192.168.1.1 -e \"mget -E /2015/Date*\/*Snap/*.csv\"");
```
Also, your original code had mismatched double-quote characters. You have to close both the inner and outer set.
|
After seeing this questionSwapping in a char * array[ ] leading to issues
User Claudiu gave a solution to swap the position of a string in an array
```
tmp = array[compare];
array[compare] = array[index];
array[index] = tmp;
```
However, i was wondering how to make that in a function by itself. using pointers, and I just can't understand the link between pointers and char arrays.
|
You can define a function:
```
void swapArrayItems(char* array[], int index1, int index2)
{
char* tmp = array[index1];
array[index1] = array[index2];
array[index2] = tmp;
}
```
And then use it as:
```
swapArrayItems(array, compare, index);
```
|
I've written a function for calculating the standard deviation and the result is always '1.#QNAN0', I've tried formatting it in different ways but I can't find a solution. It was working on a different computer yesterday, is there anything I can do?
```
void CalcStandardDeviation(int count, int* nums, double mean, FILE* output){
int k;
double std=0,a;
for (k=0; k<count; k++){
a=nums[k]-mean;
std=std+(a*a);
}
std/=(count);
std=sqrt(std);
fprintf(output,"Standard deviation: %f\r\n",std);
fprintf(output,"\r\n");
}
```
|
ANaNcan only have three origins in your code:
meanis aNaN.Instd/=(count);ifcountis0.Instd=sqrt(std);ifstdat this point is a negative number (seems impossible in your case).
You should debug your code and watchcountandmeanvalues (or print/export it) to find the why.
|
I am trying to do this (is this possible?) with GCC compiler:
Specifiy a function but this function if is not implemented point to a NULL. Example:
```
extern void something(uint some);
```
And if this is unimplemented point to a NULL value.
So it's possible check like this:
```
something != NULL ? something(222) : etc.;
```
I would like solution with trough GCC (this could be solvable with function pointers).
|
This is definitely not portable, but gcc can do this with weak symbols on some platforms. I know this works on Linux and *BSD, but doesn't work on MacOS.
```
$ cat weak.c
#include <stdio.h>
extern int foo(void) __attribute__((__weak__));
int
main(int argc, char **argv)
{
int x = foo ? foo() : 42;
printf("%d\n", x);
return 0;
}
$ cat weak2.c
int
foo(void)
{
return 17;
}
$ cc -o weak weak.c && ./weak
42
$ cc -o weak weak.c weak2.c && ./weak
17
$
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.