question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I have the following code:
```
sem_t *semFull = sem_open("/semFull", O_CREAT, 0644, 0);
sem_t *semEmpty = sem_open("/semEmpty", O_CREAT, 0644, shared.buffSize);
```
This piece of code works perfectly on Linux but when I try to execute it on OS X I keep getting segmentation fault
Can anyone help me solve this issue?
Thanks
|
You shouldn't usesem_ton OS X, you should usesemaphore_t.
You need to import the following libraries
```
#include <mach/semaphore.h>
#include <mach/task.h>
#include <mach/mach_init.h>
```
And you can create your semaphores using:
```
semaphore_create(mach_task_self(), &shared.full, SYNC_POLICY_FIFO, 0);
semaphore_create(mach_task_self(), &shared.empty, SYNC_POLICY_FIFO, shared.buffSize);
```
Your problem should be solved using this approach.
|
After a c source code is compiled, an object file is created. I can only see the .exe file so where can I find the object file? I am using cygwin on windows so I am using gcc to compile programs.
|
Many compilers support the-coption to compile only and produce object files.
If you use amake-based build, object files may be treated asintermediateand automatically removed. You may declare them in the.PRECIOUS:target to avoid this.
If your program consists of only a single C source file, you could use
```
gcc -c file.c # Creates file.o, but no file.exe
gcc -o prog file.o # Creates prog.exe by linking file.o with appropriate libs
```
|
This question already has answers here:A different way to malloc a 2D array?(3 answers)Freaky way of allocating two-dimensional array?(3 answers)Closed7 years ago.
Every time I allocate the memory for a 2D array first I create an array ofint**and then with a for I allocate the memory for each element.
For example:
```
int ** arr = malloc(N*sizeof(int *));
for(i=0; i< N; i++) arr[i] = malloc(M*sizeof(int));
```
Wouldn't be possible allocate the memory like:
```
int ** arr = malloc(N*sizeof(int[M]));
```
or
```
int ** arr = malloc(sizeof(int[N][M]));
```
in order to avoid thefor?
|
like this :int (*arr)[M] = malloc(sizeof(int[N][M]));
arris pointer toint[M].
use likearr[0][M-1];
andfree(arr);
|
How can I get the number's position by c or Javascript.
It is a ordered number array,like
```
1 2
3 4
5 6
```
how can I make a function to get the number 3 is 2-1,and 6 is 3-2
Thank you very much!
|
You could do something like this in javascript
var data = [
[1, 2],
[3, 4],
[5, 6]
];
var getPos = function(elem, data) {
var result = '';
data.forEach(function(value, index) {
value.forEach(function(v, i) {
if (v == elem) result += (index + 1) + '-' + (i + 1);
});
});
return result;
}
console.log(getPos(5, data));
|
The exposed API from c is:
```
bam_hdr_t *bam_hdr_init(void);
```
how do I write its wrapper in Julia?
ccall((:bam_hdr_init,"lib.so"), Ptr{bam_hdr_t})works in Julia v0.5, but not in v0.4.
|
ccall((:bam_hdr_init,"lib.so"), Ptr{bam_hdr_t},())works for both versions of Julia
|
```
while (!EOLorEOFfound) {
int ch == fgetc(stdin);
EOLorEOFfound = ch == '\n' || ch == EOF;
}
```
Note:EOLorEOFfoundis of type bool.
I was given this answer by a StackOverFlow user concerning another problem. See here:
How to determine if fgets stopped before all letters were read?
Now, i have been puzzeling what the expression in the last line of code actually does. I suspect it is some form of the ternary operator maybe?
|
```
EOLorEOFfound = ch == '\n' || ch == EOF;
```
does the same as
```
EOLorEOFfound = (ch == '\n' || ch == EOF);
```
that is, assigning the result of a boolean expression to a variable. No magic here.
|
When I declare structure given below, it is throwing compilation error.
```
typedef struct{
const char x; //it is throwing compilation error
const char y;
}A;
void main()
{
A *a1;
a1 = (A*)malloc(2);
}
```
How can I make structure's field (charactersxandy) as constant?
|
That should be fine, but of course you can't assign to them, only use initialization.
So it doesn't make a lot of sense to allocate an instance on the heap.
This works:
```
#include <stdio.h>
int main(void) {
typedef struct {
const int x, y;
} A;
A my_a = { 12, 13 };
printf("x=%d\ny=%d\n", my_a.x, my_a.y);
return 0;
}
```
It prints:
```
x=12
y=13
```
Also,please don't cast the return value ofmalloc()in C.
|
I am debugging awhileloop using conditional breakpoints ingdb. There are multiple large arrays that are getting created inwhileloop. I would like to print them in a file while debugging so that I can compare usingdifflater.
I am able to visualize content at the console using the following command :
```
(gdb) p *&ff[0]@10
```
whereffis my array. Kindly tell how I can redirect them to text file.
|
You can use:
```
(gdb) set logging file large_array.txt
(gdb) set logging on
```
By default the logging file name isgdb.txt
You can find more details at:https://sourceware.org/gdb/onlinedocs/gdb/Logging-Output.html
There is also one WAgdb --args a.out arg1 ... |& tee gdb_out.txt
|
I'm triying to read a string with a specific format in C using scanf()
The string has the format:
```
<LET,LET,LET> op
```
whereLETis a capital letter andophas to be'+'or'%'.
These are valid entries:
```
<A,B,C> +
<A,W,Z> %
<Q, X,W> +
```
These are not:
```
<A,b,C> +
<A,W,Zddddd> %
<Q,X,W> *
```
I'm trying something like this
```
#include <stdio.h>
int ret = 0;
char str[8];
ret = scanf("%8[^\n]",str);
```
butstrends up with garbage. I just don't know how to read it and how to get only capital letters.
Thanks
|
try this:
```
#include <stdio.h>
int main(void) {
char let1[2], let2[2], let3[2], op[2];
char line[80];
while(fgets(line, sizeof line, stdin)){
if(sscanf(line, "<%1[A-Z], %1[A-Z], %1[A-Z]> %1[+%]", let1, let2, let3, op) == 4)
puts("valid");
else
puts("invalid");
}
return 0;
}
```
|
Are there any better way to loadunsigned chararray toshortusing SSE? Like
```
unsigned char foo1[16];
__m128i foo2 = _mm_loadu_si128((__m128i*)foo1);
```
I wantfoo2to store elements in theshort intdata type.
|
Not completely clear what you want.
But if you want SSE register with one short value per each input byte, then you probably need this (untested):
```
__declspec( align( 16 ) ) unsigned char foo1[ 16 ];
// Fill your array with data
const __m128i src = _mm_load_si128( ( __m128i* )foo1 );
const __m128i zero = _mm_setzero_si128();
const __m128i lower = _mm_unpacklo_epi8( src, zero ); // First 8 short values
const __m128i higher = _mm_unpackhi_epi8( src, zero ); // Last 8 short values
```
|
I can't find any information how to implement in C module of iOS Xcode project lseek() for large files:
```
llseek()
```
or
```
lseek64()
```
Compilation with:
```
#define _LARGEFILE64_SOURCE
#define _FILE_OFFSET_BITS 64
```
has no effect.
How is this possible to do?
|
You need to use fseeko() and ftello() when seeking to specific 64bit offsets in a file. Pass the file offset as a off_t instead of int and it will work on both 32bit and 64bit systems.
|
I know how to create shared libraries usinggccandln, but how do I create a shared library using onlyldwhen I have object files (from c++ or c code) as input and how do I swap onto new version of library?
|
how do I create a shared library using only ld when I have object files (from c++ or c code) as input
You could rungcc -v -shared ...to discover what optionsgccpasses told. You could then pass the same arguments tolddirectly, and you should end up with identical result.
Note: this isill-advised (don'tdo this): the arguments change with different versions ofgccandld, and they change from one OS release to the next.
It is very common to construct link lines forldthat used to be correct some years ago, but no longer are. The bugs introduced when doing this are often low-level and subtle, and beyond most programmers' ability to understand and fix.
|
When I declare structure given below, it is throwing compilation error.
```
typedef struct{
const char x; //it is throwing compilation error
const char y;
}A;
void main()
{
A *a1;
a1 = (A*)malloc(2);
}
```
How can I make structure's field (charactersxandy) as constant?
|
That should be fine, but of course you can't assign to them, only use initialization.
So it doesn't make a lot of sense to allocate an instance on the heap.
This works:
```
#include <stdio.h>
int main(void) {
typedef struct {
const int x, y;
} A;
A my_a = { 12, 13 };
printf("x=%d\ny=%d\n", my_a.x, my_a.y);
return 0;
}
```
It prints:
```
x=12
y=13
```
Also,please don't cast the return value ofmalloc()in C.
|
I am debugging awhileloop using conditional breakpoints ingdb. There are multiple large arrays that are getting created inwhileloop. I would like to print them in a file while debugging so that I can compare usingdifflater.
I am able to visualize content at the console using the following command :
```
(gdb) p *&ff[0]@10
```
whereffis my array. Kindly tell how I can redirect them to text file.
|
You can use:
```
(gdb) set logging file large_array.txt
(gdb) set logging on
```
By default the logging file name isgdb.txt
You can find more details at:https://sourceware.org/gdb/onlinedocs/gdb/Logging-Output.html
There is also one WAgdb --args a.out arg1 ... |& tee gdb_out.txt
|
I'm triying to read a string with a specific format in C using scanf()
The string has the format:
```
<LET,LET,LET> op
```
whereLETis a capital letter andophas to be'+'or'%'.
These are valid entries:
```
<A,B,C> +
<A,W,Z> %
<Q, X,W> +
```
These are not:
```
<A,b,C> +
<A,W,Zddddd> %
<Q,X,W> *
```
I'm trying something like this
```
#include <stdio.h>
int ret = 0;
char str[8];
ret = scanf("%8[^\n]",str);
```
butstrends up with garbage. I just don't know how to read it and how to get only capital letters.
Thanks
|
try this:
```
#include <stdio.h>
int main(void) {
char let1[2], let2[2], let3[2], op[2];
char line[80];
while(fgets(line, sizeof line, stdin)){
if(sscanf(line, "<%1[A-Z], %1[A-Z], %1[A-Z]> %1[+%]", let1, let2, let3, op) == 4)
puts("valid");
else
puts("invalid");
}
return 0;
}
```
|
Are there any better way to loadunsigned chararray toshortusing SSE? Like
```
unsigned char foo1[16];
__m128i foo2 = _mm_loadu_si128((__m128i*)foo1);
```
I wantfoo2to store elements in theshort intdata type.
|
Not completely clear what you want.
But if you want SSE register with one short value per each input byte, then you probably need this (untested):
```
__declspec( align( 16 ) ) unsigned char foo1[ 16 ];
// Fill your array with data
const __m128i src = _mm_load_si128( ( __m128i* )foo1 );
const __m128i zero = _mm_setzero_si128();
const __m128i lower = _mm_unpacklo_epi8( src, zero ); // First 8 short values
const __m128i higher = _mm_unpackhi_epi8( src, zero ); // Last 8 short values
```
|
I can't find any information how to implement in C module of iOS Xcode project lseek() for large files:
```
llseek()
```
or
```
lseek64()
```
Compilation with:
```
#define _LARGEFILE64_SOURCE
#define _FILE_OFFSET_BITS 64
```
has no effect.
How is this possible to do?
|
You need to use fseeko() and ftello() when seeking to specific 64bit offsets in a file. Pass the file offset as a off_t instead of int and it will work on both 32bit and 64bit systems.
|
I know how to create shared libraries usinggccandln, but how do I create a shared library using onlyldwhen I have object files (from c++ or c code) as input and how do I swap onto new version of library?
|
how do I create a shared library using only ld when I have object files (from c++ or c code) as input
You could rungcc -v -shared ...to discover what optionsgccpasses told. You could then pass the same arguments tolddirectly, and you should end up with identical result.
Note: this isill-advised (don'tdo this): the arguments change with different versions ofgccandld, and they change from one OS release to the next.
It is very common to construct link lines forldthat used to be correct some years ago, but no longer are. The bugs introduced when doing this are often low-level and subtle, and beyond most programmers' ability to understand and fix.
|
Observe the following block of code:
```
//*
... code block ...
//*/
```
It can be enabled/disabled using just the first slash.
```
/*
... code block ...
//*/
```
Was this by design, or is it a happy coincidence?There doesn't seem to be any history on the matter.
|
I doubt you can say it wasdesignedthis way. Block comments were introduced in C way before single-line comments appeared - and this is what your code ends up being after you add another slash.
I'd rather call it a happy coincidence.
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question
What's really happening behind?
```
int a=10,b=5,c=3;
b!=!a;
c=!!a;
```
Why the values ofbandcare 5 and 1 respectively?
|
bis5because you've assigned it that value and never changed it, since
```
b!=!a;
```
...is just a condition that you don't do anything with, not any form of assignment.
cis1becauseais10and!10is0, and!0is1, thus!!ais1(ais10).
|
```
int n;
int i, j, k = 0;
for (i = n/2; i <= n; i++) {
for (j = 2; j <= n; j = j * 2) {
k = k + n/2;
}
}
```
Just need to calculate the time complexity of the code snippet and the answer is Θ(nLogn) but can you explain how it is Θ(nLogn)
|
It's really not that difficult.
The outer loop runsn/2times. That isO(n)complexity.
The inner loop again depends onnonly. It doesn't depend on theifrom the first loop. So for the complexity of the inner loop we can ignore completely the outer loop. How fortunate!.jmultiples each time by2so we havelogarithm base 2. That isO(log(n)).
The loops are nested so we multiply, thus ending with:
```
O(n log(n))
```
|
Output is:10and it gives no error.
```
int main(){
int j=10;
int *i=&j;
printf("%d",*i);
return 0;
}
```
but it gives me an error:
```
int main(){
int *i;
int j=10;
*i=&j;
printf("%d",*i);
return 0;
}
```
I understand that pointer de-referencing is causing the error. But how is that happening?
|
Because you are using an uninitialized pointer.
Your*i = &jshould bei = &j
|
There may or may not be a duplicate to this question, although I tried to find one but everyone's answer seemed to only be referring to thedeclaration/prototype. They specify that a definitionvoid foo() { }is the same asvoid foo(void) { }, but which way should I actually use? In C89? In C99? I believe I should start usingvoid foo(void);for myprototypedeclarations, but is there any difference at all if I usevoidor not for thedefinition?
|
They are different,void foo(void)declaresfooas a function that takes NO argument, and returns nothing.
While forvoid foo(), the functionfootakes UNSPECIFIED number of arguments, and returns void.
You should always use the first one for standard conforming C.
|
I was searching for a way to find out the length of arequest_queue(that is defined as a structure inlinux/include/linux/blkdev.h).
However I am new to the kernel development and can't figure out where is
the actual list of requests to be processed by an elevator.
Is there a way to iterate requests in a queue or at least find a number
of them?
|
The requests of a queue are linked bystruct list_head queue_head. You can iterating all the request using the linked list functions, you can see some examples here:
http://lxr.free-electrons.com/source/include/linux/blkdev.h?v=2.4.37#L271
|
Im trying to learn c, I'm using tutorialspoint, and the function they give me doesn't do anything on my computer, the function is:
```
#include <stdio.h>
int main (){
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
```
Am I missing something?
|
It is good to introduce some error checking with file streams
Do
```
fp = fopen("test.txt", "w+");
/*
* Try creating the file in the same folder for a start
*/
if(fp!=NULL)
{
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
}
else
{
/* There are multiple reasons you can't open a file like :
* You don't have permission to open it
* A parent directory doesn't exist and so on.
*/
printf("Can't open the file for write\n");
}
fclose(fp);
```
|
I am trying out some ways of measuring the TLB size on my machine. I somehow needed to ensure that the CPU does not cache the elements of the array I am using to measure the average access time per page. So I tried this code inside the loop that I have, using the answer overhere:
```
FILE *fp;
fp = fopen("/proc/sys/vm/drop_caches", "w");
fprintf(fp, "3");
fclose(fp);
```
However, I am getting theSegmentation Fault (core dumped)error. I have no idea why this could be happening. I am not very good with C and any help would be appreciated. Thanks.
|
Be sure to check whether the open of the file was successful, since you are writing to a system file, that certainly requires you run in privileged mode.
```
FILE *fp;
fp = fopen("/proc/sys/vm/drop_caches", "w");
if (fp == NULL) {
printf("error %d: %s\n", errno, strerror(errno));
// error handling, exit or return
}
fprintf(fp, "3");
fclose(fp);
```
|
I'm trying to create a C++ dll. I have followed the msdn tutorial but I can't compile my dll correctly.
The problem is that any function is exported. I have tested it withdumpbin.exetool andnmtool.
In both cases, there is no detected symbols.
Here is the code of this library:
Header file:
```
#ifndef NLIB_H
#define NLIB_H
#ifdef _WINDLL
#define NLIB_EXPORTS __declspec( dllexport )
#else
#define NLIB_EXPORTS __declspec( dllimport )
#endif
#ifdef __cplusplus
extern "C"{
#endif
NLIB_EXPORTS int fun1(int n);
#ifdef __cplusplus
}
#endif
#endif
```
Source code file:
```
#include "nlib.h"
int fun1(int n) {
return 100;
}
```
|
I have found the error. It's necessary to addNLIB_EXPORTSto the*.cfile also, like this:
```
#include "nlib.h"
NLIB_EXPORTS int fun1(int n) {
return 100;
}
```
|
I want to read argument and then compare it with a character:
```
int main (int argc, char *const argv[]) {
if (argv[1][1] == 'c') {
client();
}
else if (argv[1][1] == 's') {
server();
}
return 0;
}
```
It works if I typeccordd, it also works if I typeccttttt. It's just taking the second character, but I'd like it to work only if I typec.
|
Just change argv[1][1] to argv[1][0] and remember in c/c++ all arrays start in '0'
|
So lets say i have an array of ints (max being its maximum size)
```
array = { 1, 7, 22, 3, 7, ... }
```
and i need to find a way to count the duplicates of each element in the previous array into another array like this one
```
duplicates = { { 1, 2 times }, { 7, 3 times } ...}
```
i know the syntax is wrong i just wanted to exemplify my goal (hope i expressed myself well enough) .. i have been thinking and i cant think of a way to do this (maybe it's simple but im kinda new at this) so i decided to post here for some guidance.
Thanks in advance
|
You could sort the array, maybe with an algorithm likeqsortand then with aforor awhileloop you can count how many times each element appear into the array since the duplicates will be one after another.
If you're under mac/linux type in the terminalman 3 qsortto see how it should be used.
|
bag-implementation.h:
```
typedef struct node {
struct node *next;
char *element;
int repeats;
} Node;
typedef struct{
size_t size;
Node *head;
}Bag;
```
Line that errors in bag.c (which includes bag.h which includes bag-implementation.h):
```
Bag bag_union(Bag bag1, Bag bag2){
Bag union;
return bag1;
}
```
Error:
```
bag.c: In function 'bag_union':
bag.c:188:12: error: expected '{' before ';' token
bag.c:188:7: error: two or more data types in declaration specifiers
make: *** [bag.o] Error 1
```
If I try to compile without creating that bag, then it works fine. What is the issue?
|
unionis a reserved word in C, so you can't have a variable called like this. Simply rename it.
|
I need to select one processor from my Comm to do some works ( I don`t want other processors do the work ).
Since I split my Comm to the groups, I cannot always pick one specific rank ( for example 0) as my master. I need to choose it from my current comm. Any suggestion?
Thank you.
|
The rank of a process is always relative to a communicator. After you split your processes, you can just take process 0 in the new communicator to perform the work you want.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed7 years ago.Improve this question
loop fusion, does it mean the above code will become
```
for(j=1; j<=4,j++){
a[j]=3;
a[j]=a[j]*2*h;
b[j]=6;
b[j]=b[j]+3*k*k;
}
```
|
Aside from using two separate loops, the original code contains lots of redundant statements. One possible improvement would be this:
```
int tmp = 6 * h;
for (j = 1; j <= 4; j++) {
a[j] = tmp;
b[j] = 6 + 3 * j * j;
}
```
The main optimizations:
One loop instead on twoRemoved assignments that get overwritten in the next statementCalculate a value that does not depend on the loop index outside the loop
You should be aware that most of these optimizations would be done by a compiler anyways.
|
There may or may not be a duplicate to this question, although I tried to find one but everyone's answer seemed to only be referring to thedeclaration/prototype. They specify that a definitionvoid foo() { }is the same asvoid foo(void) { }, but which way should I actually use? In C89? In C99? I believe I should start usingvoid foo(void);for myprototypedeclarations, but is there any difference at all if I usevoidor not for thedefinition?
|
They are different,void foo(void)declaresfooas a function that takes NO argument, and returns nothing.
While forvoid foo(), the functionfootakes UNSPECIFIED number of arguments, and returns void.
You should always use the first one for standard conforming C.
|
I was searching for a way to find out the length of arequest_queue(that is defined as a structure inlinux/include/linux/blkdev.h).
However I am new to the kernel development and can't figure out where is
the actual list of requests to be processed by an elevator.
Is there a way to iterate requests in a queue or at least find a number
of them?
|
The requests of a queue are linked bystruct list_head queue_head. You can iterating all the request using the linked list functions, you can see some examples here:
http://lxr.free-electrons.com/source/include/linux/blkdev.h?v=2.4.37#L271
|
Im trying to learn c, I'm using tutorialspoint, and the function they give me doesn't do anything on my computer, the function is:
```
#include <stdio.h>
int main (){
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
```
Am I missing something?
|
It is good to introduce some error checking with file streams
Do
```
fp = fopen("test.txt", "w+");
/*
* Try creating the file in the same folder for a start
*/
if(fp!=NULL)
{
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
}
else
{
/* There are multiple reasons you can't open a file like :
* You don't have permission to open it
* A parent directory doesn't exist and so on.
*/
printf("Can't open the file for write\n");
}
fclose(fp);
```
|
I am trying out some ways of measuring the TLB size on my machine. I somehow needed to ensure that the CPU does not cache the elements of the array I am using to measure the average access time per page. So I tried this code inside the loop that I have, using the answer overhere:
```
FILE *fp;
fp = fopen("/proc/sys/vm/drop_caches", "w");
fprintf(fp, "3");
fclose(fp);
```
However, I am getting theSegmentation Fault (core dumped)error. I have no idea why this could be happening. I am not very good with C and any help would be appreciated. Thanks.
|
Be sure to check whether the open of the file was successful, since you are writing to a system file, that certainly requires you run in privileged mode.
```
FILE *fp;
fp = fopen("/proc/sys/vm/drop_caches", "w");
if (fp == NULL) {
printf("error %d: %s\n", errno, strerror(errno));
// error handling, exit or return
}
fprintf(fp, "3");
fclose(fp);
```
|
I'm trying to create a C++ dll. I have followed the msdn tutorial but I can't compile my dll correctly.
The problem is that any function is exported. I have tested it withdumpbin.exetool andnmtool.
In both cases, there is no detected symbols.
Here is the code of this library:
Header file:
```
#ifndef NLIB_H
#define NLIB_H
#ifdef _WINDLL
#define NLIB_EXPORTS __declspec( dllexport )
#else
#define NLIB_EXPORTS __declspec( dllimport )
#endif
#ifdef __cplusplus
extern "C"{
#endif
NLIB_EXPORTS int fun1(int n);
#ifdef __cplusplus
}
#endif
#endif
```
Source code file:
```
#include "nlib.h"
int fun1(int n) {
return 100;
}
```
|
I have found the error. It's necessary to addNLIB_EXPORTSto the*.cfile also, like this:
```
#include "nlib.h"
NLIB_EXPORTS int fun1(int n) {
return 100;
}
```
|
I want to read argument and then compare it with a character:
```
int main (int argc, char *const argv[]) {
if (argv[1][1] == 'c') {
client();
}
else if (argv[1][1] == 's') {
server();
}
return 0;
}
```
It works if I typeccordd, it also works if I typeccttttt. It's just taking the second character, but I'd like it to work only if I typec.
|
Just change argv[1][1] to argv[1][0] and remember in c/c++ all arrays start in '0'
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed7 years ago.Improve this question
I am relatively new to OpenGL and am using it for a class that requires me to use it with C (no C++). I would like to use .obj files in my code, but do not know how to import them. I have found many importers online for C++, but must use C. Can anyone direct me to an importer or give me the basics on how to write my own/handle and import .obj files into my program. Thanks!
|
Here is an example of WaveFront OBJ loader in C -http://kixor.net/dev/objloader/
|
FromSSL_CTX_load_verify_locations:
SSL_CTX_load_verify_locations - set default locations for trusted CA certificates
Does this means I can put certificates in location (or file), which passed as parameter toSSL_CTX_load_verify_locationsfunction. And are these certificates automatically will be trusted?
|
That is correct. This is how you specify the list of certificate authorities that are trusted.
|
In this source-code of Arwin I saw :
```
fprc_func = GetProcAddress(hmod_libname,argv[2]);
if(fprc_func == NULL)
{
printf("Error: could find the function in the library!\n");
exit(-1);
}
printf("%s is located at 0x%08x in %s\n",argv[2],(unsigned int)fprc_func,argv[1]);
```
Why we useexit(-1)and not useexit(1)here ?
Also please explain theprintfstatement in a understanding way.
|
Whether to use exit(-1) or exit(1) for failure is a personal choice.
POSIX compliant codeuses 1 orEXIT_FAILUREfor failures
In
```
printf("%s is located at 0x%08x in %s\n",argv[2],(unsigned int)fprc_func,argv[1]);
```
Two stringsargv[2]&argv[1](as specified by%s) and an unsigned hexadecimal integerfprc_func(as specified by0x%08x) are printed. The%08in0x%08xis for setting the width to eight. Seeprintf doc.
|
If I run this code is shown to me "segmentation fault", but if in the "for" of the "create" function I set the clause i <1 (ie one cycle), the program is working, why?
```
void create(char ***a,int *length){
int i=0;
*length = 0;
for(i=0;i<4;i++){
++(*length);
(*a)=realloc(*a,(*length)*sizeof(char *));
*(a[i])="Hello\0";
}
}
int main(int argc, char *argv[]) {
int i;
char **a = NULL;
int *l = malloc(sizeof(int));
create(&a,l);
for (i=0; i<(*l); i++) {
printf("%s",a[i]);
}
printf("\n");
return EXIT_SUCCESS;
}
```
what I would like is that at the end, the program show me 4 times "Hello"
|
This
```
*(a[i]) = ...
```
should be
```
(*a)[i] = ...
```
A "string" literal like"Hello"alreadyimplicitlyadds a terminating'\0'character. So there is no need to specify itexplicitlylike in here:"Hello\0".
|
I'm using api on windows (not gdi), and i would like to know how to do square edged line.
```
MoveToEx(hdc, x1, y1, NULL);
LineTo(hdc, x2, y2);
```
My current line output :
I want this line :
thanks, have code
|
You can modify the pen style used to draw your line, specificallyPS_ENDCAP_SQUAREand select that pen into the device context, read the documentation forCPen:
```
LOGBRUSH logBrush;//you need to use LOGBRUSH structure to specifiy brush attributes of the pen when the pen has PS_GEOMETRIC style
logBrush.lbStyle = BS_SOLID;
logBrush.lbColor = RGB(255,0,0);
CPen pen( PS_GEOMETRIC | PS_ENDCAP_SQUARE,10,&logBrush);//creates a pen with a square end caps and width of 10 pixels
SelectObject(hdc,pen.GetSafeHandle());//select the above pen into the device context
MoveToEx(hdc,x1,y1,NULL);
LineTo(hdc,x2,y2);
```
|
What's the reason for FOO returning '0' in the final answer:
```
int FOO = 0, bar = 0, i;
for (i = 0; i < 4; i++) {
int FOO = i;
printf("%d ", FOO);
if (i % 2 == 0)
FOO += bar;
bar++;
}
printf("%d %d", FOO, bar);
```
|
Inside the foo loop, you defined a variable with the same nameFOO, this will shadow theFOOin the outside, which means, theFOOyou use in the loop is a variable local to the block only. The finalprintfis outside the loop, so theFOOit prints is the one resides in the outside scope. The shadowedFOOno longer exists at the this point.
So the code can be treat as same as this:
```
int FOO_out = 0, bar = 0, i;
for (i = 0; i < 4; i++) {
int FOO_in = i;
printf("%d ", FOO_in);
if (i % 2 == 0)
FOO_in += bar;
bar++;
}
printf("%d %d", FOO_out, bar);
```
|
I am having to store sequences of Japanese names written in the Shift-JIS format that are scooped from the internet. I am thinking for storing them in character arrays and writing them to a file with something like:
```
fprintf(fp,"The name is [%s]\n",string_array);
```
My only concern is that if Shift-JIS characters may include '\0' then this will obviously break... but I'm not sure if Shift-JIS ever does. Unfortunately it seems Shift-JIS is such an arcane system that I can barely comprehend the definitions of the system I've found online with enough confidence to answer the question myself.
|
Looking at Wikipedia'sShift-JIS byte map, the byte values 0x00-0x3F are not used as second bytes (and nor are 0x7F or 0xFD-0xFF), so you're fine interpreting'\0'as a null terminator.
|
I learning C and trying and I have written a small program.
```
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int *x = malloc(sizeof(int)*3);
int i;
for(i=0;i<3; i++){
x[i] = i*i;
printf("x[i] = %d\n", x[i]);
}
free(x);
}
```
Right now the output is (ofc it is)
x[i] = 0x[i] = 1x[i] = 4
My question is, how would I change the code to get the output?
x[0] = 0x[1] = 1x[2] = 4
|
```
printf("x[%d] = %d\n",i, x[i]);
```
|
I was reading a c++ code and i came across this problem and i don't know what it mean:
```
uint8 (*const flag_search)[SEARCH_RANGE]=
(uint8 (*)[SEARCH_RANGE])&_flag_search[MAX_MOTION][MAX_MOTION];
```
can someone explain it for me ?
|
```
uint8 (*const flag_search)[SEARCH_RANGE]
```
flag_searchis a const pointer pointing to an array, which containsSEARCH_RANGEelements with typeuint8.
```
(uint8 (*)[SEARCH_RANGE])&_flag_search[MAX_MOTION][MAX_MOTION]
```
&_flag_search[MAX_MOTION][MAX_MOTION]will take the address of_flag_search[MAX_MOTION][MAX_MOTION], and cast it touint8 (*)[SEARCH_RANGE], which is a non-const pointer pointing to an array, which containsSEARCH_RANGEelements with typeuint8.
|
I'm working in this directory structure
```
root: Code
|--src
|--client
|--client.c
|--server
|--server.c
|--lib
|--utility.c
|--include
|--prototype.h
|--utility_lib.h
```
inclient.cfile, I have to include theutility_lib.hfile.
With#include "-I../../include/utility_lib.h"it doesn't work, probably the route is not correct.
Anyone could help me?
|
You can directly include the header file in your code:
```
// file client.c
#include "../../include/utility_lib.h"
```
Or you can tell your compiler where to find the header file:
```
// file client.c
#include <utility_lib.h>
```
Compilation command if the current directory isclient:
```
gcc -c client.c -o client.o -I../../include
```
Compilation command if the current directory issrc:
```
gcc -c src/client.c -o client.o -I../include
```
|
I seem to be having a very strange issue in running a program with Visual Studio C++ 2010. Here is the (very simplified) code:
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void recieve(double, double);
void simple_pass();
void recieve(double x, double y)
{
printf("%d %d\n", x, y);
}
void main(int argc , char **argv)
{
simple_pass();
}
void simple_pass()
{
recieve (0.25, 0.25);
recieve (0.25, 0.75);
recieve (0.75, 0.5);
}
```
When printing the values, x is always 0 and y is something greater than a billion.
Thanks!
|
%dis for ints,%lfis for doubles.
Most compilers would give you a warning for that these days...
|
I am trying to select bits [0:2] and bits [6:8] of the bit-string 1010000000001. Bits [0:2] are 001 and bits [6:8] are 000. I tried to select these bits with:
```
int instr = 0x1401;
int src2 = (instr & 0x0006); //get bits [2:0]
int src1 = (instr & 0x01C0) >> 6; //get bits [6:8]
printf("%04x, %04x",src2, src1);
```
However I am getting that src1 and src2 are both 0000. Can someone please help me understand what I am doing incorrectly so I can select bits [0:2] and [6:8]?
|
Look at this code:
```
#include <stdio.h>
int main (void) {
unsigned instr = 0x1401;
unsigned src2 = instr & 0x0007; // 7 in hex == 0000 0000 0111 in binary
unsigned src1 = (instr & 0x01C) >> 6; // 1C in hex == 0001 1100 0000 in binary
printf("%04x, %04x", src2, src1);
}
```
It masks out the desired bits ininstrand shifts them by the correct offset. Also, when doing bit manipulation, unsigned types are preferred.
|
I have a struct of words:
```
typedef struct {
char *word;
unsigned long occurrences;
} Word;
```
and I want to malloc an array of these but I don't know how large the size will be. Is there a way to malloc an array of structs without knowing the size of the array beforehand?
Thanks.
|
You can allocate memory withmalloc(), and then change size withrealloc()
```
typedef struct {
char *word;
unsigned long occurrences;
} Word;
int main()
{
Word *arr = malloc(sizeof(Word) * n);
// do smth
// need more
arr = realloc(arr, sizeof(Word) * more);
return 0;
}
```
|
```
execl("/usr/bin/cc","cc","myprog.c",NULL)
```
I use the this line for compiler to myprog.c in myMainProg. But myprog.c have #include "math.h" . So I have to add -lm. How can I do that?
|
Command (from shell) to link your program should be:
```
cc myprog.c -o myprog -lm
```
So if you want to useexeclto compile it from another program you should use:
```
execl("/usr/bin/cc","cc","myprog.c", "-o", "myprog", "-lm", (char *) NULL);
```
Edit: I almost forgot when usingexecl()the endingNULLargument must be cast tochar *
|
I am trying to select bits [0:2] and bits [6:8] of the bit-string 1010000000001. Bits [0:2] are 001 and bits [6:8] are 000. I tried to select these bits with:
```
int instr = 0x1401;
int src2 = (instr & 0x0006); //get bits [2:0]
int src1 = (instr & 0x01C0) >> 6; //get bits [6:8]
printf("%04x, %04x",src2, src1);
```
However I am getting that src1 and src2 are both 0000. Can someone please help me understand what I am doing incorrectly so I can select bits [0:2] and [6:8]?
|
Look at this code:
```
#include <stdio.h>
int main (void) {
unsigned instr = 0x1401;
unsigned src2 = instr & 0x0007; // 7 in hex == 0000 0000 0111 in binary
unsigned src1 = (instr & 0x01C) >> 6; // 1C in hex == 0001 1100 0000 in binary
printf("%04x, %04x", src2, src1);
}
```
It masks out the desired bits ininstrand shifts them by the correct offset. Also, when doing bit manipulation, unsigned types are preferred.
|
I have a struct of words:
```
typedef struct {
char *word;
unsigned long occurrences;
} Word;
```
and I want to malloc an array of these but I don't know how large the size will be. Is there a way to malloc an array of structs without knowing the size of the array beforehand?
Thanks.
|
You can allocate memory withmalloc(), and then change size withrealloc()
```
typedef struct {
char *word;
unsigned long occurrences;
} Word;
int main()
{
Word *arr = malloc(sizeof(Word) * n);
// do smth
// need more
arr = realloc(arr, sizeof(Word) * more);
return 0;
}
```
|
```
execl("/usr/bin/cc","cc","myprog.c",NULL)
```
I use the this line for compiler to myprog.c in myMainProg. But myprog.c have #include "math.h" . So I have to add -lm. How can I do that?
|
Command (from shell) to link your program should be:
```
cc myprog.c -o myprog -lm
```
So if you want to useexeclto compile it from another program you should use:
```
execl("/usr/bin/cc","cc","myprog.c", "-o", "myprog", "-lm", (char *) NULL);
```
Edit: I almost forgot when usingexecl()the endingNULLargument must be cast tochar *
|
I am trying to do an electronic notice board i.e E-NOTICE BOARD using lpc2148 and gsm module. Here basically, I'm trying to send an sms from a mobile phone through GSM and I want it to be displayed on the LCD screen.
I'm using SIM900A GSM module. I'm able to get the code everywhere for sending a message to the phone from GSM, but receiving code is hardly available anywhere.
It's really important and it would be helpful if anyone can provide the answer.
|
http://www.smssolutions.net/tutorials/gsm/receivesmsat/tells you how to use AT commands to receive sms. The ring indicator will probably be set low when an sms is received.
|
```
int main()
{
char* str1 = "Tom's cat";
char* str2 = "Tom\'s cat";
}
```
The code can be compiled with VS 2015.
I just wonder:
Are both of the two ways compliant to the C and/or the C++ standard?
|
From theC++11 ISO Standard
§ 2.14.5 String Literals[lex.string]...15Escape sequences and universal-character-names in non-raw string literals have the same meaning as in character literals (2.14.3), except that the single quote ’ is representable either by itself or by the escape
sequence \’
|
Here is my code:
```
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main()
{
FILE *fp;
char s[50];
fp = fopen("line.txt" , "r");
if( fgets (s, 50, fp)!=NULL )
{
puts(s);
}
fclose(fp);
return 0;
}
```
I know how to display a string in all uppercase and lowercase letters using the printf function. But I don't know how to do it using the fgets function. I am reading a string in from a file too, so thats the tricky thing for me.
|
```
if( fgets (s, 50, fp)!=NULL )
{
for( size_t ii = 0; s[ii]; ii++ )
{
s[ii] = toupper((unsigned char)s[ii]);
}
puts(s);
}
```
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed7 years ago.Improve this question
I'm trying to use thefnmatchfunction fromfnmatch.h
printf("match: %i") ,fnmatch("hello", "hello world", 0);
The above prints a large negative number. How should the call look like?
|
You accidentally used C's comma operator. I think you want to pass the return value offnmatchtoprintf, so you should change that line to:
```
printf("match: %i", fnmatch("hello", "hello world", 0));
```
|
When using thetee()system call to move data from one pipe to another, it returns 0 if the writer on the input pipe closes, but how can one discern whether the reader on the output pipe has closed?
|
For future generations, it looks like the answer is thattee()will return -1 signalling an error, witherrnoset to EPIPE, when the reader of the pipe has closed it, even though this isn't documented in the man pages. Correspondingly, a SIGPIPE will be generated, so be sure to properly handle that if you value your program continuing to execute.
|
When I usedrand()withsrand()to generate random number in [0,1], it gave me numbers like: 0.70324, 0.70328, 0.70321...
They were difference only in the last one or two digits, while I was intended to get random float numbers like 0.1,0.7,0.3....
How could I get random float number like that instead of making difference in the last digit?
Here's my code:
```
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main(){
int i;
float randomNum;
for ( i=0; i<10; i++){
srand((unsigned int)time(NULL));
randomNum = ((float)rand())/RAND_MAX;
printf("%f\n",randomNum);
}
return 0;
}
```
|
You should callsrand()only once, at the beginning of your program. Calling it before each call torand()only makes the results more predictable, since each time you call it with a number probably very similar to the previous one.
|
I know how to do stuff with Lua states and what not but what i don't understand is how you would distribute the final program with a seperate lua file because say you have a .exe and a lua file in the same directory how would I make it so that it is all one executable like how Löve 2d uses
```
copy /b
```
to append the lua file to the Löve 2d interpreter so it can be distributed.
could someone possibly explain how this works.
many thanks
Blazing
|
You could embed the lua code directly into your C++ source in a raw string literal like so:
```
const auto lua_code = R"lua(
...lua code here...
)lua";
```
|
I need to make a function , which will take as input a .txt file and then proceed
working on each character , while doing a bunch of operations.
This how function's declaration looks like.
```
int ProcessInput(FILE *in);
```
The thing is I don't want to take an input from keyboard , but from the .txt file as mentioned before.
I am working on Dev C++ .
Any ideas ?
|
```
#include <stdio.h>
int main(int argc, char** argv)
{
if (2 > argc)
{
printf("Please enter a file name on the command line\n");
return 0;
}
FILE* in = fopen(argv[1], "r");
if (!in)
{
printf("Unable to open the specified file\n");
return 0;
}
ProcessInput(in);
fclose(in);
return 0;
}
```
|
Simple code snippet:
```
#define FOO 7
int bar = -875;
bar <<= FOO;
```
This is being reported by UBSAN as UB.
My understanding is that-875 << 7is just-(875<<7)and there is no overflow.
So, is there a real problem here?
|
Your understanding is incorrect.
Firstly you usedbar <<= FOOsyntax. This explicitly shiftsbarandbaris negative. Left-shifting of negative values produces undefined behavior in C. There's no waybar <<= FOOcan be interpreted as-(875<<7).
Secondly, concerning-875 << 7in terms of operator priority: unary operators always have higher priority than binary ones, which means that-875 << 7is(-875) << 7and not-(875 << 7). And, again, left-shifting of negative values produces undefined behavior in C.
|
I am initializing a the Calendar structure blow, but I am having trouble initializing the priority_array.
```
typedef struct task {
const char *name;
const char *description;
struct task *next_task;
} Task;
typedef struct {
Task **priority_array;
int max_priority;
} Calendar;
```
I try to initialize it by doing so
```
cal->*priority_array = calloc(max_priority + 1, sizeof(Task));
```
However, I get
```
error: incompatible types when assigning to type 'Task' from type 'void *'
```
If I remove the '*', then I can compile correctly, but priority_task would just be a single pointer.
Why is it that I cannot dereference priority_array to set it to its second pointer
|
Try
```
cal->priority_array = calloc(max_priority + 1, sizeof(Task *));
```
That is assuming you allocated cal and set max_priority. The example code is a bit lacking.
|
I have 2 structs
```
typedef struct {
int i;
int p;
} item;
typedef struct {
item items[10];
} buffer;
void swap (item** p1, item** p2) {
item* temp = *p1;
*p1 = *p2;
*p2 = temp;
}
```
im trying to call
```
item *ps = &buffer.items[0];
item *p = &buffer.items[1];
swap(&ps, &p);
```
but it is not swapping them? What am I doing wrong? Thanks
would there be any change if the struct buffer was local in main or global?
Thanks
|
Your function only swaps thepointerspsandp, not the actual structures they point to. For that you need to copy the structures, something like
```
void swap (item* p1, item* p2) {
item temp = *p1;
*p1 = *p2;
*p2 = temp;
}
```
Call as
```
swap(&buffer.items[0], &buffer.items[1]);
```
|
In the following code:
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
float *a;
printf("%x\n",&a);
a = malloc(100*sizeof(float));
printf("%x\n",a);
*a=5;
printf("%x\n",*a);
}
```
I expect to see "5" in the final output, but all I see is zero. How can I modify those memory space?
|
I expect to see "5" in the final output, but all I see is zero. How
can I modify those memory space?
Use"%f"(or"%g"etc appropriate identifier) to print the value. (Or use explicit casting tounsigned intand printsizeof(double) * CHAR_BITbits)
Printing adoubleargument with"%u"printfformat specifier leads toundefined behavior. Related post:Understanding implicit conversions for printf
Can't modify values at addresses allocated by malloc()
You should be able to modify the contents on conforming implementation ifais notNULL. There is problem in presenting the data.
|
I have a question about null char. i have a bufferchar buffer_2[245]
```
memset(buffer_2, 0, 245);
strcpy(buffer_2, "Test");
strcat(buffer_2, "\0");
```
Do i need the third line? because isn't \0 autuomatically appended.
|
Do i need the third line? because isn't \0 autuomatically appended.
You don't need the third line.strcpyappends the'\0'.
Fromman strcpy:
Thestrcpy()function copies the string pointed to by src,includingthe terminating null byte ('\0'), to the buffer pointed to by dest. The strings may not overlap, and the destination string
dest must be large enough to receive the copy. Beware of buffer
overruns! (See BUGS.)
Also note that: Type of"Test"isconst char [5]with values'T','e','s','t'and'\0'.
|
I've installed
```
sudo apt-get install libbluetooth-dev
```
to have bluetooth package in my environment.
Hence, using the following command can successfully compile the bluetooth code using gcc.
```
gcc -o bt bt.c -lbluetooth
```
However, when I tried to use the cross-compiler to compile the source code
```
$CC -o bt2 bt.c -lbluetooth
```
I got the fatal error:
```
fatal error: bluetooth/bluetooth.h: No such file or directory
compilation terminated
```
Is there anything I've done wrong or I need to link this library to this cross-compiler ?
Thanks
|
I guess your cross compiler comes with a completetoolchainandSDK.
You must check that e.g.libBluetooth.soinstalled into your SDK under/usr/libor/usr/local/libfolders and the correct header, as the one installed fori386/x64platform, is present intoSDK.
In case of theheaderandlibexist you must change your#includeinto your code to match the path into yourSDK.
|
Suppose I have
```
int i=25;
double j=(double)i;
```
Is there a chance thatjwill have values24.9999999..upto_allowedor25.00000000..._upto_allowed_minus_one_and_then_1. I remember reading such stuff somehere but not able to recall properly.
In other words:
Is there a case when an integer loses its precision when casted to double?
|
For small numbers like25, you are good. For very large (absolute) values ofints on architecture whereintis 64 bit (having a value not representable in 53 bits) or more, you will loose the precision.
Double precision floating point numberhas 53 bits of precision of which Most significant bit is (implicitly) usually1.
On Platforms where floating point representation is not IEEE-754, answer may be a little different. For more details you can refer chapter5.2.4.2.2of C99/C11 specs
|
We have an array of structs like this one:
```
struct allocation
{
size_t alloc_size_;
char* alloc_memory_;
};
static struct allocation allocations[] =
{{1024, NULL},{2048, NULL},};
```
later on inmain()it's membersalloc_memory_are initialized usingnuma_alloc_onnode().
So the question: isalloc_memory_also static and where they are located (heap, stack) ? If they are not static then how to make them static?
|
Thealloc_memory_member of arrayallocationsare static, but the memory the pointed to are not necessarily static.
In your case, since you allocated them withnuma_alloc_onnodeinmain, this means they pointed to dynamic storage.
If you really want static storage too, you can define the memory before the structure:
```
static char buffer1[1024];
static char buffer2[2048];
static struct allocation allocations[] =
{ {1024, buffer1}, {2048, buffer2} };
```
|
Is using__MSDOS__enough with djgpp or should__DJGPP__be used instead?
By comparison, I know_WIN32isn’t defined by default on cygwin(based on the assumption djgpp and cygwin have the purpose to build an Unix layer to hide real OS details).
I no longer have a DOS machine to test it.
|
To list the predefined macros and their values, use
```
djgpp -E -x c -dM /dev/null
```
|
I've coded this up and I'm unsure how to get this to work any other way.
I would also appreciate example code of how to test its correctness.
Thanks for the help
```
dup2(STDOUT_FILENO, STDERR_FILENO);
dup2(fd, STDOUT_FILENO);
```
|
You were close, but you need to do the twodup2calls in the opposite order.
```
dup2(fd, STDOUT_FILENO);
dup2(STDOUT_FILENO, STDERR_FILENO);
close(fd);
```
Your code is equivalent to the POSIX shell syntax (which is available in all shells whose syntax is based on Bourne shell):
```
2>&1 >filename
```
which makesstderrgo to theoldstdoutwhile redirectingstdoutto the file.
|
```
int main(int argc, char **argv)
{
FILE *file = fopen("Offices.txt", "r");
char officeArray[10];
int yCoordinate[10];
int xCoordinate[10];
int i=0;
int x, y;
char office;
while(fscanf(file, "%c,%d,%d", &office, &x, &y) > 0)
{
officeArray[i] = office;
xCoordinate[i] = x;
yCoordinate[i] = y;
printf("%c,%d,%d \n", officeArray[i], xCoordinate[i], yCoordinate[i]);
i++;
}
fclose(file);
return 0;
}
```
I have a text file of node letters and coordinates:
```
A,1,1
B,1,5
C,3,7
D,5,5
E,5,1
```
My output is:
```
A,1,1
,1,1
B,1,5
,1,5
C,3,7
,3,7
D,5,5
,5,5
E,5,1
,5,1
```
I can't tell why I am getting double the integer reads from the text file.
|
I needed to include a newline command in my fscanf call.
```
while(fscanf(file, "%c,%d,%d\n", &office, &x, &y) > 0)
```
|
In the following code:
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
float *a;
printf("%x\n",&a);
a = malloc(100*sizeof(float));
printf("%x\n",a);
*a=5;
printf("%x\n",*a);
}
```
I expect to see "5" in the final output, but all I see is zero. How can I modify those memory space?
|
I expect to see "5" in the final output, but all I see is zero. How
can I modify those memory space?
Use"%f"(or"%g"etc appropriate identifier) to print the value. (Or use explicit casting tounsigned intand printsizeof(double) * CHAR_BITbits)
Printing adoubleargument with"%u"printfformat specifier leads toundefined behavior. Related post:Understanding implicit conversions for printf
Can't modify values at addresses allocated by malloc()
You should be able to modify the contents on conforming implementation ifais notNULL. There is problem in presenting the data.
|
I have a question about null char. i have a bufferchar buffer_2[245]
```
memset(buffer_2, 0, 245);
strcpy(buffer_2, "Test");
strcat(buffer_2, "\0");
```
Do i need the third line? because isn't \0 autuomatically appended.
|
Do i need the third line? because isn't \0 autuomatically appended.
You don't need the third line.strcpyappends the'\0'.
Fromman strcpy:
Thestrcpy()function copies the string pointed to by src,includingthe terminating null byte ('\0'), to the buffer pointed to by dest. The strings may not overlap, and the destination string
dest must be large enough to receive the copy. Beware of buffer
overruns! (See BUGS.)
Also note that: Type of"Test"isconst char [5]with values'T','e','s','t'and'\0'.
|
I've installed
```
sudo apt-get install libbluetooth-dev
```
to have bluetooth package in my environment.
Hence, using the following command can successfully compile the bluetooth code using gcc.
```
gcc -o bt bt.c -lbluetooth
```
However, when I tried to use the cross-compiler to compile the source code
```
$CC -o bt2 bt.c -lbluetooth
```
I got the fatal error:
```
fatal error: bluetooth/bluetooth.h: No such file or directory
compilation terminated
```
Is there anything I've done wrong or I need to link this library to this cross-compiler ?
Thanks
|
I guess your cross compiler comes with a completetoolchainandSDK.
You must check that e.g.libBluetooth.soinstalled into your SDK under/usr/libor/usr/local/libfolders and the correct header, as the one installed fori386/x64platform, is present intoSDK.
In case of theheaderandlibexist you must change your#includeinto your code to match the path into yourSDK.
|
Suppose I have
```
int i=25;
double j=(double)i;
```
Is there a chance thatjwill have values24.9999999..upto_allowedor25.00000000..._upto_allowed_minus_one_and_then_1. I remember reading such stuff somehere but not able to recall properly.
In other words:
Is there a case when an integer loses its precision when casted to double?
|
For small numbers like25, you are good. For very large (absolute) values ofints on architecture whereintis 64 bit (having a value not representable in 53 bits) or more, you will loose the precision.
Double precision floating point numberhas 53 bits of precision of which Most significant bit is (implicitly) usually1.
On Platforms where floating point representation is not IEEE-754, answer may be a little different. For more details you can refer chapter5.2.4.2.2of C99/C11 specs
|
What is the difference between compiling without the-goption and compiling with the-g0option in gcc? Is there any specific reason behind giving the-g0option in gcc?
I tried compiling and found the "no debugging symbols" message with both cases in GDB.
|
If you go to the GCCmanual, you will find that it says:
-glevel…Request debugging information and also use level to specify how much information. The default level is 2.Level 0 produces no debug information at all. Thus,-g0negates-g.
So, don't use-g0if you want debug information. If you do want debug information, remember to use the-goption both when creating the object files (-c) and when linking the program.
And compiling without-gat all and compiling with-g0are equivalent and there is no debugging information in the resulting binaries — as you found by experimentation.
|
I'm implementing AVL trees in C and I want to print all the elements of the tree in three columns in the console.
I have this:
```
void printInOrder(nodo * raiz) {
if (raiz != NULL) {
printInOrder(raiz->esq);
printf("%s\n", raiz->codigo);
printInOrder(raiz->dir);
}
}
```
Anyone knows how to print the output in three columns?
|
This is what I was searching for:
```
int printInOrder(nodo *root, int count){
if(root!=NULL){
count=printInOrder(root->left,count);
count++;
if(count%PRINT_COLS==0 && count!=0) printf("%s \n", root->code);
else printf("%s \t\t", root->code);
if(count%(2*10*PRINT_COLS)==0 && count!=0){getch();}
count=printInOrder(root->right, count);
}
return count;
```
}
|
I am trying to recompile an older project where a colleague has added few more adventurous comments (ok, these are Doxygen comments, I forgot)
For instance the triple///
```
uint32_t nx; ///< number of columns
```
It was developed with 4.2 and now with 4.8 the compiler generates the following error:
error: expected specifier-qualifier-list before ‘/’ token
Should I get rid of all///expressions and replace with//? It's a large project
|
//comments do not work with-std=c89or-ansioptions. Use-std=c99or-std=gnu99instead.
|
I try to compile my window application with gSOAP 2.8.30 but i found an error which is
wctomb_s undeclared identifier
So i just wandering if the latest gSOAP is not compatible with the VC6++ since this error come from stdsoap2.cpp. Before this i'm using gSOAP 2.8.6 is working fine.
|
VS6 C++ does not supportwctomb_s(the recommended safer version ofwctomb). Upgrade to a newer VS C++ release or update the code instdsoap2.cppfunctionsoap_string_inby replacing:
```
#ifdef WIN32
m = 0;
wctomb_s(&m, buf, sizeof(buf), (wchar_t)(c & 0x7FFFFFFF));
#else
m = wctomb(buf, (wchar_t)(c & 0x7FFFFFFF));
#endif
```
with:
```
m = wctomb(buf, (wchar_t)(c & 0x7FFFFFFF));
```
at both of the two locations wherewctomb_sis used.
|
Normal pointer usage as I have been reading in a book is the following:
```
int *pointer;
int number = 5;
pointer = &number;
```
Then *pointer has a value of 5.
But does this work the other way around? I mean:
```
int *pointer;
int number = 5;
*pointer = &number;
```
Here does pointer contain the value 5 and *pointer holds the address of number?
Thanks.
|
In
```
int *pointer;
int number = 5;
*pointer = &number;
```
you never assign a valid address topointer, so dereferencing that pointer (as is done by the expression*pointer) is not valid.
|
What is the difference between compiling without the-goption and compiling with the-g0option in gcc? Is there any specific reason behind giving the-g0option in gcc?
I tried compiling and found the "no debugging symbols" message with both cases in GDB.
|
If you go to the GCCmanual, you will find that it says:
-glevel…Request debugging information and also use level to specify how much information. The default level is 2.Level 0 produces no debug information at all. Thus,-g0negates-g.
So, don't use-g0if you want debug information. If you do want debug information, remember to use the-goption both when creating the object files (-c) and when linking the program.
And compiling without-gat all and compiling with-g0are equivalent and there is no debugging information in the resulting binaries — as you found by experimentation.
|
In the code below, the output values are not as defined in macro , is that because the values have to be available before pre processor stage?
```
#define INT_MAX 100
#include <iostream>
using namespace std;
int main()
{
int x = INT_MAX;
x++;
cout<<x<<INT_MAX;
}
```
Result is -2147483648
|
There is a macro namedINT_MAXdefined inlimits.h. I assume thatiostreamincludeslimits.hand overwrites your own definition ofINT_MAX.
This causes an integer overflow atx++becauseINT_MAXis the largest value that can be represented by an integer.
|
I am trying to run Valgrind in Ubuntu 14.04 with the following options:
```
valgrind --tool=massif --pages-as-heap=yes
```
But get the following error:
```
valgrind: Bad option: --page-as-heap=yes
```
This option is described in several places (and it is actually mentioned in valgrind's manualhttp://valgrind.org/docs/manual/ms-manual.html) to be used with massif.
How can I have this tool/option avaliable?
Thanks
|
Found the error. The correct command is:
```
valgrind --tool=massif --pages-as-heap=yes
```
Note the plural "pages".
|
Can someone explain me why freeingatwice in a row causes a crash, but freeingafirst, thenb, and thenaagain does not crash?
I know that a free will insert the heap chunk in a double linked free list. Freeing twice would insert the same chunk twice in the free list. But why is the crash happening?
```
int *a = malloc(8);
int *b = malloc(8);
free(a);
// free(a); // Would crash!
free(b);
free(a); // No crash.
```
|
Because in C lingo,undefined behavioris just that: undefined. Anything might happen.
Also seeman 3 free:
[…] iffree(ptr)has already been called before, undefined behavior occurs.
|
I'm very new to C, and I'm not understanding this behavior. Upon printing the length of this empty array I get 3 instead of 0.
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct entry entry;
struct entry{
char arr[16];
};
int main(){
entry a;
printf("%d\n",strlen(a.arr));
return 0;
}
```
What am I not understanding here?
|
The statemententry a;doesnotinitialize the struct, so its value is likely garbage. Therefore, there's no guarantee thatstrlenon any of its members will return anything sensible. In fact, it might even crash the program, orworse.
|
How can I insert characters in a file using C instead of overwriting? I also want to write in start of file and end of a file. I triedthis methodbut it didn't work out (I can re-position but I cannot insert. The text is overwritten)
I've tried this, but it didn't work:
```
fword = fopen("wrote.txt", "rb+");
fseek(fword, 0, SEEK_SET);
fscanf(fword, "%c", &l);
```
|
To add text at the end, you can open the file with"a"mode (check thefopenmanual). It will write your text to end.
To add text in other positions, you have to read everything after that to memory, write what you want and then write the rest.
|
Seeing yet anotherquestionthe answer to which would have been obvious had the questioner compiled with-Wallgot me thinking.
Is there a 'C standard' based reason why-Wallcannot be enabled by default by the compiler?
As far as I know none of the major compilers do this (and certainly historically none of them did it), and I'd like to know whether this is adherence to the standard, or some other reason (inertia, back compatibility or whatever). Speculating as to the other reason is probably off-topic (opinion based), but I think asking whether a standard requires this behaviour is on-topic (factual).
|
Quoted from N1570 Annex I:
1 An implementation may generate warnings in many situations, none of
which are specified as part of this International Standard.
This implies that warnings are non-compulsory to compilers, so I don't think there would be any "C standard" based reasons.
|
This question already has answers here:Enabling VLAs (variable length arrays) in MS Visual C++?(5 answers)Closed7 years ago.
Under GCC 4.8.1
```
static int len = 10;
int main() {
int a[len];
return 0;
}
```
can compile success.
But compile will fail if changed like this:
```
static int len = 10;
int main() {
static int a[len];
return 0;
}
```
But in my Visual Studio, the former also can not compile success. How can I fix this problem?
And is there a way to change latter one to make it compile success?
|
The MSVC compiler only supports C90, it does not support C99, and variable length arrays are a feature of C99.
Seethis; it's not possible even with MSVC++.
|
How can I insert characters in a file using C instead of overwriting? I also want to write in start of file and end of a file. I triedthis methodbut it didn't work out (I can re-position but I cannot insert. The text is overwritten)
I've tried this, but it didn't work:
```
fword = fopen("wrote.txt", "rb+");
fseek(fword, 0, SEEK_SET);
fscanf(fword, "%c", &l);
```
|
To add text at the end, you can open the file with"a"mode (check thefopenmanual). It will write your text to end.
To add text in other positions, you have to read everything after that to memory, write what you want and then write the rest.
|
Seeing yet anotherquestionthe answer to which would have been obvious had the questioner compiled with-Wallgot me thinking.
Is there a 'C standard' based reason why-Wallcannot be enabled by default by the compiler?
As far as I know none of the major compilers do this (and certainly historically none of them did it), and I'd like to know whether this is adherence to the standard, or some other reason (inertia, back compatibility or whatever). Speculating as to the other reason is probably off-topic (opinion based), but I think asking whether a standard requires this behaviour is on-topic (factual).
|
Quoted from N1570 Annex I:
1 An implementation may generate warnings in many situations, none of
which are specified as part of this International Standard.
This implies that warnings are non-compulsory to compilers, so I don't think there would be any "C standard" based reasons.
|
This question already has answers here:Enabling VLAs (variable length arrays) in MS Visual C++?(5 answers)Closed7 years ago.
Under GCC 4.8.1
```
static int len = 10;
int main() {
int a[len];
return 0;
}
```
can compile success.
But compile will fail if changed like this:
```
static int len = 10;
int main() {
static int a[len];
return 0;
}
```
But in my Visual Studio, the former also can not compile success. How can I fix this problem?
And is there a way to change latter one to make it compile success?
|
The MSVC compiler only supports C90, it does not support C99, and variable length arrays are a feature of C99.
Seethis; it's not possible even with MSVC++.
|
Is there a way to read a HH:MM format from a file usingfscanf(), and treat it like an int? The file has this format :
```
3 14:50 20.10
```
Is it possible to do something likefscanf(fp, "%d ... %f, &a, &b, &c);andbwill have 1450?
|
I'm afraid you can't do this in a line. However, you can:
```
fscanf(fp, "%d %d:%d %f", &a, &b1, &b2, &c);
b = b1 * 100 + ((b1 > 0) * 2 - 1) * b2; // in case b1, b2 are the different sign.
```
|
This question already has answers here:What is special about numbers starting with zero?(4 answers)Closed4 years ago.
Can you explain it? Why it given 56 value as output?
```
#include <stdio.h>
#include <conio.h>
void main()
{
int x = 070;
printf("%d", x);
getch();
}
```
|
Any integer literal (integer constant) starting with0is anoctal representation.
QuotingC11, chapter §6.4.4.1,Integer constants
octal-constant:0octal-constantoctal-digit
and
octal-digit: one of0 1 2 3 4 5 6 7
and, as per chapter §7.21.6.1, for%dformat specifier withprintf(), (emphasis mine)
d,iTheintargument is converted to signeddecimal[...]
Thereby,octal 70 == decimal 56.
|
When should I use locks using freertos on something like cortex-m3? It seems to be clear using multicore systems but what about single core?
For example I have two tasks. In first I increment variable namedcounter. Second task saves current value of that variable when some event occurs. Should I use locks here? May first task corrupt value which second task is saving?
|
Yes, you should use locks to protect access to the shared resource.
You can't be sure that the sequence generated by the compiler to read the shared variable is atomic, so it might be unsafe.
If you want to be a bit more hard-core, possibly gaining performance, you can use various ways to actually ensure that the variablecanbe accessed atomically. See comment.
|
I runbayesoptwith python bindings. So I have abayesopt.sothat I import from python (a C-extension).
When I run it, it core dumps. I want to load this core dump in gdb to see what the issue is. How can I do this? Or get information on it?
I tried to load gdb on it, but of course it asks for a binary which I don't have since it's a.so.
|
You want to run gdb on python, ie:gdb -ex r --args python myscript.py. There's some helpful tips in the python wiki:https://wiki.python.org/moin/DebuggingWithGdb
|
I have wrote a program inKeilforstm32F4discoverymicrocontrollerand i want to run this C program inMatlab simulink. For this I am trying to use legacy_code function in Matlab. But there are many parameters which I cannot add like
SFunctionName,OutputFcnSpec,StartFcnSpec,HeaderFiles,SourceFiles,HostLibFiles,TargetLibFiles,IncPaths,SrcPaths,LibPaths.
It would be really helpful if anyone guide me how to find these parameters from keil project/program
|
Most of those are just obvious as its name suggests, SFunctionName is the function name you want to run by the simulator, HeaderFiles is the header that contains the declaration of the functions etc. There is an example in the docs for providing specifications for legacy functions:
http://mathworks.com/help/rtw/examples/lookup-tables.html
|
How can I scroll my Tree View control to the top?
For example we have some tree with a lot of elements:
```
Root element
|-- item 1
|-- item 2
|-- .....
|-- item 1567
```
Tree View control can display only 5 node at the same time. As result, when I press Expand button, it expand all items and shows me only the last 5 nodes.
I want so that after expanding it returns view to the first 5 nodes.
I tried to use this macros to return caret back to the root, but they take no effect:
```
TreeView_Select(hTreeView, hRoot, TVGN_CARET);
TreeView_SelectSetFirstVisible(hTreeView, hRoot);
```
|
I assume you want to use Windows API (and the macros). You can ensure an item is visible with TreeView_EnsureVisible. If you do not have the root item you can get it with TreeView_GetRoot.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.