question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I have this function:
```
int printArray(int* arr, int size) {
int i = 0;
while (size--) {
printf("%d, ", *(arr + i++));
}
return EXIT_SUCCESS;
}
```
How can I print the array without using thesizeparameter?
L.E. I tried to do something like this:
```
int printArray(int* arr) {
int i... |
You could pass in the address to the last element:
```
int printArray(int* arr, int* end) {
do {
printf("%d, ", *arr);
} while( (arr++) != end);
return EXIT_SUCCESS;
}
```
|
I added this line:
```
PATH=.:$PATH
```
to my.bash_profile.
Now I have to makemain.ccompile when I typezz(under the same directory in~/user/filename)
What do I have to write in thezzshell script?Did I add the current directory correctly?
|
PATHdetermines where executables are searched; it has no influence on where source files are searched. Source files without a directory component are searched in the current directory anyway. What you have to write to compilemain.cdepends on the compiler used, which you didn't specify, but it's usually likecc main.c. ... |
Is there a way using the standard c or c++ library to make a directory, including the subfolders that may be required given a string of the absolute path?
Thanks
|
Yes, InC++17, You can usefilesystem
```
#if __cplusplus < 201703L // If the version of C++ is less than 17
#include <experimental/filesystem>
// It was still in the experimental:: namespace
namespace fs = std::experimental::filesystem;
#else
#include <filesystem>
namespace fs = std::filesystem;
#endif
in... |
I want to save some strings in a matrix of string. The problem is that I get this error:segmentation fault core dumped. I researched on the internet but I haven't any example that showed how to use ssscanf with string matrix.
```
char * b[20][4];
sscanf("one two three","%s %s %s",b[0][0], b[0][1],b[0][2]);
printf("%s... |
try:
```
char b[20][8]; // three has five characters, lose the * to allocate memory
sscanf("one two three","%s %s %s",b[0], b[1],b[2]);
printf("%s %s %s\n",b[0], b[1],b[2]);
```
|
Compiling with -Wconversion,
```
uint32_val = 0x00000C00;
uint_8_val = ((uint32_val >> 8) & 0x000000FF);
```
gives no warning.
What compiler flag shall I use to get a warning?
|
There is no warning because theexpression:
```
((uint32_val >> 8) & 0x000000FF)
```
is always convertible to a type that fits in a byte. Youruint32_valis not cast, but takes part in a calculation. The compiler can optimize this, and in this case it is clear the result after bit-wise and-ing with000000ffwill always f... |
I have an 128x128 image stored as a contigous array of 2048 bytes. Given pixel x,y, how can i retrieve the byte index + bit index of the pixel? This is a monochrome, binary image.
|
Here is the code with a sample call that retreives the pixel value at position (33, 41).
```
#include <limits.h>
// Returns the char position and bit of pixel x, y.
void calc_pos(int x, int y, int width, int *char_no, int *bit_no) {
*char_no = (x + y * width) / CHAR_BIT;
*bit_no = (x + y * width) % CHAR_BIT;
}
... |
I am reading abookon C.
It mentions a concept which does not make sense to me.
What I know is that the compiler sometimes optimises code by removing variables which it feels would not affect an expression. So if we specify volatile to a variable, it does not remove this variable from any expression.
So the book intro... |
Avolatile constvariable is one whose value may change due to external influences, and which cannot be written to.
|
Can we write the code for sending user defined traps rather than those mentioned in snmpd using Net-SNMP API like below to send traps netsnmp_send_traps(), send_v2trap(), send_v3trap()?
I am not planning to write any MIB module. So I don't expect that my trap should be going through snmpd (Agent Daemon).
The idea I ... |
There is no Net-SNMP API provided. We can just fork-exec Net-SNMP command to send trap.
|
I use thecodeblock.
When the code is:
```
printf("%d",1/0);
```
The program can not run, there is an error. But when I write this:
```
printf("%d",1/0.0);
```
The program can run,and the output is0. I want to know why.
|
1/0or1/0.0are both undefined behavior:
C11 §6.5.5 Multiplicative operatorsThe result of the/operator is the quotient from the division of the first operand by the
second; the result of the%operator is the remainder.In both operations, if the value of the second operand is zero, the behavior is undefined.
|
I keep getting a lot of 'assignment from incompatible pointer type' warnings, and I haven't a clue as to why.
```
myPageFrame pageFrames[numOfFrames];
myPage pages[numOfPages];
//in a for loop
pageFrames[i].thePage = (myState == HOT ? (&pages[i]) : NULL); // one of the offenders
```
I get the warning any time I tr... |
myPageandstruct myPageare different types. You could make them the same type by changing thestructdefinition to:
```
typedef struct myPage {
int pageNum;
} myPage;
```
or you could just usemyPage *instead ofstruct myPage *.
|
Is there a way to create two structs that make a reference to each other?
Example:
```
struct str1
{
struct str1* ptr1;
struct str2* ptr2;
}
struct str2
{
struct str1* ptr1;
struct str2* ptr2;
}
```
|
```
struct str2; // put a forward reference to str2 here
struct str1
{
struct str1* s1;
struct str2* s2;
};
struct str2
{
struct str1* s1;
struct str2* s2;
};
int main()
{
struct str1 s1;
struct str2 s2;
s1.s1 = &s1;
s1.s2 = &s2;
s2.s1 = &s1;
s2.s2 = &s2;
return 0;
}
```
|
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char *str = "This is a string!";
int therealthing = sizeof(str[0]) * 4;
memset(str, 'b', therealthing);
printf("%s\n", str);
return 0;
}
```
This code causes a segfault, any ideas why?
I have already... |
This is a string literal. It's immutable. Can't be changed.
```
char *str = "This is a string!";
```
You're trying to change it with memset. You could use an array of characters
```
char str[] = "This is a string!";
```
or
```
char * str = malloc(sizeof(char) * (strlen("This is a string!") + 1));
strcpy(str, "Thi... |
Is there a good description of the STM432f4xx libraries along the lines of the really good one available for thestm32f2xx library, or is the 32f4xx entirely self documented through comments and examples?
It's great to have this available all in one doc, as opposed to wading through the library tree. It looks like muc... |
Yes, here are the most helpful sources (imo) other than the ref manual, and source. 'Tis all about formatting:
CMSIS Library
Github STM32F4 Standard Peripheral Lib Documentation
Reference Manuals
Programming Manual
Note the use of DOXYGEN to generate some sources
|
I have a questionhere. Now I wish to clear every element of the array without the use of setting the '\0' trick. I tried with memset, but it complains of
```
expected ‘void *’ but argument is of type ‘struct array’
```
here is my code:
```
int i;
for( i=0; i< sizeof(array)/sizeof(array[0]) ; i++){
memset(arra... |
memsetexpects a pointer (add&):
```
memset(&array[i], 0, sizeof(array[i] ) );
```
But if you are going to clear the entire array, you could replace thefor-loop with:
```
memset(array, 0, sizeof(array));
```
As a side note: You should really avoidsizeof(array)/sizeof(array[0]). Define constant for element count. It... |
I happened to write a if-else statement, the condition would be false at most time(check a static pointer is assigned or not). Which one would be better for the compiler to optimize? Or they are just equal?. The function would be called so many times, so it is critical to optimize its performance.
```
void foo() {
... |
Some compilers can allow the dev to specify which is condition is more likely or unlikely to occur.
This is heavily used in the Linux kernel.
In gcc, there's the likely(x) or unlikely(x) macros.
Example:
```
if (unlikely(p == NULL)) {
p = malloc(10);
}
```
|
I have a query:
```
select count(distinct RID)
from MASTER_MOVIEVOD as M
inner join RID_GENRE_MOVIEVOD as RG
inner join GENRE_MOVIEVOD as G on M.RID=RG.RID and RG.GENRE_SR_NO=G.GENRE_SR_NO
where M.UPDATE_PRESENT=1
and M.CLIP_TYPE=220
and M.PCAT=2
and G.GENRE_NAME!='Drama';
```
It gives me error
Error:... |
This is because SQL doesn't know whichRIDto selectM.RIDorRG.RID, the ambiguity comes from here.
You have to choose one of them instead ofRID:
```
select count(RG.RID)
from MASTER_MOVIEVOD as M
..
```
|
I am currently working with the Altera Nios II and this gives me the possibility to, for example, connect all the red LEDs to an int* with given memory address. In all the examples this looks like the following:
```
volatile int * ledR = (int*) 0x00093050;
```
It is always prefixed with the volatile keyword, why? As... |
Mainly when dealing with hardware registers , we need to use volatile keyword. This makes the compiler to fetch the register everytime when you invoke the address , rather than using the local copy of that variable .
|
Is there a good description of the STM432f4xx libraries along the lines of the really good one available for thestm32f2xx library, or is the 32f4xx entirely self documented through comments and examples?
It's great to have this available all in one doc, as opposed to wading through the library tree. It looks like muc... |
Yes, here are the most helpful sources (imo) other than the ref manual, and source. 'Tis all about formatting:
CMSIS Library
Github STM32F4 Standard Peripheral Lib Documentation
Reference Manuals
Programming Manual
Note the use of DOXYGEN to generate some sources
|
I have a questionhere. Now I wish to clear every element of the array without the use of setting the '\0' trick. I tried with memset, but it complains of
```
expected ‘void *’ but argument is of type ‘struct array’
```
here is my code:
```
int i;
for( i=0; i< sizeof(array)/sizeof(array[0]) ; i++){
memset(arra... |
memsetexpects a pointer (add&):
```
memset(&array[i], 0, sizeof(array[i] ) );
```
But if you are going to clear the entire array, you could replace thefor-loop with:
```
memset(array, 0, sizeof(array));
```
As a side note: You should really avoidsizeof(array)/sizeof(array[0]). Define constant for element count. It... |
I happened to write a if-else statement, the condition would be false at most time(check a static pointer is assigned or not). Which one would be better for the compiler to optimize? Or they are just equal?. The function would be called so many times, so it is critical to optimize its performance.
```
void foo() {
... |
Some compilers can allow the dev to specify which is condition is more likely or unlikely to occur.
This is heavily used in the Linux kernel.
In gcc, there's the likely(x) or unlikely(x) macros.
Example:
```
if (unlikely(p == NULL)) {
p = malloc(10);
}
```
|
I have a query:
```
select count(distinct RID)
from MASTER_MOVIEVOD as M
inner join RID_GENRE_MOVIEVOD as RG
inner join GENRE_MOVIEVOD as G on M.RID=RG.RID and RG.GENRE_SR_NO=G.GENRE_SR_NO
where M.UPDATE_PRESENT=1
and M.CLIP_TYPE=220
and M.PCAT=2
and G.GENRE_NAME!='Drama';
```
It gives me error
Error:... |
This is because SQL doesn't know whichRIDto selectM.RIDorRG.RID, the ambiguity comes from here.
You have to choose one of them instead ofRID:
```
select count(RG.RID)
from MASTER_MOVIEVOD as M
..
```
|
I am currently working with the Altera Nios II and this gives me the possibility to, for example, connect all the red LEDs to an int* with given memory address. In all the examples this looks like the following:
```
volatile int * ledR = (int*) 0x00093050;
```
It is always prefixed with the volatile keyword, why? As... |
Mainly when dealing with hardware registers , we need to use volatile keyword. This makes the compiler to fetch the register everytime when you invoke the address , rather than using the local copy of that variable .
|
I have a questionhere. Now I wish to clear every element of the array without the use of setting the '\0' trick. I tried with memset, but it complains of
```
expected ‘void *’ but argument is of type ‘struct array’
```
here is my code:
```
int i;
for( i=0; i< sizeof(array)/sizeof(array[0]) ; i++){
memset(arra... |
memsetexpects a pointer (add&):
```
memset(&array[i], 0, sizeof(array[i] ) );
```
But if you are going to clear the entire array, you could replace thefor-loop with:
```
memset(array, 0, sizeof(array));
```
As a side note: You should really avoidsizeof(array)/sizeof(array[0]). Define constant for element count. It... |
I happened to write a if-else statement, the condition would be false at most time(check a static pointer is assigned or not). Which one would be better for the compiler to optimize? Or they are just equal?. The function would be called so many times, so it is critical to optimize its performance.
```
void foo() {
... |
Some compilers can allow the dev to specify which is condition is more likely or unlikely to occur.
This is heavily used in the Linux kernel.
In gcc, there's the likely(x) or unlikely(x) macros.
Example:
```
if (unlikely(p == NULL)) {
p = malloc(10);
}
```
|
I have a query:
```
select count(distinct RID)
from MASTER_MOVIEVOD as M
inner join RID_GENRE_MOVIEVOD as RG
inner join GENRE_MOVIEVOD as G on M.RID=RG.RID and RG.GENRE_SR_NO=G.GENRE_SR_NO
where M.UPDATE_PRESENT=1
and M.CLIP_TYPE=220
and M.PCAT=2
and G.GENRE_NAME!='Drama';
```
It gives me error
Error:... |
This is because SQL doesn't know whichRIDto selectM.RIDorRG.RID, the ambiguity comes from here.
You have to choose one of them instead ofRID:
```
select count(RG.RID)
from MASTER_MOVIEVOD as M
..
```
|
I am currently working with the Altera Nios II and this gives me the possibility to, for example, connect all the red LEDs to an int* with given memory address. In all the examples this looks like the following:
```
volatile int * ledR = (int*) 0x00093050;
```
It is always prefixed with the volatile keyword, why? As... |
Mainly when dealing with hardware registers , we need to use volatile keyword. This makes the compiler to fetch the register everytime when you invoke the address , rather than using the local copy of that variable .
|
I saw the following code in the wild and I don't know what to make of it:
more or less:
```
int main(void)
{
int a = 0, v;
printf("%d\n", v);
}
```
This code with gcc will print out 0. At first I though, oh well that's because initialized local variables are assigned 0, but in this case I never declared the ... |
```
int a = 0, v;
```
is equivalent to:
```
int a = 0;
int v;
```
So youdiddeclare the type ofv, just not explicitly. It's anint.
Anyway,like all uninitialized local variables,v's value isn't guaranteed to be anything. Accessing it is still undefined behavior; you just happened to get 0.
|
Do i need to use valgrind on each program file with which ".so" is made.. or is there any we can run valgrind directly on ".so" library. please provide steps for later.
|
Not directly. Library does not have an entry point where to start executing it, andvalgrindonly checks code that is actually executing.
Still, if you want to test a library withvalgrind, there is a simple way. Just write a test program, which uses the library in the way that tests the parts and features of library yo... |
```
int P;
printf("Print a Character:");
scanf("%d",&P);
printf("\n The character you pressed was %d",P);
```
Without me inputting any number, this outputs:
"Print a Character:
The character you pressed was -1073750520"
Do you know why this would be? I'm using Xcode.
|
I think there is something already present in thestdinstream. So flushing the stream could help.
Tryfflush(stdin);beforescanf();.
Butfflush(stdin)is undefined behavior.
|
This question already has answers here:Difference between [square brackets] and *asterisk(5 answers)Closed9 years ago.
I know these two are equivalent:
int some_function(char n[])
and
int some_function(char *n)
is there any reason to prefer one over the other??
|
On seeing
```
int some_function(char n[])
```
compiler interprets it as
```
int some_function(char *n)
```
Both are same. First one prefer over second sometimes to let the other programmers know that an array is passed (i.e, pointer to array element) to the function.
|
I know the switch in gcc but there is nothing about such option in TTC. I read about something _winstart or what swich but I don't know where to put it.
|
Ok, it seems it is possible to make non-console app in tcc. I didn't figured out yet what are the key elements necessary here. But in tcc package there ishello_win.cexample.
|
This may be a deeper question than I expect, but can you see if a character pointer is unallocated? For example, a string that is unallocated is notNULL, as seen from when I ran this code:
```
char *ptr; /* Unallocated char pointer */
if (ptr == NULL) {
ptr = malloc(10); /* Not casted cause it doesn't matter ... |
No, it is not possible. In your case,ptrisuninitialised, which means it might contain any value at all, until the first time you assign something to it. It might beNULL, or it might not.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
its behavior is undefined. if you want to show the values of a, b and c you should have coded as below:
printf("%d%d%d",a,b,c);
now the output is:
```
5 6 11
```
|
Consider the following (C11) code:
```
void *ptr = aligned_alloc(4096, 4096);
... // do something with 'ptr'
ptr = realloc(ptr, 6000);
```
Since the memory thatptrpoints to has a 4096-byte alignment fromaligned_alloc, will it (read: is it guaranteed to) keep that alignment after a (successful) call torealloc? Or cou... |
The alignment is not kept with the pointer. When you call realloc you can only rely on the alignment that realloc guarantees. You'll need to use aligned_alloc to perform any reallocations.
|
In my application, we take in char values one at a time and we need to be able to but them into a string. We are assembling these strings one by one by putting the char values into a char array, then clearing the array. However the strings are each different lengths and we are unable to determine the size of the strin... |
If the array was dynamically allocated withmalloc, you can resize it withrealloc:
```
int array_size = 1024;
char *array = (char *) malloc(array_size);
int n = 0;
char c;
while ((c = getchar()) != EOF) {
array[n++] = c;
if (n >= array_size) {
array_size += 1024;
array = (char *) realloc(array... |
Here is my code snippet
```
typedef struct Position
{
short X;
short Y;
} Pos;
Pos Block[25*25+1];
void Clear_String (void)
{
memset (&Block, 0, sizeof (Pos));
}
```
Here is my full code in plain text:Click Me
Whyvoid Clear_String (void)doesn't clear all of the elements in structure?
|
Block and unfilled are arrays of Pos. You are zeroing only the first item since you pass sizeof (Pos).
|
I'm having a problem where I am wanting to go through an array and check that only positive numbers have been entered. I know that it is possible to use isDigit from ctype.h but I'd rather construct something myself. The way I think it is possible, is to iterate through each element of the array and see if the value s... |
It is not working because0and9are integers not characters.
Change yourifcondition to
```
if((testArray[x] >= '0') || (testArray[x] <= '9')){ ... }
```
to check the digits from 0 to 9.
|
I am writing a small kernel device where i need to store values in a list. Adding first to the list work fine but next entries trigger a error. Can any one say me why ? my code is given below; i am using kernel 3.6.10-4.fc18.x86_64 in fedora 18
```
LIST_HEAD(dns_list_lp ) ;
static void add_dns_list(__be32 v4address,... |
You try to store a pointer to a local variable. You have to remember that once the function returns the lifetime of the variablenodeends, and that pointer in the list is no longer valid.
|
I am new to Cuda, I have the following function:
```
__global__ void square(float *myArrayGPU)
{
myArrayGPU[threadIdx.x] = sqrt(threadIdx.x);
}
```
I want to use the cuda math library, I tried to#include "math.h"but I still get the error
error: calling a __host__ function("__sqrt") from a __global__ function("sq... |
threadIdx.xis of type int. CUDA math library is overloaded only for single precision (float) and double precision (double). You need to supply either a 'float' or 'double' type parameter tosqrt()for the CUDA version ofsqrt()to be called.
Change
```
myArrayGPU[threadIdx.x] = sqrt(threadIdx.x);
```
into
```
myArrayG... |
I have the following piece of code:
```
struct sched_param {
union {
int sched_priority;
struct rcost_sched_param rcost_params;
};
};
```
I want to know which of the two parameters is "active". Is there a way for me to do that other than adding a int to thestruct sched_param?
|
```
struct sched_param {
int type;
union {
int sched_priority;
struct rcost_sched_param rcost_params;
};
}
```
you can add member namedtype,save the data which parameters is "active"
|
This question already has answers here:scanf() leaves the newline character in the buffer(7 answers)Closed3 years ago.
the program doesnt stop on scanf("%c", &ch) line. why does it happens sombody can please explain this to me
```
#include<stdlib.h>
#include<stdio.h>
struct list {
char val;
struct list * next... |
Let's say you input 2 when you're reading for num. The actual input stream will be 2\n (\n is the newline character). 2 goes into the num, and there remains \n, which goes into ch. To avoid this, add a whitespace in format specifier.
```
scanf(" %c", &ch);
```
This will ignore any whitespaces, newlines or tabs.
|
Is there a findall function in C's regex library like there is in python:
```
re.findall(pattern, input_string)
```
I have a string containing filenames like so:"path/to/file1.ics,path/file2.ics"with anundeterminednumber of files in the string. I want to find all the filenames (including their path) and put them in ... |
Assuming you're using POSIXregcomp/regexec, each call toregexecwill only find thefirstmatch in the string. To find the next, use the end position of the first match (the 0th entry of theregmatch_tarray filled byregexec) as an offset to apply to the string before searching it again. Repeat until you have no more matche... |
This question already has an answer here:Difference between char* var; and char *var;? [duplicate](1 answer)Closed9 years ago.
Is there any differences between these two declarations?
```
int* a;
int *a;
```
Or these two declarations are the same (pointer to an integer)?
|
They're exactly the same, but here's a small gotcha I came across when first learning C years ago. The * binds to thevariable, not the type. This means that
```
int* a, b;
```
Declaresaas a pointer to int, andbas anint. To declare both as pointers, one should do.
```
int *a, *b;
```
This is why I prefer to place t... |
When i call fork() in main.I don't get 0 value for child process id.
My code :
```
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(){
pid_t pid = fork();
printf("pid in child=%d and parent=%d\n",getpid(),getppid());
wait(NULL);
}
```
And the output ... |
You should actually use the value ofpidin yourprintfstatement.
The result offork()is zero for the forked process, but its process id as gained bygetpid()is not zero.
|
I would write a program as follows
```
int main ()
{
FILE *fp = fopen("test.txt", "r")
if (fp == NULL)
{
printf("Sorry, file doesn't exist.");
return 0;
}
return 0;
}
```
Is there any other check that I would need to make sure before or after opening a file?
W... |
No other check needed.
I always also make it a practice of callingfclose, however, when done with the FILE*.
|
How can I use#defineto say that one value consists of the sum of two other values. Would it be allowed and good practice inCto do something like this?
```
#define VALUE_A 2
#define VALUE_B 2
#define SUM_A_B (VALUE_A + VALUE_B)
```
If not, what should I do to achieve this functionality?
|
The Linux and GCC header files do it routinely, if that's a vote of confidence. e.g.:
```
$ grep -r 'define.*+' /usr/include/
...
/usr/include/linux/fdreg.h:#define FD_STATUS (4 + FD_IOPORT )
...
/usr/include/linux/elf.h:#define PT_GNU_STACK (PT_LOOS + 0x474e551)
...
/usr/include/i386-linux-gnu/asm/unistd_32.h:... |
my LD_LIBRARY_PATH is currently at /usr/local/libanytime I try to call any library i get the following error
```
ld: library not found for -libfftw3
clang: error: linker command failed with exit code 1 (use -v to see invocation)
```
for example when I enter this:
```
$ gcc -o prog -L/usr/local/lib -libfftw3 -I/usr/... |
You don't specify the lib prefix of a library when linking, so use-lfftw3, look in /usr/local/lib/ for the actual library name, if it isn't libfftw3.a or libfftw3.so
-lfftw3 should be at the end of all the arguments.
|
I'm trying to call a C function defined in sample_c.c (with function declaration in sample_c.h) from a C++ code. I'm using this declaration in sample_c.h
```
extern "C" void print_c(void);
```
and this definition in sample_c.c
```
extern void print_c(void) {....}
```
and trying to generate lib which I want to link... |
extern "C"is not valid in C. To write a header that can be used for both C and C++ you have to make sure that theextern "C"is not visible when compiled as C:
```
#ifdef __cplusplus
extern "C"
#endif
void print_c(void);
```
|
I know how to loop through a file line by line by reading into a FILE* using fopen, fgets etc
but how can i look through a char array line by line using plain C?
i have googled a lot an can only find stuff that reads from a file.
|
```
#include <stdio.h>
char *sgets(char *s, int n, const char **strp){
if(**strp == '\0')return NULL;
int i;
for(i=0;i<n-1;++i, ++(*strp)){
s[i] = **strp;
if(**strp == '\0')
break;
if(**strp == '\n'){
s[i+1]='\0';
++(*strp);
break;
... |
```
Ceeloss-MacBook-Pro:desktop ceelos$ gcc -o prog -I/usr/local/include test.c
Undefined symbols for architecture x86_64:
"_fftw_destroy_plan", referenced from:
_main in test-IBqBdS.o
"_fftw_execute", referenced from:
_main in test-IBqBdS.o
"_fftw_plan_dft_1d", referenced from:
_main in test-I... |
It's telling you that you forgot to use-Land-lto tell gcc where the FFTW libraries are and what they're called.
|
I have two int values that I want to combine into a decimal number. So for example, I have A = 1234 and B = 323444. Both are int and I do not want to change it if possible.
I want to combine them to get 1234234233.323444.
My initial method was to divide b by 1e6 and add it to A to get my value.
I assigned
```
int A... |
Try like this:
```
C = A + (B/ 1000000.0);
```
ie, make the denominator as double so that when integer by integer division is made it does not return weird results like you are getting.
NOTE:-
Integer/Integer = IntegerInteger/Double = DoubleDouble/Integer = DoubleDouble/Double = Double
|
I am trying to compile a C program in the terminal.
This is my command:
```
gcc -1 string -o syncing.c -o syncing
```
This is my result:
```
clang: error: no input files
```
I know that-1... indicates the library I used,syncing.cis the C file I am trying to compile.
What am I doing wrong with my command or is it... |
Please read up onhow to use GCC,GCC command-line optionsand alsoofficial command-line documentation. You are telling it thatsyncing.cis your output file. But you want it to be your input file.
Also, I am not so sure on the-1there. You might want to have a look atthison how to include/link external libraries.Hereare m... |
I am trying to cast an array of uint8_t to an array of uint32_t, but it seems not to be working.Can any one help me on this. I need to get uint8_t values to uint32_t.I can do this with shifting but i think there is a easy way.
```
uint32_t *v4full;
v4full=( uint32_t *)v4;
while (*v4full) {
if (*v4full & 1)
... |
Given the need to get uint8_t values to uint32_t, and the specs on in4_pton()...
Try this with a possible correction on the byte order:
```
uint32_t i32 = v4[0] | (v4[1] << 8) | (v4[2] << 16) | (v4[3] << 24);
```
|
I can't understand why this
```
#include <stdio.h>
#include <stdint.h>
typedef int16_t my_type;
my_type value = 0xFC7F;
int main(int argc, const char * argv[])
{
printf("0x%02X\n", value);
printf("Type uses %lu bytes\n", sizeof(my_type));
}
```
outputs this
```
0xFFFFFC7F
Type uses 2 bytes
Program ended wit... |
You are printing with printf format specifier X, which is for integers.
Use thehlength specifierto show it as a short.
Live demo
|
I would write a program as follows
```
int main ()
{
FILE *fp = fopen("test.txt", "r")
if (fp == NULL)
{
printf("Sorry, file doesn't exist.");
return 0;
}
return 0;
}
```
Is there any other check that I would need to make sure before or after opening a file?
W... |
No other check needed.
I always also make it a practice of callingfclose, however, when done with the FILE*.
|
How can I use#defineto say that one value consists of the sum of two other values. Would it be allowed and good practice inCto do something like this?
```
#define VALUE_A 2
#define VALUE_B 2
#define SUM_A_B (VALUE_A + VALUE_B)
```
If not, what should I do to achieve this functionality?
|
The Linux and GCC header files do it routinely, if that's a vote of confidence. e.g.:
```
$ grep -r 'define.*+' /usr/include/
...
/usr/include/linux/fdreg.h:#define FD_STATUS (4 + FD_IOPORT )
...
/usr/include/linux/elf.h:#define PT_GNU_STACK (PT_LOOS + 0x474e551)
...
/usr/include/i386-linux-gnu/asm/unistd_32.h:... |
my LD_LIBRARY_PATH is currently at /usr/local/libanytime I try to call any library i get the following error
```
ld: library not found for -libfftw3
clang: error: linker command failed with exit code 1 (use -v to see invocation)
```
for example when I enter this:
```
$ gcc -o prog -L/usr/local/lib -libfftw3 -I/usr/... |
You don't specify the lib prefix of a library when linking, so use-lfftw3, look in /usr/local/lib/ for the actual library name, if it isn't libfftw3.a or libfftw3.so
-lfftw3 should be at the end of all the arguments.
|
I'm trying to call a C function defined in sample_c.c (with function declaration in sample_c.h) from a C++ code. I'm using this declaration in sample_c.h
```
extern "C" void print_c(void);
```
and this definition in sample_c.c
```
extern void print_c(void) {....}
```
and trying to generate lib which I want to link... |
extern "C"is not valid in C. To write a header that can be used for both C and C++ you have to make sure that theextern "C"is not visible when compiled as C:
```
#ifdef __cplusplus
extern "C"
#endif
void print_c(void);
```
|
I know how to loop through a file line by line by reading into a FILE* using fopen, fgets etc
but how can i look through a char array line by line using plain C?
i have googled a lot an can only find stuff that reads from a file.
|
```
#include <stdio.h>
char *sgets(char *s, int n, const char **strp){
if(**strp == '\0')return NULL;
int i;
for(i=0;i<n-1;++i, ++(*strp)){
s[i] = **strp;
if(**strp == '\0')
break;
if(**strp == '\n'){
s[i+1]='\0';
++(*strp);
break;
... |
```
Ceeloss-MacBook-Pro:desktop ceelos$ gcc -o prog -I/usr/local/include test.c
Undefined symbols for architecture x86_64:
"_fftw_destroy_plan", referenced from:
_main in test-IBqBdS.o
"_fftw_execute", referenced from:
_main in test-IBqBdS.o
"_fftw_plan_dft_1d", referenced from:
_main in test-I... |
It's telling you that you forgot to use-Land-lto tell gcc where the FFTW libraries are and what they're called.
|
I have two int values that I want to combine into a decimal number. So for example, I have A = 1234 and B = 323444. Both are int and I do not want to change it if possible.
I want to combine them to get 1234234233.323444.
My initial method was to divide b by 1e6 and add it to A to get my value.
I assigned
```
int A... |
Try like this:
```
C = A + (B/ 1000000.0);
```
ie, make the denominator as double so that when integer by integer division is made it does not return weird results like you are getting.
NOTE:-
Integer/Integer = IntegerInteger/Double = DoubleDouble/Integer = DoubleDouble/Double = Double
|
I am trying to compile a C program in the terminal.
This is my command:
```
gcc -1 string -o syncing.c -o syncing
```
This is my result:
```
clang: error: no input files
```
I know that-1... indicates the library I used,syncing.cis the C file I am trying to compile.
What am I doing wrong with my command or is it... |
Please read up onhow to use GCC,GCC command-line optionsand alsoofficial command-line documentation. You are telling it thatsyncing.cis your output file. But you want it to be your input file.
Also, I am not so sure on the-1there. You might want to have a look atthison how to include/link external libraries.Hereare m... |
I am trying to cast an array of uint8_t to an array of uint32_t, but it seems not to be working.Can any one help me on this. I need to get uint8_t values to uint32_t.I can do this with shifting but i think there is a easy way.
```
uint32_t *v4full;
v4full=( uint32_t *)v4;
while (*v4full) {
if (*v4full & 1)
... |
Given the need to get uint8_t values to uint32_t, and the specs on in4_pton()...
Try this with a possible correction on the byte order:
```
uint32_t i32 = v4[0] | (v4[1] << 8) | (v4[2] << 16) | (v4[3] << 24);
```
|
I can't understand why this
```
#include <stdio.h>
#include <stdint.h>
typedef int16_t my_type;
my_type value = 0xFC7F;
int main(int argc, const char * argv[])
{
printf("0x%02X\n", value);
printf("Type uses %lu bytes\n", sizeof(my_type));
}
```
outputs this
```
0xFFFFFC7F
Type uses 2 bytes
Program ended wit... |
You are printing with printf format specifier X, which is for integers.
Use thehlength specifierto show it as a short.
Live demo
|
I have 2 arrays say
sum:
```
68
78
25
45
85
```
Index:
```
0
1
2
3
4
```
I did bubble sort on sum and got as:
```
25
45
68
78
85
```
Now, I need to know sort index array with respect to the sum array. So, my output of array should be:
```
2
3
0
1
4
```
How can I do that?
|
I'd recommend you sort the index array instead, and have the comparisons made using the values the indexes "point" to. So then you don't actually need to sort the "value" array just the "index" array.
|
when I pass a const int array to a function that gets int array there is compiler error but
when I pass an int array to a function that gets const int array its OK.
why is this happening? I thought mispassing argument is compiler error.
|
Not doing something you're allowed to do is fine.
Doing something you're not allowed to do is not fine.
|
This question already has answers here:How come an array's address is equal to its value in C?(6 answers)Closed9 years ago.
I have a "v" array that I want to pass to a function. Are "v" and "&v" equivalent or is there any difference between them?
For example:
```
char v[4]
scanf("%s", v);
scanf("%s", &v);
```
|
vis address ofv[0]and&vis address of whole array. Fortunately both will have same value. But any arithmetic on these pointers will access differently. For example
(v+1)and(&v + 1)are not same.
|
I am iterating over all the handles opened by my process after making sure that I have opened up a volume handle. During iteration, I use GetFinalPathNameByHandle() to receive information about object associated with the certain handle but as I see it this function only works with files and returns ERROR_INVALID_HANDL... |
You are doing this all wrong. When you create a handle, remember it. When you are done with it, close it.
You cannot hope to be able to enumerate all open handles in your process and close a bunch of them that meet some criteria. You have no way of knowing whether or not the handle is in use. There will be handles op... |
when we put put delay, it will put a delay between doing the up line and down line or it will put a delay in doing all of the lines in our code?
```
int main()
{
if ( kbhit() )
{
E = getCommand();
doCommand(E);
delay(100);
}
}
```
|
There is no standarddelayfunction, but many non-standard headers (like dos.h) and custom implementations are available in which it is used to suspend execution of a program for a particular time.
So, after executingdoCommand(E), your program will wait for 100 milliseconds, i.e. it will pause for that time period, bef... |
I have been trying to figure out how to make an app similar to emacs in that when you run it, it runs in the terminal but it takes up the whole terminal and acts almost like a window. I can't find anything online about this, can anyone give me pointers of where to get started to figure this out?
|
For *nix, there isncurses.
Wikipediaexplains it to you: It is a library to write "GUI-like" applications in text format.
Also:Ncurses for Windows
|
Obviously the compiler has to store the information whether variable x is unsigned int or signed int, float or whatever, but where and how?
Is there some sort of lookup table? Where in memory do I find it, in which section of the executable?
|
It is implicit, in the instructions that the compiler chose.
For instance, if address 18 contained afloat, the compiler may use an instruction to load a floating-point register from address 18. And if it's neighbor at address 20 contained anint, the compiler may load an integer register from the previous address + 2.... |
I have the following typedef struct
```
typedef unsigned int NOTE_FREQ;
/*******A_MUSIC_ELEMENT structure****************/
typedef struct {
NOTE_FREQ frequencyValue;
int duration;
} A_MUSIC_ELEMENT;
```
Now I want to make an array of A_MUSIC_ELEMENT and with specific values.
```
A_MUSIC_ELEMENT ZTitleSc... |
The value ofBPM1could change so the compiler won't allow it as an argument for the initializer list.
If you want to use named constants, try usingenum.
|
Is there a way to create a Simulink bus from the definition of a C struct? Let's say I have some C struct definition in a header file:
```
typedef struct {
double a, b;
} u_T;
```
Can I use this to automatically generate aSimulink.Busobject?
Edit:Is there a tool that generatesMatlabcode for creatingSimulink.Busob... |
This is supported in the latest version of MATLAB (2017a). Use the following command.
```
importInfo = Simulink.importExternalCTypes(headerFiles)
```
For more info see:https://www.mathworks.com/help/simulink/slref/simulink.importexternalctypes.html
|
I'm coding a snake game in C and my compiler is turbo C.
I've got a problem with moving the snake. I need a function or a way of coding so that I can move my snake without the keyboard waiting for a key to be pressed. but if a key is pressed some specific actions are to be done. I used the structure below but it doesn... |
kbhit is a function. When you write if(kbhit) you are testing if the function exists. Instead call the function by writing if(kbhit()).
|
I need to find the number of current SSL connections for a SSL Context.
Does openssl provide any API to get this number?
Checked the SSL_CTX man page andhttp://www.openssl.org/docs/ssl/ssl.html, couldn't find any reference.
openssl does provide APIs to get the total number of connections:SSL_CTX_sess_number, but thi... |
I did not find any straight forward way to do this.
I ended up doing this by maintaining a global variable and protect its access by a mutex (since mine was a multi-threaded program)
Every time a new connection is created, increment the count, and decrement it when a connection closes.
Not exact answer but a conven... |
```
time_t tInicio;
time(&tInicio);
int TempSim=1;
while( ( (int)difftime(time(NULL),tInicio) )<TempSim) {
printf("TESTE");
}
```
Im trying to make this While loop to keep going for 1 minute but its doing way less any sugestion to accomplish this ? im using unix... |
The unit of time_t is seconds. Try:
```
int TempSim=60;
```
I'd advise to put some delay after the printf, or else you'll get lots and lots of output.
Perhaps: sleep(1)
Or: usleep(500 * 1000) to sleep 500ms.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question
I wonder if there are studies and attempts in designing a float-like ( IEEE754 ) type, wh... |
Are you looking forfixed pointnumbers ordecimal floating points? There's even an implementation of them ingcc. See alsotheseresources about decimal arithmetic.
|
I have an array of pointers, namelychar *nline[MAX_M]. What is the most effective way to copy eachnline[i]to the ith-line of a tablechar TAB[MAX_M][MAX_N]; I've tried
```
for (i = 0; i < M_max; i++)
for (j = 0; j < N_max; j++)
TAB[i][j] = *(nlinha[i] + j);
```
But it has added garbage to my table.
|
Usestrncpy:
```
for (i = 0; i < M_max; i++)
strncpy( TAB[i] , nline[i] , MAX_N ) ;
```
Make sure your array of pointersnlinehas valid pointers.
|
I ran gcc (within a makefile) and I got a lot of this:
```
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 1 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/u... |
One of the major reason for this error is that you have a missingmain()function.
```
int main()
{
// Your code here
}
```
|
I'm trying to create dynamic string array to be the buffer for reading a file. The point is that the array must be declared with given size, but it's got to resize if file contains more lines than buffer size is. Buffer I've created looks like this:
```
#define N 32
char **array = (char**) malloc((N+1)*sizeof(char*)... |
You need two dimensions, like such:
```
char **array = malloc((N+1) * (numEntries) * sizeof(char));
```
Note I'm usingsizeof(char), notsizeof(char *).
|
I wonder if its okay to comment methods in c in the same way you comment code in java-language?
```
/**
*
* @param x
* @param y
* @return
*/
protected boolean myMethod(int x, int y) {
return true;
}
```
that is in the same manner in c
```
/**
*
* @param x
* @param y
* @return
*/
int myMethod(int x,... |
Of course its up to the programmer but I would like to know if
c-programmers uses these @param or not?
In C, whatever you put inside the/**/is treated as comments. But I dont think@paramhas got anything to do for it inC.
As far as@is concerned the@in Java is for the Javadoc functionality.
|
I have char array that contains information like so (which is basically string) :
```
char arr[] = "Age: 22 Height: 180 Weight: 80";
```
I want to get specific information from this Char array. For example i need Height number (which would be 180 in this case) and store it in another Char array.
I can get to "Heigh... |
If you need the numbers, usesscanf():
```
int age, height, weight;
const int result = sscanf(arr, "Age: %d Height: %d Weight: %d", &age, &height, &weight);
if (result < 3) // error: couldn't match all elements
```
|
I am building a linux device using make and i need to use string.h in my device. I tried to add /usr/include to make file but it does not work. can any one help me on adding another include path to make file.
my make file is
```
KBUILD_CFLAGS += -w
obj-m += netlinkKernel.o
all:
make -w -C /lib/modules/$(shell u... |
That's because justusr/include/isn't a proper compiler flag. You need to use e.g.-I/usr/include/.
However, using libraries from userspace in a kernel driver might not work as you expect it to, like not at all. The kernel should have have it's own string library (including the"string.h"header file) that you should use... |
When defining a macro (e.g.#define BALL). Why do people use uppercase letters? I can write something like#define ball. It is not in uppercase, but it works.
|
It's convention. It makes reading and understanding code easier. It's not required, but recommended.
|
I am trying to run this command
```
ld -Ttext 0x1000 -o kernel.bin loader.o main.o video.o
```
but it returnsld: unknown option: -Ttext
Is there any alternatives to this action or a way to make ld work?
Here is written, that option -Ttext exists, but in my case it shows that nohttp://linux.about.com/library/cmd/bl... |
"-Ttext" is where in memory the text(code) segment will be. The macintosh ld does not support that option. It does support "-segaddr text"(it might not be text, though, it might be _text or __text). If you are writing an operating system, you probably want a separate toolchain because the macintosh toolchain is onl... |
I'm a beginner in programming so I would like a simple answer :)
I have a for loop with multiple conditions, which prints out two arrays. It works, but i get a warning and a red line under for(). Why is it so and how can I avoid it? I'm writing it in C and I use a Geany compiler in Ubuntu. :)
```
for((i=LEN-1) && (j... |
```
for(i=LEN-1,j=1 ; (i>=LEN-3) && (j<=PODIUM); i--, j++)
```
EDIT:It works because this is the correct syntax. you don't need to use and operator to combine two initializations or two increments. you can just use the,
|
When defining a function this way:
```
void someFunction(int x[][n]){
//Function instruction
}
```
What is the x objet exactly:
Is it an array of n pointers to an array of undefined amount of integers?
What is the synonymous definition using pointers syntax.
How the program allocat the x object in memory.
|
When you define function as
```
void someFunction(int x[][n]) { ... }
```
copiler interprets it as
```
void someFunction(int (*x)[n]) { ... }
```
Is it an array of n pointers to an array of undefined amount of integers?
No.xis a pointer to an array ofnintegers.
What is the synonymous definition using pointers sy... |
I'm working on a kernel module. Long story short: I need to allocate some memory and make it stay there after the module is unloaded. Is it possible? How?
Please keep in mind I'm not asking if that is a good idea. I have my reasons, which are good.
|
It's easy enough to do, really. All you have to do is dynamically allocate the memory in the module init function and they fail to deallocate it in the exit function. In other words, create a deliberate memory leak.
You'll need to be careful during the init though, to avoid doing the allocation (and syscall table pat... |
I have got snippet of old c-code with that lines (result is just slash sign):
```
putchar('/' //**/
1 / 1 /'\1');
```
Can anyone explain this snippet? What does this symbols mean?
P.S. By the way it compiles well with std=c89 flag in gcc, but not with std=c99.
|
That's a division, followed by an empty comment. In C99 mode, it's a new-style comment, causing a syntax error because there's no division operator now.
|
I'm wondering for a solution to the below problem. Please help.
Problem:
```
struct s{
int a;
int b;
}st;
```
I want a function to initialize the values at runtime. The problem is that I want to make it generic, so I want to pass the member name as input to the function and get it initialized.
```
fun_init(char* m... |
C does not provide a way to find a symbol by name. Seethis threadfor more information.
The simplest solution here is to use anassociative array.
Read this threadif you need to mix value-types. (In your example, all value types are int, so you might not need this.)
|
When defining a function this way:
```
void someFunction(int x[][n]){
//Function instruction
}
```
What is the x objet exactly:
Is it an array of n pointers to an array of undefined amount of integers?
What is the synonymous definition using pointers syntax.
How the program allocat the x object in memory.
|
When you define function as
```
void someFunction(int x[][n]) { ... }
```
copiler interprets it as
```
void someFunction(int (*x)[n]) { ... }
```
Is it an array of n pointers to an array of undefined amount of integers?
No.xis a pointer to an array ofnintegers.
What is the synonymous definition using pointers sy... |
I'm working on a kernel module. Long story short: I need to allocate some memory and make it stay there after the module is unloaded. Is it possible? How?
Please keep in mind I'm not asking if that is a good idea. I have my reasons, which are good.
|
It's easy enough to do, really. All you have to do is dynamically allocate the memory in the module init function and they fail to deallocate it in the exit function. In other words, create a deliberate memory leak.
You'll need to be careful during the init though, to avoid doing the allocation (and syscall table pat... |
I have got snippet of old c-code with that lines (result is just slash sign):
```
putchar('/' //**/
1 / 1 /'\1');
```
Can anyone explain this snippet? What does this symbols mean?
P.S. By the way it compiles well with std=c89 flag in gcc, but not with std=c99.
|
That's a division, followed by an empty comment. In C99 mode, it's a new-style comment, causing a syntax error because there's no division operator now.
|
I'm wondering for a solution to the below problem. Please help.
Problem:
```
struct s{
int a;
int b;
}st;
```
I want a function to initialize the values at runtime. The problem is that I want to make it generic, so I want to pass the member name as input to the function and get it initialized.
```
fun_init(char* m... |
C does not provide a way to find a symbol by name. Seethis threadfor more information.
The simplest solution here is to use anassociative array.
Read this threadif you need to mix value-types. (In your example, all value types are int, so you might not need this.)
|
I have 4 bytes of space to create a random number. The Last byte is used for container and slot (Not relevant to this question) so I have 3 bytes to fill the current time (epoch also will do)
I have the following so far:
```
uint32_t create_handle(uint8_t container_id, uint8_t file_slot)
{
uint32_t handle;
... |
You are shifting now by 24, which only leaves 8. I think you want to just shift by 8. The& ~(0xff)is redundant.
How about using one of the random number libraries? or are you never going to need more than one handle per second?
|
I am using two different datatypes and doing the calculation by mathematical operators.
```
int x = 1;
double y = 2;
int z;
z = x*y;
printf("Result %d\n", z);
```
Will it be Ok??
|
You'll lose precision (probably getting a warning) if the value has a fractional part. It will be truncated.
Example:
```
const float PI = 3.14;
int notPi = PI;
```
notPiwill be truncated to3
|
I want to save the value of different types of variable in a comma separated csv file.
right now I have something like
```
printf("[%-2d]|%08x%s[%s][%s][%08x][%08x]", a,b,c,d,e,f,g);
```
what I want is to write in a text file the values like:
```
a,b,c,d,e,f,g
```
Here are the constraints.ais an unsigned integer ... |
printfhas its cousinfprintfwhich will happily print whatever you want into a file you've opened/created withfopen
```
fprintf(stream, "%-2d, %08x, %s, %s, %s, %08x, %08x\n", a,b,c,d,e,f,g);
```
|
This is a 16 bit unsigned value that the caller task assigns while sending a message. For each new message the value increments by one, eventually wrapping round and producing a sequence 0,1,2,……65533,65534,65535,0 etc. So I need a counter to find targets. I need help in getting the most efficient way to wrap around. ... |
If you are using anunsigned intcounter then you can simply do(x + 5) & 0xffffU- there is no need to check for overflow because arithmetic in unsigned types is defined to wrap around in C, and unsigned types must use a pure binary representation.
|
I am trying to implement regular expression in C, I have the following code to find all the string which contains '*' in it,
```
regex_t regex;
regcomp(®ex, "^[A-Za-z0-9\*]+$", 0);
if (!regexec(®ex, args[j], 0, NULL, 0)) {
printf("string found");
}
```
Is this the right way to do it? My code is not matchi... |
In C++, the character\needs to be escaped. So if you want to escape an regex*, you need to do\\*. That should fix the problem. Whenever you use the backslash in a string, you need to escape it like that. If you ever need to find it in a string with the regex, you'll need to search for it with\\\\.
|
I am using sendfile to send and receive files between the client and server, sending the file is fine, but when receiving the file, it returns -1, and the errno is 29 illegal seek, I am not sure what is wrong.
```
int fd = open(filename, O_WRONLY | O_CREAT);
off_t offset = 0;
int ret = sendfile(fd, sockfd, &offset, f... |
The man page forsendfile()says:
Thein_fdargument must correspond to a file which supports mmap(2)-like operations (i.e., it cannot be a socket).
Thein_fdis the second argument, the one you namedsockfd. That suggests your problem is that the input file descriptor is not valid for use withsendfile().
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.