question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I'm still a beginner at C, so I'm finding difficulty in understanding "%d! = %ld".
I know that %d and %ld are respectively used for an integer and long, so "! =" is confusing me.
```
#include<stdio.h>
long factorial(int);
int main() {
int n;
long f;
printf("Enter an non-negative integer: ");
scanf("%d", &n);
if (n < 0)
printf("Negative integers are not allowed.\n");
else {
f = factorial(n);
printf("%d! = %ld\n", n, f); //what does this mean?
}
return 0; }
long factorial(int n) {
if (n == 0)
return 1;
else
return(n * factorial(n-1)); }
```
|
This will print:
%d, i.e. the decimal value ofint n! =, i.e. the literal character sequence%ld, i.e. the decimal value oflong f
|
Are there any deprecation betweenc89/90c99c11c18? Or only recommendation of avoid certain function likestrlenand use a "safer"strnlen_s?
|
Newer standards are not guaranteed to be compatible, even though the committee has a (far too) strong focus on backwards compatibility.
C90 is not completely compatible with newer versions.C11 and C17 are compatible with C99, apart from some corrections.
Official recommendations of functions to avoid are found in:
C17 6.11Future language directions, andC17 6.32Future library directions
Notably, the official recommendations are free from misguided Microsoft propaganda regarding the string handling functions etc.
Unofficial recommendations by yours sincerely here:Which functions from the standard library must (should) be avoided?.
|
I am trying to copy the string contained in
```
char *src
```
into
```
char *dst
```
this is my function but doesn't compile
```
char *mystrncpy(char *dst, char *src, size_t len)
{
char *temp = dst;
char *p = dst;
size_t i = 0;
for (p = dst; i < len; p += 1)
{
*p = *(src + p);
i += 1;
}
return *temp;
}
```
|
You're overdoing it.
You probably want this:
```
char *mystrncpy(char *dst, char *src, size_t len)
{
while (len > 0)
{
*dst++ = *src++;
len--;
}
return dst - len;
}
```
This is totally wrong
```
return *temp;
```
*tempis acharan not a pointer soreturn temp;would be correct.
BTW: strictly speaking we are not copying a string as a string in C is a NUL terminated sequence of chars. Here we are just copyinglenbytes.
|
I am new to C++ and was curious what is the C equivalent of Vecdoub and VecInt?
I am trying to evaluate code for LU decomposition but it is written in C++, some of the code is as follows.
```
VecDoub vv(n);
VecInt indx;
vv[i] = 1/max;
```
I am assuming that VecInt is similar to an array and vecdoub is similar to a 2-d array or am I completely wrong? Any clear and concise information would be greatly appreciated.
|
I think you're talking aboutVecDoub, which is a typedef/rename of the typestd::vector<double>in the book Numerical Recipes.
C doesn't have an STL library like C++, so there's nothing there that you won't have to create yourself from scratch. Even if you plan to do it, you should be proficient C programmer to be able to manage memory correctly. One library I saw implementing such a vector is libbtc. See their implementationhereandhere. You can also see how to use it in the testshere.
|
I'm still a beginner at C, so I'm finding difficulty in understanding "%d! = %ld".
I know that %d and %ld are respectively used for an integer and long, so "! =" is confusing me.
```
#include<stdio.h>
long factorial(int);
int main() {
int n;
long f;
printf("Enter an non-negative integer: ");
scanf("%d", &n);
if (n < 0)
printf("Negative integers are not allowed.\n");
else {
f = factorial(n);
printf("%d! = %ld\n", n, f); //what does this mean?
}
return 0; }
long factorial(int n) {
if (n == 0)
return 1;
else
return(n * factorial(n-1)); }
```
|
This will print:
%d, i.e. the decimal value ofint n! =, i.e. the literal character sequence%ld, i.e. the decimal value oflong f
|
Are there any deprecation betweenc89/90c99c11c18? Or only recommendation of avoid certain function likestrlenand use a "safer"strnlen_s?
|
Newer standards are not guaranteed to be compatible, even though the committee has a (far too) strong focus on backwards compatibility.
C90 is not completely compatible with newer versions.C11 and C17 are compatible with C99, apart from some corrections.
Official recommendations of functions to avoid are found in:
C17 6.11Future language directions, andC17 6.32Future library directions
Notably, the official recommendations are free from misguided Microsoft propaganda regarding the string handling functions etc.
Unofficial recommendations by yours sincerely here:Which functions from the standard library must (should) be avoided?.
|
I am trying to copy the string contained in
```
char *src
```
into
```
char *dst
```
this is my function but doesn't compile
```
char *mystrncpy(char *dst, char *src, size_t len)
{
char *temp = dst;
char *p = dst;
size_t i = 0;
for (p = dst; i < len; p += 1)
{
*p = *(src + p);
i += 1;
}
return *temp;
}
```
|
You're overdoing it.
You probably want this:
```
char *mystrncpy(char *dst, char *src, size_t len)
{
while (len > 0)
{
*dst++ = *src++;
len--;
}
return dst - len;
}
```
This is totally wrong
```
return *temp;
```
*tempis acharan not a pointer soreturn temp;would be correct.
BTW: strictly speaking we are not copying a string as a string in C is a NUL terminated sequence of chars. Here we are just copyinglenbytes.
|
I am new to C++ and was curious what is the C equivalent of Vecdoub and VecInt?
I am trying to evaluate code for LU decomposition but it is written in C++, some of the code is as follows.
```
VecDoub vv(n);
VecInt indx;
vv[i] = 1/max;
```
I am assuming that VecInt is similar to an array and vecdoub is similar to a 2-d array or am I completely wrong? Any clear and concise information would be greatly appreciated.
|
I think you're talking aboutVecDoub, which is a typedef/rename of the typestd::vector<double>in the book Numerical Recipes.
C doesn't have an STL library like C++, so there's nothing there that you won't have to create yourself from scratch. Even if you plan to do it, you should be proficient C programmer to be able to manage memory correctly. One library I saw implementing such a vector is libbtc. See their implementationhereandhere. You can also see how to use it in the testshere.
|
I am trying to copy the string contained in
```
char *src
```
into
```
char *dst
```
this is my function but doesn't compile
```
char *mystrncpy(char *dst, char *src, size_t len)
{
char *temp = dst;
char *p = dst;
size_t i = 0;
for (p = dst; i < len; p += 1)
{
*p = *(src + p);
i += 1;
}
return *temp;
}
```
|
You're overdoing it.
You probably want this:
```
char *mystrncpy(char *dst, char *src, size_t len)
{
while (len > 0)
{
*dst++ = *src++;
len--;
}
return dst - len;
}
```
This is totally wrong
```
return *temp;
```
*tempis acharan not a pointer soreturn temp;would be correct.
BTW: strictly speaking we are not copying a string as a string in C is a NUL terminated sequence of chars. Here we are just copyinglenbytes.
|
I am new to C++ and was curious what is the C equivalent of Vecdoub and VecInt?
I am trying to evaluate code for LU decomposition but it is written in C++, some of the code is as follows.
```
VecDoub vv(n);
VecInt indx;
vv[i] = 1/max;
```
I am assuming that VecInt is similar to an array and vecdoub is similar to a 2-d array or am I completely wrong? Any clear and concise information would be greatly appreciated.
|
I think you're talking aboutVecDoub, which is a typedef/rename of the typestd::vector<double>in the book Numerical Recipes.
C doesn't have an STL library like C++, so there's nothing there that you won't have to create yourself from scratch. Even if you plan to do it, you should be proficient C programmer to be able to manage memory correctly. One library I saw implementing such a vector is libbtc. See their implementationhereandhere. You can also see how to use it in the testshere.
|
So I have a function inside the main that just concatenates two strings passed into argument.
They are passed like this:
```
./main hello world
```
and will generate:
```
helloworld
```
But I need to have this when no arguments are passed:
```
./main
main: Usage: str1 str2
```
How can I do this ?
|
You probably want something like this:
```
...
int main(int argc, char *atgv[]) {
if (argc < 3) // argc = number of arguments including name of program
{
printf("Usage: main str1 str2\n");
return 1;
}
...
}
```
|
I was practicing my C skills online. And I got a question like:
What is the output of this program?
```
void main(){
int i;
for(i=1;i++<=1;i++)
i++;
printf("%d",i);
}
```
The answer was 5. But I thought the for loop would execute endlessly. As the i will be incremented on each iteration and i will benever less than or equal to 1. how come 5 will be the output of this program?
|
This is explained by the sequence of events:
```
i = 1; // for init
i++ <= 1 ? true // for condition, i evaluates as 1 but is made into i = 2 after the expression
i++; // inside for body, makes i = 3
i++; // for increment, makes i = 4
i++ <= 1 ? false // for condition again, i evaluates as 4 but is made into i = 5 after the expression
// condition is false, for loop ends, i = 5
```
Perhaps you are forgetting that theforcondition, although false, is still executed to verify that before the program decides the loop is terminated.
|
I'm thinking about how the result of the following snippet is0xc? Shouldn't it bec0-90=30? I run it onideone.com.
```
#include <stdio.h>
int main(void) {
int a[10] = {0};
int b[10] = {0};
printf("sizeof(a) = %d\n", (int)sizeof(a));
printf("%p, %p\n", (void *)(a+10), (void *)(b+10));
printf("a = %p; b = %p\n", (void *)a, (void *)b);
printf("a-b = %p", (void *)(a-b));
return 0;
}
```
Result:
```
sizeof(a) = 40
0x7ffcabb73ce8, 0x7ffcabb73cb8
a = 0x7ffcabb73cc0; b = 0x7ffcabb73c90
a-b = 0xc
```
|
When you subtract pointers you get the difference inlocationsnot difference in bytes
So, you get0x7ffcabb73cc0-0x7ffcabb73c90=0x30bytes
Dividing this by 4 bytes per integer, you get0x0cintegers
|
I have a string
```
char value[16]="ffffffffc06e91"
```
and I need to retrieve the address stored as a string in the variable value.
ie..
```
void * ptr = NULL;
somefunction(value,ptr); // ptr = 0xffffffffc06e91
```
Is there such a function or a method to do so ?
Thanks
|
Don't useatoi(); anintvalue probably isn't big enough to store this value, and the function won't work with hexadecimal strings.
Usestrtoll()instead:
```
void *ptr = (void*)strtoll("ffffffffc06e91", NULL, 16);
```
|
I'm thinking about how the result of the following snippet is0xc? Shouldn't it bec0-90=30? I run it onideone.com.
```
#include <stdio.h>
int main(void) {
int a[10] = {0};
int b[10] = {0};
printf("sizeof(a) = %d\n", (int)sizeof(a));
printf("%p, %p\n", (void *)(a+10), (void *)(b+10));
printf("a = %p; b = %p\n", (void *)a, (void *)b);
printf("a-b = %p", (void *)(a-b));
return 0;
}
```
Result:
```
sizeof(a) = 40
0x7ffcabb73ce8, 0x7ffcabb73cb8
a = 0x7ffcabb73cc0; b = 0x7ffcabb73c90
a-b = 0xc
```
|
When you subtract pointers you get the difference inlocationsnot difference in bytes
So, you get0x7ffcabb73cc0-0x7ffcabb73c90=0x30bytes
Dividing this by 4 bytes per integer, you get0x0cintegers
|
I have a string
```
char value[16]="ffffffffc06e91"
```
and I need to retrieve the address stored as a string in the variable value.
ie..
```
void * ptr = NULL;
somefunction(value,ptr); // ptr = 0xffffffffc06e91
```
Is there such a function or a method to do so ?
Thanks
|
Don't useatoi(); anintvalue probably isn't big enough to store this value, and the function won't work with hexadecimal strings.
Usestrtoll()instead:
```
void *ptr = (void*)strtoll("ffffffffc06e91", NULL, 16);
```
|
I would like to look for values in an array that equal to0up to a certain index, but the function sets all my previous values to 0; instead of checking for 0s.
ais the specified index, andMemis an array of size100.
```
for(int i=0;i<a;i++){
if (Mem[i]=0){
printf("Error!\n");
}
}
```
I'm trying to check for0s in an array up to a certain index.If there are any, I need to output anerror.
|
if (Mem[i]=0)is assigning 0 to each Mem[i].You are effectively writing 0 to every element of the array.
You need to use the == comparison operator
i.eif (Mem[i] == 0)
Other than that, you have the right idea.
|
Consider this code:
```
#include <unistd.h>
int main(void) {
sleep(.1);
return 0;
}
```
I compile it withgcc -Wall sleep.c -o sleepwith no warnings.
Running it gives me
```
time ./sleep
real 0m0,001s
user 0m0,001s
sys 0m0,000s
```
.1magically becomes0, but my question is why no warnings?
I'm using stock gcc 7.3.0 in Lubuntu 18.04
|
It's a valid conversion - the fractional part is discarded when you convert it0.1tounsigned int. It's essentially equivalent tosleep(0);. So a compiler is not required to issue any diagnostics.
However,gccdoes have an option-Wconversionwhich produces:
```
gcc -Wall -Wextra -pedantic -Wconversion a.c
a.c: In function ‘main’:
a.c:8:11: warning: conversion from ‘double’ to ‘unsigned int’ changes value from ‘1.0000000000000001e-1’ to ‘0’ [-Wfloat-conversion]
sleep(0.1);
^~~
```
|
Say I have an array that sets values for 5 elements. How do I make the last one to print out as 100?
```
int n[5];
for(i=0; i<5; i++){
printf("Please enter value %d: \n",i+1);
scanf(" %d", &n[i]);
}
```
|
You can rewrite your loop to not scan for the final element in your array, and fill that out with the hard-coded value of 100 in your code:
```
int n[5];
n[4] = 100;
for(i = 0; i < 4; i++)
{
printf("Please enter value %d: \n",i+1);
scanf(" %d", &n[i]);
}
```
Note that since yourforloop no longer asks for a value forn[4]from the user, it doesn't matter whether the linen[4] = 100;comes before or after your loop.
|
__attribute__((alias))means:
alias ("target")The alias attribute causes the declaration to be emitted as an alias for another symbol, which must be specified. For instance,void __f () { /* Do something. */; }
void f () __attribute__ ((weak, alias ("__f")));definesfto be a weak alias for__f. In C++, the mangled name for the target must be used. It is an error if__fis not defined in the same translation unit.Not all target machines support this attribute.
|
You can do something like this for C. This is supported for x86 and x64 for msvc v19.15.
```
#include <stdio.h>
void __f() { puts("This function is aliased"); }
void f();
#pragma comment(linker, "/alternatename:f=__f")
int main()
{
f();
}
```
See the compiled demohere.
I have tested this in Visual Studio 2017 with/TCoption.
|
With C99 (and later standards) standard requires certain types to be available in the header<stdint.h>. For exact-width, e.g.,int8_t,int16_t, etc..., they are optional and motivated in the standard why that is.
But for theuintptr_tandintptr_ttype, they are also optional but I don't see a reason for them being optional instead of required.
|
On some platforms pointer types have much larger size than any integral type. I believe an example of such as platform would be IBM AS/400 with virtual instruction set defining all pointers as 128-bit. A more recent example of such platform would be Elbrus. It uses 128-bit pointers which are HW descriptors rather than normal addresses.
|
A simple calculation: 3^20%15.The answer, according to a calculator, is 6.
The following code generates answer 7.
```
#include <stdio.h>
#include <math.h>
int main() {
int i = 20;
printf("%d\n", ((int)pow(3,20)%15));
return 0;
}
```
If I replace20in theprintfstatement with the variablei, it gives-8as output.
Assuming that the calculator is corrent (or not?), what is the problem in the program?
Thank you.
|
The result ofpow(3,20)can't fit in aninton your platform (or mine for that matter). Because of that, you're experiencing unexpected results.
Changing to a larger integer type such aslong longwill do the job.
Moreover,powworks with floating-point numbers which aren't represented exactly in memory (look that up). During conversion to an integer, that can cause certain errors. For example, forprintf("%fl\n", (pow(3,20)));I get3486784401.000000lwhich is not a precise integer value.
|
The goal is to get the transpose of the matrix passed in argument.
I did this but don't get what expected:
mis the matrix andris where the result is stored
```
void transpose(double m[], size_t rows, size_t cols, double r[])
{
for (size_t i = 0; i < rows; i += 1)
{
for (size_t j = 0; j < cols; j += 1)
{
r[j * cols + i] = m[i * rows + j];
}
}
}
```
When I print it, only the first row is transposed and becomes the 1st column.
Example:
```
1 2
3 4
```
will be:
```
1 3
2 4
```
but using my code:
```
1 2
3 4
```
gives me :
```
1 0
2 0
```
|
This line
```
r[j * cols + i] = m[i * rows + j];
```
is wrong. Try with:
```
r[j * rows + i] = m[i * cols + j];
```
as it is the number of columns that gives the distance between rows.
|
There is recursion function below, and I did not calculated time & space complexity. I looked at some resources, but it was not clear enough for me the understanding. Could anyone explain the way of solving in the simplest way, and answers the question?
By the way, I tried to solve time complexity, and I found O(2^n). Is it correct?
```
int func(int n) {
if (n < 3)
return 3;
else {
return func(n-3)*func(n-3);
}
}
```
|
Yes, the time complexity is indeedO(2 ^ n).
The recurrence relation for time complexity is:T(n) = 2 * T(n - 3)
Applying the above equationktimes:T(n) = 2 * 2 * 2 ... k times * T(n - 3 * k) = 2 ^ k * T(n - 3k)
Whenkisn/3,T(n) = 2 ^ k = 2 ^ (n / 3) = O(2 ^ n)
There's only one function running at a time and stack depth can bekat max.
So, space complexity isn / 3orO(n)
|
Recently a large refactor of our C code occured on our code base. I wanted to come up with a quick list of changed structure / function call names using git. Below is how I did this.
|
Use git to find whole word differences, rather than line differencesgit diff dev --word-diff-regex="([a-zA-Z0-9_]+)"Pipe this through sed to find clean up the output.
You will get output like[-OldName-]{+NewName+}Build a regex to output OldName NewNamesed -n "s/.*\[-\([a-zA-Z_]*\)-\]{+\([a-zA-Z_0-9]*\)+}.*/\1 \2/p"Combine this with uniq, and sort for a inital list of changed names.git diff dev --word-diff-regex="([a-zA-Z0-9_]+)" | \\
sed -n "s/.*\[-\([a-zA-Z_]*\)-\]{+\([a-zA-Z_0-9]*\)+}.*/\1 \2/p" | \\
sort | \\
uniq
|
This is my code :
```
void render(char * world) {...}
int main() {
char world[HEIGHT * WIDTH];
render(&world);
return 0;
}
```
Tell me if I have given enough information!
Thanks in Advance!
|
You just need to passworld. Passing&worldis passing the address ofworld, which is already achar *, so you're passing achar **.
|
Is there a difference between defining:
```
void example(int usuario[]);
```
or
```
void example(int usuario[SIZE]);
```
|
Inc, the array name when passed decays to a pointer. Using asizeofin both your examples onusariowill return the size of an int pointer, regardless ofSIZE. So both examples are identical, and are the same as
```
void example (int *usario)
```
The[]syntax in this context is purely syntactic sugar. Functionally, a pointer will be what you are actually working with - the[]or[SIZE]are only useful for a future programmer to see youexpectan array with lengthSIZE. This will not be enforced by the compiler at all.
On a modern compiler, you will get a warning if you dosizeof(usario)in the function - you can try it with both your examples.
|
I don't understand how clock function works within an operating system.
First the documentation for clock function inwww.cplusplus.comis:
```
Returns the processor time consumed by the program.
The value returned is expressed in clock ticks[...]
```
As far as I understand, the clock function must access directly some register within the CPU that is a counter for CPU cycles. How is this possible? I mean, any register of 32 bits would overflow very soon if it is being incremented one unit at the CPU frecuency. Is the OS handling this overflow in some way?
|
"Clock ticks" are implementation-defined, not in units of the cpu clock. Historically they were fixed-length, coarse-grained scheduling timeslices. There is no need for any special hardware TSC to implementclock. It suffices to simply count up the timeslices the process is scheduled for (which are ultimately enforced by a timer interrupt or similar).
|
Can someone explain why am I getting error running this code in Visual Studio 17, but not in Code:Blocks?
```
int n,m;
int main (){
printf("n");
scanf("%d", &n);
printf("m");
scanf("%d", &m);
int tab[n][m]; // Return error
}
```
In VS I'm getting a 'constant value error' asking me to replace the [n] and [m] integers with constant values, yet in Code:Blocks I get no errors at all.
It works in VS when I use the malloc() function to allocate mememory for 'tab' first, but I was wondering why I doesn't work the same way as in Code:Blocks.
|
You are declaring avariable-length array. This is a feature of theClanguage in codeblocks with some compilers which support it as an extension.Visual Studiodoes not;
```
int n,m;
int main (){
printf("n");
scanf("%d", &n);
printf("m");
scanf("%d", &m);
int *tab[m];
for (i=0; i<m; i++)
tab[i] = (int *)malloc(n * sizeof(int));
```
|
Can someone help with the else if statements. This is the script:
What I am trying to do is for example type ¨2¨ and make it calculate the subtraction of two numbers but it always starts with the first if statement before continuing through the entire script. So basically it's ignoring what I am typing at the start when I want to choose the type of calculation I am looking for.
|
You've put the conditions into double quotes, those are then evaluated as true, that's why it always runs the code in the first if block. Change
```
if ("x == 1") // always true
//...
else if ("x == 2")
//...
```
to
```
if (x == 1) // true when x has the value 1
//...
else if (x == 2) // true when x has the value 2
//...
```
|
I'm readingALSAtutorialand faced some misunderstanding. In the2. Basic PCM audiosection there is a code example:
```
snd_pcm_t *pcm_handle; //uninitialized
snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
snd_pcm_hw_params_t *hwparams;
char *pcm_name;
pcm_name = strdup("plughw:0,0");
snd_pcm_hw_params_alloca(&hwparams); //macro, must be ok
if (snd_pcm_open(&pcm_handle, pcm_name, stream, 0) < 0) { // <--- !!HERE!!
fprintf(stderr, "Error opening PCM device %s\n", pcm_name);
return(-1);
}
```
I don't understand why isn't it UB. We pass unitialized&pcm_handleto thesnd_pcm_open(&pcm_handle, pcm_name, stream, 0)which should be UB. Why is it ok?
|
You're not "using an uninitialized pointer". You're taking its address for something else to store a value to it. The pointer is a red herring. This is no different fromint x; scanf("%d", &x);
|
Recently a large refactor of our C code occured on our code base. I wanted to come up with a quick list of changed structure / function call names using git. Below is how I did this.
|
Use git to find whole word differences, rather than line differencesgit diff dev --word-diff-regex="([a-zA-Z0-9_]+)"Pipe this through sed to find clean up the output.
You will get output like[-OldName-]{+NewName+}Build a regex to output OldName NewNamesed -n "s/.*\[-\([a-zA-Z_]*\)-\]{+\([a-zA-Z_0-9]*\)+}.*/\1 \2/p"Combine this with uniq, and sort for a inital list of changed names.git diff dev --word-diff-regex="([a-zA-Z0-9_]+)" | \\
sed -n "s/.*\[-\([a-zA-Z_]*\)-\]{+\([a-zA-Z_0-9]*\)+}.*/\1 \2/p" | \\
sort | \\
uniq
|
This is my code :
```
void render(char * world) {...}
int main() {
char world[HEIGHT * WIDTH];
render(&world);
return 0;
}
```
Tell me if I have given enough information!
Thanks in Advance!
|
You just need to passworld. Passing&worldis passing the address ofworld, which is already achar *, so you're passing achar **.
|
Is there a difference between defining:
```
void example(int usuario[]);
```
or
```
void example(int usuario[SIZE]);
```
|
Inc, the array name when passed decays to a pointer. Using asizeofin both your examples onusariowill return the size of an int pointer, regardless ofSIZE. So both examples are identical, and are the same as
```
void example (int *usario)
```
The[]syntax in this context is purely syntactic sugar. Functionally, a pointer will be what you are actually working with - the[]or[SIZE]are only useful for a future programmer to see youexpectan array with lengthSIZE. This will not be enforced by the compiler at all.
On a modern compiler, you will get a warning if you dosizeof(usario)in the function - you can try it with both your examples.
|
I don't understand how clock function works within an operating system.
First the documentation for clock function inwww.cplusplus.comis:
```
Returns the processor time consumed by the program.
The value returned is expressed in clock ticks[...]
```
As far as I understand, the clock function must access directly some register within the CPU that is a counter for CPU cycles. How is this possible? I mean, any register of 32 bits would overflow very soon if it is being incremented one unit at the CPU frecuency. Is the OS handling this overflow in some way?
|
"Clock ticks" are implementation-defined, not in units of the cpu clock. Historically they were fixed-length, coarse-grained scheduling timeslices. There is no need for any special hardware TSC to implementclock. It suffices to simply count up the timeslices the process is scheduled for (which are ultimately enforced by a timer interrupt or similar).
|
Can someone explain why am I getting error running this code in Visual Studio 17, but not in Code:Blocks?
```
int n,m;
int main (){
printf("n");
scanf("%d", &n);
printf("m");
scanf("%d", &m);
int tab[n][m]; // Return error
}
```
In VS I'm getting a 'constant value error' asking me to replace the [n] and [m] integers with constant values, yet in Code:Blocks I get no errors at all.
It works in VS when I use the malloc() function to allocate mememory for 'tab' first, but I was wondering why I doesn't work the same way as in Code:Blocks.
|
You are declaring avariable-length array. This is a feature of theClanguage in codeblocks with some compilers which support it as an extension.Visual Studiodoes not;
```
int n,m;
int main (){
printf("n");
scanf("%d", &n);
printf("m");
scanf("%d", &m);
int *tab[m];
for (i=0; i<m; i++)
tab[i] = (int *)malloc(n * sizeof(int));
```
|
Can someone help with the else if statements. This is the script:
What I am trying to do is for example type ¨2¨ and make it calculate the subtraction of two numbers but it always starts with the first if statement before continuing through the entire script. So basically it's ignoring what I am typing at the start when I want to choose the type of calculation I am looking for.
|
You've put the conditions into double quotes, those are then evaluated as true, that's why it always runs the code in the first if block. Change
```
if ("x == 1") // always true
//...
else if ("x == 2")
//...
```
to
```
if (x == 1) // true when x has the value 1
//...
else if (x == 2) // true when x has the value 2
//...
```
|
I'm readingALSAtutorialand faced some misunderstanding. In the2. Basic PCM audiosection there is a code example:
```
snd_pcm_t *pcm_handle; //uninitialized
snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
snd_pcm_hw_params_t *hwparams;
char *pcm_name;
pcm_name = strdup("plughw:0,0");
snd_pcm_hw_params_alloca(&hwparams); //macro, must be ok
if (snd_pcm_open(&pcm_handle, pcm_name, stream, 0) < 0) { // <--- !!HERE!!
fprintf(stderr, "Error opening PCM device %s\n", pcm_name);
return(-1);
}
```
I don't understand why isn't it UB. We pass unitialized&pcm_handleto thesnd_pcm_open(&pcm_handle, pcm_name, stream, 0)which should be UB. Why is it ok?
|
You're not "using an uninitialized pointer". You're taking its address for something else to store a value to it. The pointer is a red herring. This is no different fromint x; scanf("%d", &x);
|
I don't understand how clock function works within an operating system.
First the documentation for clock function inwww.cplusplus.comis:
```
Returns the processor time consumed by the program.
The value returned is expressed in clock ticks[...]
```
As far as I understand, the clock function must access directly some register within the CPU that is a counter for CPU cycles. How is this possible? I mean, any register of 32 bits would overflow very soon if it is being incremented one unit at the CPU frecuency. Is the OS handling this overflow in some way?
|
"Clock ticks" are implementation-defined, not in units of the cpu clock. Historically they were fixed-length, coarse-grained scheduling timeslices. There is no need for any special hardware TSC to implementclock. It suffices to simply count up the timeslices the process is scheduled for (which are ultimately enforced by a timer interrupt or similar).
|
Can someone explain why am I getting error running this code in Visual Studio 17, but not in Code:Blocks?
```
int n,m;
int main (){
printf("n");
scanf("%d", &n);
printf("m");
scanf("%d", &m);
int tab[n][m]; // Return error
}
```
In VS I'm getting a 'constant value error' asking me to replace the [n] and [m] integers with constant values, yet in Code:Blocks I get no errors at all.
It works in VS when I use the malloc() function to allocate mememory for 'tab' first, but I was wondering why I doesn't work the same way as in Code:Blocks.
|
You are declaring avariable-length array. This is a feature of theClanguage in codeblocks with some compilers which support it as an extension.Visual Studiodoes not;
```
int n,m;
int main (){
printf("n");
scanf("%d", &n);
printf("m");
scanf("%d", &m);
int *tab[m];
for (i=0; i<m; i++)
tab[i] = (int *)malloc(n * sizeof(int));
```
|
Can someone help with the else if statements. This is the script:
What I am trying to do is for example type ¨2¨ and make it calculate the subtraction of two numbers but it always starts with the first if statement before continuing through the entire script. So basically it's ignoring what I am typing at the start when I want to choose the type of calculation I am looking for.
|
You've put the conditions into double quotes, those are then evaluated as true, that's why it always runs the code in the first if block. Change
```
if ("x == 1") // always true
//...
else if ("x == 2")
//...
```
to
```
if (x == 1) // true when x has the value 1
//...
else if (x == 2) // true when x has the value 2
//...
```
|
I'm readingALSAtutorialand faced some misunderstanding. In the2. Basic PCM audiosection there is a code example:
```
snd_pcm_t *pcm_handle; //uninitialized
snd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;
snd_pcm_hw_params_t *hwparams;
char *pcm_name;
pcm_name = strdup("plughw:0,0");
snd_pcm_hw_params_alloca(&hwparams); //macro, must be ok
if (snd_pcm_open(&pcm_handle, pcm_name, stream, 0) < 0) { // <--- !!HERE!!
fprintf(stderr, "Error opening PCM device %s\n", pcm_name);
return(-1);
}
```
I don't understand why isn't it UB. We pass unitialized&pcm_handleto thesnd_pcm_open(&pcm_handle, pcm_name, stream, 0)which should be UB. Why is it ok?
|
You're not "using an uninitialized pointer". You're taking its address for something else to store a value to it. The pointer is a red herring. This is no different fromint x; scanf("%d", &x);
|
I open a file, get its contents, look for matches for a regex pattern and print the matches out one by one. Some of the matches contain octal notation eg.\012for newlines.
When I simply applyprintf("%s\n", match);it gets printed out as\012. Is there a way to print out the respective ASCII characters instead (a newline in this case)?
|
Ifmatchis a string, you can use the functionstrtolin<stdlib.h>to convert it to anintby specifying base 8:
```
int num = strtol(match + 1, NULL, 8);
```
Note that I incremented the pointer tomatchby 1 since it begins with a"\\"whichstrtolwill stop on.
|
I want to call a function to fill in the values of a struct in C. I have the following code but I get errors like[Error] request for member 'id' in something not a structure or union.
```
#include <stdio.h>
typedef struct {
int id;
float grades[3];
} student_t;
void scan_student (student_t *s) {
printf("Please give student's info:\n");
scanf("%d%f%f%f", s.id, s.grades[0], s.grades[1], s.grades[2]);
}
int main ()
{
student_t stu2;
scan_student(&stu2);
printf("Student's info are:\n");
printf("%6d %5.2f %5.2f %5.2f\n", stu2.id, stu2.grades[0], stu2.grades[1], stu2.grades[2]);
return 0;
}
```
|
sis a pointer, not a struct. That means you can't use.on it.
Instead you have to write(*s).id(dereference, then access struct member) ors->id(same thing, but shorter).
Also,scanf%dtakes a pointer, so that should be&s->id, etc.
|
I'm new to C (programming in general). I was working on this for a while, my school assignment. I'm getting an output of many random numbers (e.g. 1xxxxxxxxx) instead of printed displays of input entered.
Here's the code in question:
```
#include<stdio.h>
int main()
{
char item[5][20];
double ppu[5], total, price[5], quantity[5];
int i;
for(i = 0; i < 5; i++)
{
printf("Enter item, price and quantity: ");
scanf("%s %f %f", &item[i], &ppu[i], &quantity[i]);
price[i] = ppu[i]*quantity[i];
total += price[i];
}
printf("ITEM\t\tPRICE PER UNIT\t\tQUANTITY\t\tPRICE\n");
for(i=0; i < 5; i++)
{
printf("%s\t\t%.2f\t\t%.0f\t\t%.2f\n", item[i], ppu[i], quantity[i], price[i]);
}
}
```
|
Change the format specifier to%lf. Don't forget to assigntotalwith an initial value.
|
manpages of theprintfand online documentations often showprintf(3)when explaining the functionality ofprintf. What does the "3" denote?
|
3denotes the section whichprintfis a part of. Section3corresponds to: Library calls (functions within program libraries).
You could also issueman <section number> <keyword>, eg.man 3 printfto look up a keyword in a specific section.man 1 printfwill show you theprintfshell command.
|
The problem is to determine if the sum of the child data is equal to parent data. if so, return true, else return false.
Below is my code which is giving an error upon submission. i know this is a simple question but after writing the condition, i am having difficulty in how to recursively check the sum condition for every node in the binary tree by traversing all the left and right nodes.
int isSumProperty(Node *node)
{
if(node == NULL) return 0;
if((node->left->data + node->right->data) == node->data)
{
return 1;
}
else
{
return isSumProperty(node->left)&&isSumProperty(node->right);
}
}
Please guide me as in where i am doing it wrong.
|
You are accessingnode->left->datawithout ensuring thatnode->leftis notNULL.
That's resulting in a segmentation fault.
|
Is it an intended behavior forscanf(), to ignore the remainder of the input after partially matching the format string?
The source code:
```
#include <stdio.h>
int main()
{
int a=0, b=0;
b = scanf("abc %d def", &a);
printf("a=%d, b=%d\n", a, b);
return 0;
}
```
The output (BTW, I'm using GCC 6):
$ ./test_scanf01
abc 123 def
a=123, b=1
$ ./test_scanf01
fff 444 zzz
a=0, b=0
$ ./test_scanf01
abc 333 rrrr
a=333, b=1
|
Yes,scanfreads as long as the input matches the format. Once there is a mismatchscanfstops reading and leaves the rest in the buffer.
For example if you have
```
scanf("%d %d", &int_var_1, &int_var_2);
```
and the input is
```
123 abc
```
then only the"123 "part would be read. The letters"abc"(and the trailing newline) would be left in the input buffer for the next input operation to read.
|
I want to call a function to fill in the values of a struct in C. I have the following code but I get errors like[Error] request for member 'id' in something not a structure or union.
```
#include <stdio.h>
typedef struct {
int id;
float grades[3];
} student_t;
void scan_student (student_t *s) {
printf("Please give student's info:\n");
scanf("%d%f%f%f", s.id, s.grades[0], s.grades[1], s.grades[2]);
}
int main ()
{
student_t stu2;
scan_student(&stu2);
printf("Student's info are:\n");
printf("%6d %5.2f %5.2f %5.2f\n", stu2.id, stu2.grades[0], stu2.grades[1], stu2.grades[2]);
return 0;
}
```
|
sis a pointer, not a struct. That means you can't use.on it.
Instead you have to write(*s).id(dereference, then access struct member) ors->id(same thing, but shorter).
Also,scanf%dtakes a pointer, so that should be&s->id, etc.
|
I'm new to C (programming in general). I was working on this for a while, my school assignment. I'm getting an output of many random numbers (e.g. 1xxxxxxxxx) instead of printed displays of input entered.
Here's the code in question:
```
#include<stdio.h>
int main()
{
char item[5][20];
double ppu[5], total, price[5], quantity[5];
int i;
for(i = 0; i < 5; i++)
{
printf("Enter item, price and quantity: ");
scanf("%s %f %f", &item[i], &ppu[i], &quantity[i]);
price[i] = ppu[i]*quantity[i];
total += price[i];
}
printf("ITEM\t\tPRICE PER UNIT\t\tQUANTITY\t\tPRICE\n");
for(i=0; i < 5; i++)
{
printf("%s\t\t%.2f\t\t%.0f\t\t%.2f\n", item[i], ppu[i], quantity[i], price[i]);
}
}
```
|
Change the format specifier to%lf. Don't forget to assigntotalwith an initial value.
|
I am trying to export a function to shared object (.so) using NDK from c++ using terminal on macOS mojave . I have installed latest versions of command line tool and Xcode.
Here's myGetNumber()which i want to export
```
#include <iostream>
#define DllExport __declspec(dllexport)
extern "C" {
DllExport int GetNumber() {
return 5 ;
}
}
```
After compiling the code using NDK , it throws the following error,
I tried out clang and Xcode compiler as well as on tried same patterns on Windows and Ubuntu . I get the same error .
Tutorial i followed to export shared library using ndk
|
You should useJNIEXPORTinstead ofDllExporton Android platforms.
The referenced tutorial you provided in your question is too old for current Android NDK development.
|
I compiled a program and get
```
format_io.c:3:6: error: cannot combine with previous 'void' declaration specifier
void int int int
^
format_io.c:3:10: error: cannot combine with previous 'void' declaration specifier
void int int int
^
```
how readformat_io.c:3:6:,when check line 6, do no t find the void error.
|
filename:line:column
Column 6 of line 3. And column 10 of line 3.
|
I am getting0xABCDABCD.0.1when I run the following code. I wanted to get the last two bytes01b0from val, but the output shows as1. I am masking the last two bytes using :0x000000000000FFFF
```
uint64_t val = 0xabcdabcd010001b0;
int main() {
printf("0x%X.%d.%x",(val&0xFFFFFFFF00000000)>>32,
(val&0x00000000FF000000)>>24,(val&0x000000000000FFFF));
return 0;
}
```
|
The problem is that the results of the bitmasks areuint64_ttypes. To print correctly, you need this code,online here:
```
#include <stdio.h>
#include <inttypes.h>
uint64_t val = 0xabcdabcd010001b0;
int main() {
printf("0x%" PRIX64 ".%" PRId64 ".%" PRIx64,
(val&0xFFFFFFFF00000000)>>32,
(val&0x00000000FF000000)>>24,
(val&0x000000000000FFFF));
return 0;
}
```
See the section "Format constants for the std::fprintf family of functions" onthis page for more formats.
|
I was doing a little bit of work on my c file when I accidentally turned off the setting which underlines problems. I'm a C novice so this tab is extremely helpful for me to figure out what I did wrong.
My question is what setting turns on error squigglies for C code. An important thing to note is that every other language I program in, the problems show up. So I'm 100% certain that it's language specific.
Thanks in advance.
|
In the workspace settingsjsonfile, you can add the following line.
```
"C_Cpp.errorSquiggles": "Enabled"
```
That will show the squiggles for both C and C++ files.
Thislinkis an useful overview on changing the settings. You will find the language specific editor settings there as well.
|
Is there a way to specify a certain number of inflated clear text in zlib? The sample code zpipe.c reads of size CHUNK (16384 bytes) but I do not see where to specify an inflated size. For example, if I only want to read the first 10 bytes before determining if I want to continue the inflation. Is that possible?
Updating question per request:
I am parsing out some zlib deflated content, which has a header. The header determines the type of content (binary or otherwise). In some cases, I just want to deflate the header. At other times, I need to deflate the entire thing. I was wondering if I could write a deflation function that will return X bytes of inflated text, irrespective of the count of deflated text.
|
If you setavail_outton, theninflate()will return at mostnbytes of uncompressed data.
|
I'm making a very simple C program that simulates theexportcommand, getting an input with fgets().
Input example:
KEY=VALUE
Has to be converted to:
```
setenv("KEY", "VALUE", 1);
```
That's easy to solve with something similar to this code:
```
key = strtok(aux, "=");
value = strtok(NULL, "=");
```
The problem comes when the user input a value that start with one or several equals=characters. For example:
KEY===VALUE
This should be converted to:
```
setenv("KEY", "==VALUE", 1);
```
But with my current code it is converted to:
```
setenv("KEY", NULL, 1);
```
How I can solve this?
Thanks in advice.
|
Your secondstrtok()should not use=as the delimiter. You would only do that if there were another=that ended the value. But the value ends at the end of the string. Use an empty delimiter for this part.
```
key = strtok(aux, "=");
value = strtok(NULL, "");
```
|
I am getting0xABCDABCD.0.1when I run the following code. I wanted to get the last two bytes01b0from val, but the output shows as1. I am masking the last two bytes using :0x000000000000FFFF
```
uint64_t val = 0xabcdabcd010001b0;
int main() {
printf("0x%X.%d.%x",(val&0xFFFFFFFF00000000)>>32,
(val&0x00000000FF000000)>>24,(val&0x000000000000FFFF));
return 0;
}
```
|
The problem is that the results of the bitmasks areuint64_ttypes. To print correctly, you need this code,online here:
```
#include <stdio.h>
#include <inttypes.h>
uint64_t val = 0xabcdabcd010001b0;
int main() {
printf("0x%" PRIX64 ".%" PRId64 ".%" PRIx64,
(val&0xFFFFFFFF00000000)>>32,
(val&0x00000000FF000000)>>24,
(val&0x000000000000FFFF));
return 0;
}
```
See the section "Format constants for the std::fprintf family of functions" onthis page for more formats.
|
I was doing a little bit of work on my c file when I accidentally turned off the setting which underlines problems. I'm a C novice so this tab is extremely helpful for me to figure out what I did wrong.
My question is what setting turns on error squigglies for C code. An important thing to note is that every other language I program in, the problems show up. So I'm 100% certain that it's language specific.
Thanks in advance.
|
In the workspace settingsjsonfile, you can add the following line.
```
"C_Cpp.errorSquiggles": "Enabled"
```
That will show the squiggles for both C and C++ files.
Thislinkis an useful overview on changing the settings. You will find the language specific editor settings there as well.
|
Is there a way to specify a certain number of inflated clear text in zlib? The sample code zpipe.c reads of size CHUNK (16384 bytes) but I do not see where to specify an inflated size. For example, if I only want to read the first 10 bytes before determining if I want to continue the inflation. Is that possible?
Updating question per request:
I am parsing out some zlib deflated content, which has a header. The header determines the type of content (binary or otherwise). In some cases, I just want to deflate the header. At other times, I need to deflate the entire thing. I was wondering if I could write a deflation function that will return X bytes of inflated text, irrespective of the count of deflated text.
|
If you setavail_outton, theninflate()will return at mostnbytes of uncompressed data.
|
I'm making a very simple C program that simulates theexportcommand, getting an input with fgets().
Input example:
KEY=VALUE
Has to be converted to:
```
setenv("KEY", "VALUE", 1);
```
That's easy to solve with something similar to this code:
```
key = strtok(aux, "=");
value = strtok(NULL, "=");
```
The problem comes when the user input a value that start with one or several equals=characters. For example:
KEY===VALUE
This should be converted to:
```
setenv("KEY", "==VALUE", 1);
```
But with my current code it is converted to:
```
setenv("KEY", NULL, 1);
```
How I can solve this?
Thanks in advice.
|
Your secondstrtok()should not use=as the delimiter. You would only do that if there were another=that ended the value. But the value ends at the end of the string. Use an empty delimiter for this part.
```
key = strtok(aux, "=");
value = strtok(NULL, "");
```
|
I would like to know to to move information from a array that looks like
```
i[0]=(
i[1]=9
i[2]=3
i[3]=5
i[4]=)
i[5]=3
.
.
.
```
in to another array to look like
```
j[0]=(935)3
```
I have tried and the only result I can get is a copy of the array with each character in a each element instead of all the character being in the first element.
code:
```
char test[100];
int n;
int k;
char i[16];
n=0;
char l[16];
FILE *infile;
infile=fopen(filename,"r");
while( fscanf(infile,"%s",test)!=EOF){
nums[n]=test;
sscanf(test,"%s",&l);
for(k=0;k<16;k++){
i[k]=l[k];
}
n++;
}
```
|
You may want to look into multi-dimensional arrays as well.
|
I would like to know to to move information from a array that looks like
```
i[0]=(
i[1]=9
i[2]=3
i[3]=5
i[4]=)
i[5]=3
.
.
.
```
in to another array to look like
```
j[0]=(935)3
```
I have tried and the only result I can get is a copy of the array with each character in a each element instead of all the character being in the first element.
code:
```
char test[100];
int n;
int k;
char i[16];
n=0;
char l[16];
FILE *infile;
infile=fopen(filename,"r");
while( fscanf(infile,"%s",test)!=EOF){
nums[n]=test;
sscanf(test,"%s",&l);
for(k=0;k<16;k++){
i[k]=l[k];
}
n++;
}
```
|
You may want to look into multi-dimensional arrays as well.
|
I'm not sure about how to get an inverse index , index%size it's ok to a straight ring index but what I need it's if tou are in 0 index get the last index as the previous of 0.
```
[0][1][2][3] // the previous index of 0 should be 3
```
|
In the languageCthe remainder operator can be used as follows to get a true (positive) modulo result:
```
(index+n-1)%n
```
wherenis the length of your array.
|
I mean this | | not this %.
Like let's say that I've got two integers x and y and and integer z.
Now
```
z = x - y
```
Is there a way to express |z| so that if z is positive it stays positive and if z is negative it's turnt into its opposite? I don't mean to express it with an if, just a mathematical equation, symbol or something like that.
|
You want theabs()function, provided in themath.hheader.
Example:
```
z = abs(x - y);
```
|
I am counting the value of possible combinations of x and y. It works but when I put big numbers it takes way too long. Do you have any ideas for better algorithm?
ax + by = c
The input of program is a, b and c, which should be non-negative numbers.
My code looks like this:
```
int combs=0;
for(int x=0; x < c; x++) {
for(int y=0; y < c; y++) {
if( (a*x) + (b*y) == c) {
combs++;
}
}
}
```
|
A much faster way is to do some math first.ax+by=c=>y=(c-ax)/b
```
int combs=0;
for(int x=0; x < c; x++) {
int y = (c-a*x)/b;
if( (a*x) + (b*y) == c)
combs++;
}
```
Getting rid of that nested loop is the most important detail to improve performance. Another thing you could do is to do as Antti Haapala suggested in comments below and use ax instead of x.
```
int combs=0;
for(int ax=0; ax < c; ax+=a) {
int y = (c-ax)/b;
if( (ax) + (b*y) == c)
combs++;
}
```
|
Just started learning C and I have a problem with the scanf function. Every time I enter a number in the console, it will be printed right under the input. The program still works, but it is a little bit annoying.
(I am using CLion from JetBrains)
```
int main()
{
int x;
printf("Number: ");
scanf("%d", &x);
printf("Your number is %d!", x);
}
```
This is the output:
Number:15
15
Your number is 15!
Process finished with exit code 0
|
It is an issue in clion (Why is CLion printing back inputs from standard input?). Currently unresolved. This problem exist for C and C++.
This bug resides for four years. I definitely advice you to change your compiler if you are not bound this for a particular reason.
|
I found this question:
What is the output ofprintf("%-x", 2048);?
I know that the"%x"is outputting the hexadecimal format of the number, but I can' quite understand what the minus sign does here, since the output is the same for bothprintf("%-x", 2048);andprintf("%x", 2048);.
|
std::printf, std::fprintf, std::sprintf, std::snprintf:
-: the result of the conversion is left-justified within the field (by default it is right-justified)
|
I am counting the value of possible combinations of x and y. It works but when I put big numbers it takes way too long. Do you have any ideas for better algorithm?
ax + by = c
The input of program is a, b and c, which should be non-negative numbers.
My code looks like this:
```
int combs=0;
for(int x=0; x < c; x++) {
for(int y=0; y < c; y++) {
if( (a*x) + (b*y) == c) {
combs++;
}
}
}
```
|
A much faster way is to do some math first.ax+by=c=>y=(c-ax)/b
```
int combs=0;
for(int x=0; x < c; x++) {
int y = (c-a*x)/b;
if( (a*x) + (b*y) == c)
combs++;
}
```
Getting rid of that nested loop is the most important detail to improve performance. Another thing you could do is to do as Antti Haapala suggested in comments below and use ax instead of x.
```
int combs=0;
for(int ax=0; ax < c; ax+=a) {
int y = (c-ax)/b;
if( (ax) + (b*y) == c)
combs++;
}
```
|
Just started learning C and I have a problem with the scanf function. Every time I enter a number in the console, it will be printed right under the input. The program still works, but it is a little bit annoying.
(I am using CLion from JetBrains)
```
int main()
{
int x;
printf("Number: ");
scanf("%d", &x);
printf("Your number is %d!", x);
}
```
This is the output:
Number:15
15
Your number is 15!
Process finished with exit code 0
|
It is an issue in clion (Why is CLion printing back inputs from standard input?). Currently unresolved. This problem exist for C and C++.
This bug resides for four years. I definitely advice you to change your compiler if you are not bound this for a particular reason.
|
I found this question:
What is the output ofprintf("%-x", 2048);?
I know that the"%x"is outputting the hexadecimal format of the number, but I can' quite understand what the minus sign does here, since the output is the same for bothprintf("%-x", 2048);andprintf("%x", 2048);.
|
std::printf, std::fprintf, std::sprintf, std::snprintf:
-: the result of the conversion is left-justified within the field (by default it is right-justified)
|
I've been told that I should use fgets and sscanf instead of scanf and I'm just wondering if there are any problems associated with getchar() and putchar() that are similar to the problems with scanf.
|
This is safe
The functionsgetcharandputchar(unlikegets,scanf,fgets) usechartypes, notchar *, so there's no risk of buffer overflow since there's no buffer (there is a buffer since I/O is buffered, but you don't control its size and it's properly managed by the C library)
Be careful when using them in a loop not to recreate security issues in your own code, the ones that you wanted to avoid.
If your goal is to read a string usinggetchar, you'll have to create a loop to store characters. If you aren't careful, you could end up with the same kind of buffer overflow issues. The problem has just moved somewhere else in your code.
|
This question already has an answer here:Segmentation Fault, large arrays(1 answer)Closed4 years ago.
The following code, when compiled and run, gives me a segmentation fault. Why is this?
```
#include <stdio.h>
#include <limits.h>
int main(void)
{
int fat_array[INT_MAX];
return 0;
}
```
|
What you are requesting is to have about2,147,483,647integer spaces allocated to you. Each integer is usually four bytes so that's8,589,934,588bytes which is 8 gigabytes of memory. This is likely above the allowed amount of memory a single process is allowed to reserve, and for good reason, so you get an error.
|
I am learning fromAPUE3e
```
#include "apue.h"
#include <dirent.h>
int main(int argc, char *argv[])
{
DIR *dp;
struct dirent *dirp;
....
```
In the header, import a user-definded module"apue.h". the program run correctly after compiled.
Theapue.his placed in/Library/Developer/CommandLineTools/usr/include,
What confuse me is that/Library/Developer/CommandLineTools/usr/includeis not in the $PATH but could be retrieved by the program globally.
```
$ echo $PATH | grep include
#does not return anything.
```
How could the program get it done?
|
$PATHis where the shell looks forexecutables, not header files.This answershows how you can get the compiler to show you where it's looking for header files.
|
So when writing this code and showing the last token it comes with the line delimiter "\n", how do i take that out?
```
while( fgets( c, MAX_viagens, f) != NULL ) {
int i = 0;
char *p = strtok (c, ":");
char *array[6];
while (p != NULL){
array[i++] = p;
p = strtok (NULL, ":");
}
printf ("%s\n", array[3]);
```
|
One simple way to achieve this is to add the new line character to the delimiters:
```
char *p = strtok (c, ":\n");
...
p = strtok (NULL, ":\n");
```
Or you could remove it before (removes last character, even if it is not'\n'):
```
if(c[0])
{
c[strlen(c)-1] = '\0';
}
```
|
So when writing this code and showing the last token it comes with the line delimiter "\n", how do i take that out?
```
while( fgets( c, MAX_viagens, f) != NULL ) {
int i = 0;
char *p = strtok (c, ":");
char *array[6];
while (p != NULL){
array[i++] = p;
p = strtok (NULL, ":");
}
printf ("%s\n", array[3]);
```
|
One simple way to achieve this is to add the new line character to the delimiters:
```
char *p = strtok (c, ":\n");
...
p = strtok (NULL, ":\n");
```
Or you could remove it before (removes last character, even if it is not'\n'):
```
if(c[0])
{
c[strlen(c)-1] = '\0';
}
```
|
For example, if I first entertestingand then that same word backwards, which isgnitset, it should print that the statement is true. I'm not sure what's wrong with my program since I just started with thestrrevfunction and strings in general.
```
#include <stdio.h>
int main()
{
char wordS[101], wordT[101];
scanf("%s", wordS);
scanf("%s", wordT);
if (wordS == strrev(wordT)){
printf("true");
}
else printf("false");
return 0;
}
```
|
wordS == strrev(wordT)compares pointers but not the string.
Usestrcmpinstead.
```
if (strcmp (wordS ,strrev(wordT)) == 0)
```
|
I'm trying to read a binary file with fread() function.I want to read 2 byte every time (UTF-16 file).The relative code:
```
char words[2];
while(fread(&words, sizeof(words), 1, sFile))
//do somthing...
```
The information from the file is stored only in the first place of the array, and the second stay as zero. Any idea? Thanks
|
Thank to you all, I found the mistake -In UTF-16, every char is 2 byte, and the "regular" chars are with zero in the 2nd byte.Again, thank you.
|
I made this code to generate a matrix with all elements beeing 1
```
for (fil = 0; fil <= 9; fil++)
for (col = 0; col <= 9; col++)
sala[fil][col] = 1;
```
and I was trying to check if all elements are equal to 1 using a for loop and print a message if they were
|
Start with the loop you already have (copied to where you need it to be of course).
Then instead of the assignment, add a check. Ifsala[fil][col] != 1then set a flag (a boolean variable) and break out of the inner loop. In the outer loop check for that flag and if set then break out of the outer loop as well. Both these checks for the flag could be part of the loop condition.
After the outer loop check for the flag. If it is set, then you know that at least one element is not equal to1. If the flag isnotset then you know thatallelements are equal to1.
|
```
#include<stdio.h> // header file
int main()
{
unsigned char a=255;
unsigned char b=0;
unsigned char c;
c=a++ + --b; // a++ is 0 and --b is 255;
printf("result=%d\n",c);
return 0;
}
```
output :
result=254
confuse why output is not 255,how 254 ?.
Please let me know if i missed anything ?
|
a++is a postfix operator, meaning it will be evaluatedafterais used. If you try++a, you'll get what you expect.
If you break downc=a++ + --b;you effectively get this:
```
b = b - 1;
c = a + b;
a = a + 1;
```
|
I came up on this question:
I have the following instruction
```
float *f = (float*) malloc(5*sizeof(float));
```
and a consequence of this is that
```
&f is of type float**
```
I don't understand why it's like this.
|
The type offisfloat*, i.e., a pointer to float. So&fis the address off, so its type is address to pointer of float, aka pointer to pointer of float, meaningfloat**.
|
I found this variable declaration in code for a Freescale microprocessor:
```
extern volatile ADCSC1STR _ADCSC1 @0x00000010;
```
It is obvious what it does (store the variable _ADCSC1 to the fix memory address 0x00000010), but I'm not sure if this is a microcontroller/IDE-specific feature or something that is defined in the language standard of C. I'm not able to find ANY reference to something like this, but maybe I'm just searching at the wrong place.
Any hints are appreciated, thanks.
|
SeeHC(S)08 Compiler Manual, page 400.
It's a vendor specific extension calledGlobal Variable Address Modifier.
|
Is there any difference between those two:
```
typedef struct ddwq{
int b;
}ta;
typedef struct {
int b;
}ta;
```
|
In the former case, you can reference the type of the struct as eitherstruct ddwqorta. In the latter case, you canonlyreference it astasince the struct has no tag.
The first case is required if the struct will contain a pointer to itself such as:
```
typedef struct ddwq{
int b;
struct ddwq *p;
}ta;
```
The type nametaisn't visible inside of the struct, so the struct must have a tag name for it to reference itself.
|
```
#include <stdlib.h>
#include <stdio.h>
int main()
{
const int minAge = 16;
const int maxAge = 18;
int age = 0;
printf("how ols ru?");
scanf("%d", &age);
if (!age>=minAge || age <= maxAge)
strong text
{
printf("no phone for u");
}
return 0;
}
```
I need to give a phone for whoever is not between the ages of 16-18 how do i do it using ! operator?
|
if (!(age < minAge || age > maxAge))
|
I'm trying to pass a string to a function:
```
void PassString(unsigned char * value)
{
// ...
}
int main(void)
{
while(1)
{
PassString("TEST");
}
}
```
I'm getting warning: (359) illegal conversion between pointer types.
|
The string literal being passed is of typechar []but the argument is given asunsigned char *.
So change the type of the argument tochar[].
|
I read input usingscanfin given format:
```
scanf("<%d;%d>%c", &lo, &hi, &op);
```
This accepts some string like<1;10>k. This works when I enter exactly in that syntax, but it doesn't work with whitespaces, so e.g. this won't work:
```
< 1 ;
3 >
k
```
So how do I makescanfignore these whitespaces?
|
Put spaces before the literal characters in the format string forscanf(). You don't actually need spaces before most%conversion specifications (%c,%nand%[…]are the exceptions; they donotskip white space), but they may as well be there for symmetry (they do not harm). Hence:
```
if (scanf(" < %d ; %d > %c", &lo, &hi, &op) == 3)
…all OK — at least, three values were read OK…
```
If you were matching a%symbol in the input, you'd use%%in the format string; that'llskip leading white spacetoo.
|
I'm trying to figure out the following code.
Especially the part that relates to the function typedef.
```
#include <stdio.h>
void foo1(int var1, int var2); // foo1 decleration
typedef void (foo2)(int var1, int var2); // what is this exactly?
typedef struct somestruct{
foo2* somefunc;
}SOMESTRUCT;
int main()
{
SOMESTRUCT struct1;
struct1.somefunc = &foo1;
struct1.somefunc(1,5);
return 0;
}
void foo1(int var1, int var2){
printf("this is function inside struct var1 = %d var2 = %d",var1, var2);
}
```
|
The line...
```
typedef void (foo2)(int var1, int var2); // what is this exactly?
```
...declares a new type,foo2, as a function that takes twointparameters and returns void.
Later in the code, the address of functionfoo1(which matches the function signature) is stored in thesomefuncmember ofstruct1, and then it's called. with parameters 1 and 5.
|
Shouldn't thestrncmp("end",input,3) == 0return 0 if the input is end? It returns a number > 0 though.
```
#include <stdio.h>
int main(void) {
char *strArray[100];
int strLengths[100];
char input[100];
int flag = 0;
do {
scanf("%c",&input);
if(strncmp("end",input,3) == 0) {
printf("end\n");
}
printf("%d\n",strncmp("end",input,3));
} while(flag !=0);
return 0;
}
```
|
This
```
scanf("%c",&input);
```
reads just a singlechar- maybe. It's wrong - pay attention to the errors and warnings you get from your compiler.
The format specifier is not correct -%cmeansscanf()will attempt to read achar, but you're passing the address of achar[100]array. That's undefined behavior, so anything might happen.
You're also not checking the return value to see ifscanf()worked at all, so you don't really know what's ininput.
|
I have a 3 digit integermyInt:
```
int myInt = 809;
```
I need an output string*myStrwhich consists of the 2 last digits. Therefore
```
char *mystr = "09";
```
What would be the easiest solution to do that?
|
You can do like this:
```
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
char buf[32];
int myInt = 809;
char* mystr;
snprintf(buf, sizeof buf, "%d", myInt);
if (strlen(buf) > 2)
mystr = buf + strlen(buf) - 2;
else
mystr = buf;
fputs(mystr, stdout);
return 0;
}
```
|
I am using NIST software. This tool (written in C) has interactive mode. It gets an input file, asks user some questions about test type and parameters, and then runs the test. I want to run it on several files, so I want to automate the whole process in Python. Is there anyway to use this software in non-interactive mode?
For documentation and code:http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html
|
You can automate interactive interfaces withpexpect, which is a python library for expect. expect is also an NIST product.
|
Why my pointer code is giving me wrong output ?.
Where, my actualcodeis :
```
void fun1(int *x, int *y){
*x = 50;
*y = 100;
fun2(&x, &y);
printf("%d %d ", x, y);
}
void fun2(int *x, int *y){
*x = 6;
*y = 7;
}
void main()
{
int x = 5;
int y = 10;
fun1(&x, &y);
printf("%d %d",x,y);
}
```
My expected output is like this : 6 7 6 7
It's giving me output like this : 6 7 50 100
Thanks.
|
Infun1the expression&xis a pointerto the pointer. It's of typeint **.
You should not use the address-of operator there, sincexandyalready are pointers.
An easy way to get the compiler to warn you about this is to declare thje functionfun2before you use it:
```
// Declare fun2 prototype
void fun2(int *x, int *y);
void fun1(int *x, int *y)
{
...
}
// Define fun2 implementation
void fun2(int *x, int *y)
{
...
}
```
|
In a project where the__FILE__and__DATE__macros are used in one of the modules, I am trying to redefine the values of these macros to explicit values during build time. Trying to use the-Doption, like-D__TIME__=01:23:45gave me a compilation error.
```
Compiling ./Console.c
In file included from <built-in>:324:
<command line>:41:9: error: redefining builtin macro [-Werror,-Wbuiltin-macro-redefined]
#define __TIME__ 01:23:45
^
1 error generated.
```
Is there a way to set these macros (and similar predefined macros) from the command line, w/o altering the source code itself?
|
Compile with the switch-Wno-builtin-macro-redefined.
That will disable the warning (including the error you get because you are also compiling with-Werror). I cannot assure you what it will do with the macro definition—Clang appears to be obeying the request to use the command-line definition, but I do not know it will do so in all circumstances.
|
I've been trying to practice working with arguments and functions but I keep getting a "too few arguments error" on this basic attempt. Can anyone point out to me what I need to do in order to get this to compile?
```
#include <stdio.h>
#include <stdlib.h>
int peachy(char* str, int a, int b)
{
str = "g";
a = 7;
b = 6;
printf("Character: %s\n", str);
printf("First Integer: %d\n", a);
printf("Second Integer: %d\n", b);
}
int main(void)
{
peachy();
}
```
|
like this
```
#include <stdio.h>
#include <stdlib.h>
void peachy(char* str, int a, int b)
{
printf("Character: %s\n", str);
printf("First Integer: %d\n", a);
printf("Second Integer: %d\n", b);
}
int main(void)
{
peachy("g", 7, 6);
peachy("foo", 42, 43); //just to show the use of function args
}
```
|
Usinggccon Linux, is there a C snippet that is guaranteed to cause adouble free or corruptionerror when compiled and executed? (nevermind my reasons for wanting to achieve this). Simply freeing memory obtained viamallocmultiple times does not always seem to work.
EDIT: the predominant opinion seems to be that I should provide my reasons for wanting to achieve this in the first place. However I would rather not go into those for reasons of my own. The answer seems to be 'no' and that is really all I wanted to hear, I believe that is reasonable.
|
In order to cause adouble free or corruptionerror you have to violate some language rules, which leads toundefined behavior. Since you can never predict what happens after invoking undefined behavior, there is no guarantee to cause such error.
|
I have a 3 digit integermyInt:
```
int myInt = 809;
```
I need an output string*myStrwhich consists of the 2 last digits. Therefore
```
char *mystr = "09";
```
What would be the easiest solution to do that?
|
You can do like this:
```
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
char buf[32];
int myInt = 809;
char* mystr;
snprintf(buf, sizeof buf, "%d", myInt);
if (strlen(buf) > 2)
mystr = buf + strlen(buf) - 2;
else
mystr = buf;
fputs(mystr, stdout);
return 0;
}
```
|
I am using NIST software. This tool (written in C) has interactive mode. It gets an input file, asks user some questions about test type and parameters, and then runs the test. I want to run it on several files, so I want to automate the whole process in Python. Is there anyway to use this software in non-interactive mode?
For documentation and code:http://csrc.nist.gov/groups/ST/toolkit/rng/documentation_software.html
|
You can automate interactive interfaces withpexpect, which is a python library for expect. expect is also an NIST product.
|
Why my pointer code is giving me wrong output ?.
Where, my actualcodeis :
```
void fun1(int *x, int *y){
*x = 50;
*y = 100;
fun2(&x, &y);
printf("%d %d ", x, y);
}
void fun2(int *x, int *y){
*x = 6;
*y = 7;
}
void main()
{
int x = 5;
int y = 10;
fun1(&x, &y);
printf("%d %d",x,y);
}
```
My expected output is like this : 6 7 6 7
It's giving me output like this : 6 7 50 100
Thanks.
|
Infun1the expression&xis a pointerto the pointer. It's of typeint **.
You should not use the address-of operator there, sincexandyalready are pointers.
An easy way to get the compiler to warn you about this is to declare thje functionfun2before you use it:
```
// Declare fun2 prototype
void fun2(int *x, int *y);
void fun1(int *x, int *y)
{
...
}
// Define fun2 implementation
void fun2(int *x, int *y)
{
...
}
```
|
In a project where the__FILE__and__DATE__macros are used in one of the modules, I am trying to redefine the values of these macros to explicit values during build time. Trying to use the-Doption, like-D__TIME__=01:23:45gave me a compilation error.
```
Compiling ./Console.c
In file included from <built-in>:324:
<command line>:41:9: error: redefining builtin macro [-Werror,-Wbuiltin-macro-redefined]
#define __TIME__ 01:23:45
^
1 error generated.
```
Is there a way to set these macros (and similar predefined macros) from the command line, w/o altering the source code itself?
|
Compile with the switch-Wno-builtin-macro-redefined.
That will disable the warning (including the error you get because you are also compiling with-Werror). I cannot assure you what it will do with the macro definition—Clang appears to be obeying the request to use the command-line definition, but I do not know it will do so in all circumstances.
|
I've been trying to practice working with arguments and functions but I keep getting a "too few arguments error" on this basic attempt. Can anyone point out to me what I need to do in order to get this to compile?
```
#include <stdio.h>
#include <stdlib.h>
int peachy(char* str, int a, int b)
{
str = "g";
a = 7;
b = 6;
printf("Character: %s\n", str);
printf("First Integer: %d\n", a);
printf("Second Integer: %d\n", b);
}
int main(void)
{
peachy();
}
```
|
like this
```
#include <stdio.h>
#include <stdlib.h>
void peachy(char* str, int a, int b)
{
printf("Character: %s\n", str);
printf("First Integer: %d\n", a);
printf("Second Integer: %d\n", b);
}
int main(void)
{
peachy("g", 7, 6);
peachy("foo", 42, 43); //just to show the use of function args
}
```
|
Usinggccon Linux, is there a C snippet that is guaranteed to cause adouble free or corruptionerror when compiled and executed? (nevermind my reasons for wanting to achieve this). Simply freeing memory obtained viamallocmultiple times does not always seem to work.
EDIT: the predominant opinion seems to be that I should provide my reasons for wanting to achieve this in the first place. However I would rather not go into those for reasons of my own. The answer seems to be 'no' and that is really all I wanted to hear, I believe that is reasonable.
|
In order to cause adouble free or corruptionerror you have to violate some language rules, which leads toundefined behavior. Since you can never predict what happens after invoking undefined behavior, there is no guarantee to cause such error.
|
I have a code:
```
void switch (int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
```
It's the function I include in other .c file by this one .h file:
```
#ifndef SWITCHINT_H
#define SWITCHINT_H
void switch (int *a, int *b);
#endif
```
But console prints that:
```
switchInt.c:1:5: error: expected identifier or ‘(’ before ‘switch’
void switch (int *a, int *b);s
switchInt.h:4:6: error: expected identifier or ‘(’ before ‘switch’
void switch (int *a, int *b);
```
What should i do?
|
The error occurred due to areservedname of the function ("switch")
ThanksFiddling Bitsfor help!
P.S: I'm sorry for being so blind :(
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.