question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
This does work
```
LLIST *mylist[10] = {NULL};
```
But would if I wanted to do this I get errors:
```
int x=10;
LLIST *mylist[x] = {NULL};
```
xcan be any value I'm setting it to 10 for the time being.xis going to be used as a counter.
|
Support for variable length arrays (which your second example uses) came in the C99 standard, which your compiler may not support.
For gcc, you should pass the-std=c99option when compiling.
|
Can I somehow tell GStreamer to look for plugins in a specified directory?
|
Use theGST_PLUGIN_PATHenvironment variable to point at the directory you want, or programatically just call:
```
GstRegistry *registry;
registry = gst_registry_get();
gst_registry_scan_path(registry, directory);
```
|
I'm new to using C programming I was wondering if there is a function call that can be used to quickly determine the amount of rows in a text file.
|
```
#include <stdio.h>
#include <stdint.h>
uint32_t CountRows(FILE* fp, uint8_t line_delimiter){
uint32_t num_rows = 0;
uint16_t chr = fgetc(fp);
while(chr != EOF){
if(chr == line_delimiter){
num_rows++;
}
chr = fgetc(fp);
}
return num_rows;
}
```
|
hi i am interested in those chars which are representable by ascii table. for that reason i am doing the following:
```
int t(char c) { return (int) c; }
...
if(!(t(d)>255)) { dostuff(); }
```
so i am interested in only ascii table representable chars, which i assume after conversion to int should be l... |
Usually(not always) a char is 8-bits so all chars would typically have a value of less than 256. So your test would always succeed.
Also,ASCIIonly goes up to 127, not 255. The characters after that are not standard ASCII, and can vary depending on code pages.
If you are dealing with international characters you shou... |
```
FILE *fd;
if (fd=fopen(fileName,"r") == NULL)
{
printf("File failed to open");
exit(1);
}
```
This is a code snippet. When I compile it with gcc, i get the following warning:-
```
warning: assignment makes pointer from integer without a cast
```
When I putfd=fopen(argv[2],"r")within brackets, the pro... |
Due to operator precedence rules the condition is interpreted asfd=(fopen(fileName,"r") == NULL). The result of==is integer,fdis a pointer, thus the error message.
Consider the "extended" version of your code:
```
FILE *fd;
int ok;
fd = fopen(fileName, "r");
ok = fd == NULL;
// ...
```
Would you expect the last lin... |
I want to do some sound synthesis on Mac OS X (and ideally other Unix-like OS) using ANSI C.
This is for learning purposes rather than "I need a solution, any solution, quick!"
Say I have an 8-bit buffer in my C program that I update 22050 times a second. How can I get my speakers to output that as a waveform?
|
SDL can play sound buffers. But PortAudio may work better PA will call your C callback when it needs more data, and then you can hand it the next buffer. It's fairly easy actually.
|
I want to do something in C99 one way, otherwise to perform it another way. What is the#defineto check for?
```
#ifdef C99
...
#else
...
#endif
```
|
There is not an specific#definevalue. Just check__STDC_VERSION__and define it yourself! ;-)
```
#if __STDC_VERSION__ >= 199901L
/* C99 code */
#define C99
#else
/* Not C99 code */
#endif
#ifdef C99
/*My code in C99 format*/
#else
/*My code in C99 format*/
#endif
```
EDIT:A more general snippet,from here. I've just... |
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
One of the most widely used is libxml2. You can take a lookhere.
|
What are the various mechanisms using which we can detect if a process execution is leading to memory fragmentation?
Are there any tools available for the same? Suggestion for tools which work with 'C' code and can run on Windows, Linux and VxWorks will be helpful.
|
Just as a suggestion, you may want to try Valgrind. I'm not certain it's what you're looking for, but it may come in handy.
http://valgrind.org/
|
I've got a menu in curses that I'd like to put multi-line descriptions onto.
My code puts the description fields on but they don't display if they don't fit on the line.
Curses is happy enough printing multi-line text as strings (not as menu descriptions)
Any ideas how to get multi-line descriptions working ?
|
I've given up on this and render my own scrollable list of items instead.
|
I have a function which accepts a pointer to a struct and sets a member of that struct to a specific value. However, after that assignment code is executed, and my program exits without showing any errors.
```
void swn_addClassToInstance(struct instanceR *instance)
{
instance->classCount = 0;
//nothing below here w... |
Most probable cause is thatinstanceis NULL or not initialized, thus causing an access violation. It would be help if you show the code where you allocate and initialize the memory for the structinstancepoints to.
|
I'm now really diving into my OS project, called ForestOS, but now I'm needing to dive more into some simple and basic things of C. As now I'm having many problems with the correct variable to use and functions.
I want resources that only talk about variables, functions and how to develop without headers(stdio.h,math... |
Best starting place is probably the bookThe C Programming Language.
The book was central to the development and popularization of the C programming language and is still widely read and used today.
|
Hello I have anunsigned char *that looks (after printf) like this (it's a SHA-1 hash):
```
n\374\363\327=\3103\231\361P'o]Db\251\360\316\203
```
I need to convert thisunsigned char *to anunsigned int, what do you think it would be the best way to do it ? I have some ideas, but I'm not a C expert so wanted to see som... |
Why would you need a conversion? It's a 160 bit long digest. Digests are used only in two ways:
You print a digest with something like
```
for (i = 0; i < 20; ++i) {
printf("%2x", digest[i]);
}
```
and compare against another digest with something like
```
for (i = 0, equals = 1; i < 20; ++i) {
if (a[i] !=... |
I have a C++ application that callsSQLite's (SQLite is in C)sqlite3_exec()which in turn can call my callback function implemented in C++. SQLite is compiled into a static library.
If an exception escapes my callback will it propagate safely through the C code of SQLite to the C++ code calling sqlite3_exec()?
|
My guess is that this is compiler dependent. However, throwing an exception in the callback would be a very bad idea. Either it will flat-out not work, or the C code in the SQLite library will be unable to handle it. Consider if this is some code in SQLite:
```
{
char * p = malloc( 1000 );
...
call_the_callback... |
What is the difference between CreateThread and beginthread APIs in Windows? Which one is preferrable for thread creation?
|
_beginthread()and_beginthreadex()was required by earlier versions of the Microsoft CRT to initialize thread-local state. Thestrtok()function would be an example. That's been fixed, that state now gets dynamically initialized, at least since VS2005. UsingCreateThread()no longer causes problems.
|
The C language convention counts array indices from 0. Why do inode numbers start from 1 and not 0?
If inode 0 is reserved is for some special use, then what is the significance of inode 0?
|
0 is used as asentinel valueto indicate null or no inode. similar to how pointers can be NULL in C. without a sentinel, you'd need an extra bit to test if an inode in a struct was set or not.
more info here:
All block and inode addresses start at
1. The first block on the disk is block 1. 0 is used to indicate no
... |
Does this...
```
char* myString = "hello";
```
... have the same effect as this?
```
char actualString[] = "hello";
char* myString = actualString;
```
|
No.
```
char str1[] = "Hello world!"; //char-array on the stack; string can be changed
char* str2 = "Hello world!"; //char-array in the data-segment; it's READ-ONLY
```
The first example creates an array of size13*sizeof(char)on the stack and copies the string"Hello world!"into it.The second example creates achar... |
I have a command line C program for which I use the calloc() function to assign some memory for a struct which also has a struct in it with some memory assigned.
If I use the free() function to release the memory from the parent struct, will it also release the memory from the child struct?
Or should I release the m... |
Its a simple rule, for every memory allocation you do, you have to explicitly release the memory yourself. So, you need to release the child memory yourself.
|
considering a pointer to a struct
```
struct a_struct
{
int A;
};
```
Is it ok to do :
```
struct a_struct *ptr;
//...
if( ptr != NULL && ptr->A == 1)
{
//work with ptr struct
}
```
or should you Test if the pointer is valid before testing for on of its field.
```
if(ptr != NULL)
{
if(... |
Yes, that's ok.
The&&operator short-circuits in C, soptr->A == 1will only be evaluated ifptris non-null.
|
I have an array that contains pointers. How can I swap two pointers - say array[1] and array[4] - correctly?
|
You need a temporary variable:
```
void*temp = array[4];
array[4]=array[1];
array[1] = temp;
```
Edit Fixed first line.
|
I have below lines in my code written in C on unix platform. Please let me know why I am getting core dumped in closedir() function. I could successfully opened the directory specified by path.
```
if (opendir(MyDir) != NULL )
{
closedir((DIR *) MyDir);
exit 0;
}
```
|
closedir()takes aDIR *, not achar *. Wishingclosedir()did that is not going to work. Try:
```
#include <sys/types.h>
#include <dirent.h>
DIR *dir;
if ((dir = opendir(MyDir)) != NULL)
closedir(dir);
```
Also, it seems you added a cast in(DIR *) MyDirto suppress a compiler warning. When a compiler gives you a ... |
Why do I get segmentation fault in this function:
```
#include <stdio.h>
#include <stdlib.h>
#include "math.h"
vec_t mtrx_multiple (sparse_mat_t a, vec_t c) {
vec_t result;
int i;
result.n = a.n;
printf("result.n: %d\n", result.n);
result.vec = malloc(a.n * sizeof *result.vec);
for(i=0; i... |
I suspect the problem is witha.a[a.ja[i]], you should try verifying the valuesa.ja[i]before using them to indexa.a.
It would be useful to know howais initialised, and also on which line the segfault occurs.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do... |
"The C Programming Language"
|
I've got a menu in curses that I'd like to put multi-line descriptions onto.
My code puts the description fields on but they don't display if they don't fit on the line.
Curses is happy enough printing multi-line text as strings (not as menu descriptions)
Any ideas how to get multi-line descriptions working ?
|
I've given up on this and render my own scrollable list of items instead.
|
I have a function which accepts a pointer to a struct and sets a member of that struct to a specific value. However, after that assignment code is executed, and my program exits without showing any errors.
```
void swn_addClassToInstance(struct instanceR *instance)
{
instance->classCount = 0;
//nothing below here w... |
Most probable cause is thatinstanceis NULL or not initialized, thus causing an access violation. It would be help if you show the code where you allocate and initialize the memory for the structinstancepoints to.
|
I'm now really diving into my OS project, called ForestOS, but now I'm needing to dive more into some simple and basic things of C. As now I'm having many problems with the correct variable to use and functions.
I want resources that only talk about variables, functions and how to develop without headers(stdio.h,math... |
Best starting place is probably the bookThe C Programming Language.
The book was central to the development and popularization of the C programming language and is still widely read and used today.
|
Hello I have anunsigned char *that looks (after printf) like this (it's a SHA-1 hash):
```
n\374\363\327=\3103\231\361P'o]Db\251\360\316\203
```
I need to convert thisunsigned char *to anunsigned int, what do you think it would be the best way to do it ? I have some ideas, but I'm not a C expert so wanted to see som... |
Why would you need a conversion? It's a 160 bit long digest. Digests are used only in two ways:
You print a digest with something like
```
for (i = 0; i < 20; ++i) {
printf("%2x", digest[i]);
}
```
and compare against another digest with something like
```
for (i = 0, equals = 1; i < 20; ++i) {
if (a[i] !=... |
I have a C++ application that callsSQLite's (SQLite is in C)sqlite3_exec()which in turn can call my callback function implemented in C++. SQLite is compiled into a static library.
If an exception escapes my callback will it propagate safely through the C code of SQLite to the C++ code calling sqlite3_exec()?
|
My guess is that this is compiler dependent. However, throwing an exception in the callback would be a very bad idea. Either it will flat-out not work, or the C code in the SQLite library will be unable to handle it. Consider if this is some code in SQLite:
```
{
char * p = malloc( 1000 );
...
call_the_callback... |
What is the difference between CreateThread and beginthread APIs in Windows? Which one is preferrable for thread creation?
|
_beginthread()and_beginthreadex()was required by earlier versions of the Microsoft CRT to initialize thread-local state. Thestrtok()function would be an example. That's been fixed, that state now gets dynamically initialized, at least since VS2005. UsingCreateThread()no longer causes problems.
|
The C language convention counts array indices from 0. Why do inode numbers start from 1 and not 0?
If inode 0 is reserved is for some special use, then what is the significance of inode 0?
|
0 is used as asentinel valueto indicate null or no inode. similar to how pointers can be NULL in C. without a sentinel, you'd need an extra bit to test if an inode in a struct was set or not.
more info here:
All block and inode addresses start at
1. The first block on the disk is block 1. 0 is used to indicate no
... |
Does this...
```
char* myString = "hello";
```
... have the same effect as this?
```
char actualString[] = "hello";
char* myString = actualString;
```
|
No.
```
char str1[] = "Hello world!"; //char-array on the stack; string can be changed
char* str2 = "Hello world!"; //char-array in the data-segment; it's READ-ONLY
```
The first example creates an array of size13*sizeof(char)on the stack and copies the string"Hello world!"into it.The second example creates achar... |
I have a command line C program for which I use the calloc() function to assign some memory for a struct which also has a struct in it with some memory assigned.
If I use the free() function to release the memory from the parent struct, will it also release the memory from the child struct?
Or should I release the m... |
Its a simple rule, for every memory allocation you do, you have to explicitly release the memory yourself. So, you need to release the child memory yourself.
|
considering a pointer to a struct
```
struct a_struct
{
int A;
};
```
Is it ok to do :
```
struct a_struct *ptr;
//...
if( ptr != NULL && ptr->A == 1)
{
//work with ptr struct
}
```
or should you Test if the pointer is valid before testing for on of its field.
```
if(ptr != NULL)
{
if(... |
Yes, that's ok.
The&&operator short-circuits in C, soptr->A == 1will only be evaluated ifptris non-null.
|
I have an array that contains pointers. How can I swap two pointers - say array[1] and array[4] - correctly?
|
You need a temporary variable:
```
void*temp = array[4];
array[4]=array[1];
array[1] = temp;
```
Edit Fixed first line.
|
I have below lines in my code written in C on unix platform. Please let me know why I am getting core dumped in closedir() function. I could successfully opened the directory specified by path.
```
if (opendir(MyDir) != NULL )
{
closedir((DIR *) MyDir);
exit 0;
}
```
|
closedir()takes aDIR *, not achar *. Wishingclosedir()did that is not going to work. Try:
```
#include <sys/types.h>
#include <dirent.h>
DIR *dir;
if ((dir = opendir(MyDir)) != NULL)
closedir(dir);
```
Also, it seems you added a cast in(DIR *) MyDirto suppress a compiler warning. When a compiler gives you a ... |
I want to send a file in C++ over network (for a chat program)
what should I do?
|
Take a look athttp://www.boost.org/doc/libs/1_38_0/doc/html/boost_asio/examples.html. The Iostreams example should give you the first good step. Asio is a portable network library of the boost project. Boost is available for most platforms available today.
You can stream in the file and stream out it into the TCP str... |
How to split a string into tokens by'&'in C?
|
strtok / strtok_r
```
char *token;
char *state;
for (token = strtok_r(input, "&", &state);
token != NULL;
token = strtok_r(NULL, "&", &state))
{
...
}
```
|
I have a bug where acharpointer is turning outNULL. I've been all over gdb with the program, watching read/write at the memory address, and stepping through the instructions, but so far the bug stumps me. I've ran valgrind and the only thing coming up is the read at the crash (strcmp). What else can I do to track this... |
You can try awatchpoint. You watch an expression and when the value of that expression changes, gdb will stop execution.
You can watch a variable:
```
watch charptr
```
This will break every time charptr changes. If you just wanted to know when it changes from non-NULL to NULL (or vice versa), you can use:
```
w... |
In C, arrays are passed to functions as pointers. Structures can be passed to functions either by value or by address (pointer). Is there any specific reason why we can not pass array by value but we can pass structre by value ?
|
In C,everythingis passed by value. There is another rule that says that in most contexts, the name of an array is equivalent to a pointer to its first element. Passing an array to a function is such a context.
So, the special case is not that arrays are passed by reference, the special case isthe rule about arrays ... |
I have two tasks for an assignment, one return the number of bits in type int on any machine. I thought I would write my function like so:
```
int CountIntBitsF() {
int x = sizeof(int) / 8;
return x;
}
```
Does that look right?
The second part is to return the number of any bits of any data type with a mac... |
The fundamental unit of storage is a char. It is not always 8 bits wide. CHAR_BIT is defined in limits.h and has the number of bits in a char.
|
Any good alternative written in C to replace Boost.Program_options? Given it's able to parse:
Short options like -hLong options like --help --input-fileParse repeated keys/optionsAccepts key-value pairs: --mysql=/usr/libParsing environmental variables and XML/INI files is optional.
|
If you are okay with the GPL license, you wantGNU getopt.
|
What's the most elegant way to return astd::listobject from a shared lib function (implemented by C++ code) to a C consumer? I know forstd::vector, we can return the address of the 1st element of the vector and have the consumer treat it as an array, but std::list is implemented as a linked lis.
|
Copy thestd::listto astd::vectorand return the address of the first element, as you already mentioned.
(Of course, this may mean that you don't want to be using astd::listin the first place.)
(This solution assumes that the object being accessed isownedby the C++ library -- If this isn't the case, you may need to co... |
Hello I have been usingLibTomCryptto use SHA1 encryption ( for data integrity checking ) on mobile devices (iPhone OS and Android for the moment ). I was wondering if anyone is using anything else, things to consider are Portability ( C preferred but C++ is also an option ), and libraries size ( small == better for my... |
You might write a wrapper class that callsCommonCryptoroutines if you're on an iPhone, to reduce your library size requirements and enforce portability. Your wrapper, for example, would call other routines if compiled on another platform. The nice thing about CommonCrypto is that it is pre-built by Apple. Calls to it ... |
On Windows,
```
char c;
int i;
scanf("%d", &i);
scanf("%c", &c);
```
The computer skips to retrieve character from console because '\n' is remaining on buffer.
However, I found out that the code below works well.
```
char str[10];
int i;
scanf("%d", &i);
scanf("%s", str);
```
Just like the case above, '\n' is re... |
From the gcc man page (I don't have Windows handy):
%c: matches a fixed number of characters, always. The maximum field width says how
many characters to read; if you don't specify the maximum, the default is 1. It also does not skip over initial whitespace characters.
%s: matches a string of non-whitespace charac... |
How do I get the list of all environment variables in C and/or C++?
I know thatgetenvcan be used to read an environment variable, but how do I list them all?
|
The environment variables are made available tomain()as theenvpargument - a null terminated array of strings:
```
int main(int argc, char **argv, char **envp)
{
for (char **env = envp; *env != 0; env++)
{
char *thisEnv = *env;
printf("%s\n", thisEnv);
}
return 0;
}
```
|
Any good alternative written in C to replace Boost.Program_options? Given it's able to parse:
Short options like -hLong options like --help --input-fileParse repeated keys/optionsAccepts key-value pairs: --mysql=/usr/libParsing environmental variables and XML/INI files is optional.
|
If you are okay with the GPL license, you wantGNU getopt.
|
What's the most elegant way to return astd::listobject from a shared lib function (implemented by C++ code) to a C consumer? I know forstd::vector, we can return the address of the 1st element of the vector and have the consumer treat it as an array, but std::list is implemented as a linked lis.
|
Copy thestd::listto astd::vectorand return the address of the first element, as you already mentioned.
(Of course, this may mean that you don't want to be using astd::listin the first place.)
(This solution assumes that the object being accessed isownedby the C++ library -- If this isn't the case, you may need to co... |
Hello I have been usingLibTomCryptto use SHA1 encryption ( for data integrity checking ) on mobile devices (iPhone OS and Android for the moment ). I was wondering if anyone is using anything else, things to consider are Portability ( C preferred but C++ is also an option ), and libraries size ( small == better for my... |
You might write a wrapper class that callsCommonCryptoroutines if you're on an iPhone, to reduce your library size requirements and enforce portability. Your wrapper, for example, would call other routines if compiled on another platform. The nice thing about CommonCrypto is that it is pre-built by Apple. Calls to it ... |
On Windows,
```
char c;
int i;
scanf("%d", &i);
scanf("%c", &c);
```
The computer skips to retrieve character from console because '\n' is remaining on buffer.
However, I found out that the code below works well.
```
char str[10];
int i;
scanf("%d", &i);
scanf("%s", str);
```
Just like the case above, '\n' is re... |
From the gcc man page (I don't have Windows handy):
%c: matches a fixed number of characters, always. The maximum field width says how
many characters to read; if you don't specify the maximum, the default is 1. It also does not skip over initial whitespace characters.
%s: matches a string of non-whitespace charac... |
How do I get the list of all environment variables in C and/or C++?
I know thatgetenvcan be used to read an environment variable, but how do I list them all?
|
The environment variables are made available tomain()as theenvpargument - a null terminated array of strings:
```
int main(int argc, char **argv, char **envp)
{
for (char **env = envp; *env != 0; env++)
{
char *thisEnv = *env;
printf("%s\n", thisEnv);
}
return 0;
}
```
|
I usepthread_create(&thread1, &attrs, //... , //...);and need if some condition occured need to kill this thread how to kill this ?
|
First store the thread id
```
pthread_create(&thr, ...)
```
then later call
```
pthread_cancel(thr)
```
However, this not a recommended programming practice! It's better to use an inter-thread communication mechanism like semaphores or messages to communicate to the thread that it should stop execution.
Note that... |
How would I go about taking a number like123456and having it print as1 2 3 4 5 6?
|
The simplest way of doing this (though not the fastest) would probably be to firstsprintfthe number to a string buffer, and then loop through the bufferprintf-ing one character and one space at a time.
There's no built-in way of doing this within the standardprintfformatting.
|
Really off the wall question here, but is there a way to compile a string of C code in GCC without any medium to hold that string (eg. a source file)?
Something along the lines of:
```
$ gcc "#include <stdio.h> int main( void ){ printf('hello world'); return 0;}" -o test
```
Feels really dirty, but it would be real... |
If you use-as the input file in the command line, gcc reads from standard input. Since there is no file name extension gcc could use to find out the language that should be compiled, it has to be specified with the-xflag:
```
$ gcc -x c -o tst - <<EOF
> #include <stdio.h>
> int main(void) {
> printf("Hello world\n"... |
The title says everything. I am talking about C/C++ specifically, because both consider this as "implementation issue". I think, defining a standard interface can ease building a module system on top of it, and many other good things.What could C/C++ "lose" if they defined a standard ABI?
|
The freedom to implement things in the most natural way on each processor.
I imagine that c in particular has conforming implementations on more different architectures than any other language. Abiding by a ABI optimized for the currently common, high-end, general-purpose CPUs would require unnatural contortions on s... |
I know in C++, you're able to peek at the next character by using:in.peek();.
How would I go about this when trying to "peek" at the next character of a file in C?
|
fgetc+ungetc. Maybe something like this:
```
int fpeek(FILE *stream)
{
int c;
c = fgetc(stream);
ungetc(c, stream);
return c;
}
```
|
I have a program. I want it to be able to mmap a particular region of memory over different runs.
I have the source code of the program. C/C++I control how the program is compiled. gccI control how the program is linked. gccI control how the program is run (Linux).
I just want to have this particular region of memor... |
You need to do two things:
Specify the starting address as the first argument to mmap.Include the MAP_FIXED flag.
For the starting address, you need to make sure it's a multiple of the pagesize. To get the pagesize, use the callsysconf(_SC_PAGESIZE)(that's the appropriate call on Linux, other platforms may be diffe... |
In my programming class, I don't understand what the value ofprintf("World")is (question my prof is asking)? What value doesprintfreturn? He says it is 5, but I don't know why.
|
Becauseprintf()returns the number of bytes that were output. For "World", that's 5: 5 characters, 5 bytes. Count 'em...
When you're learning a new language, it's always a good idea to read the documentation for the new functions you're learning how to use. If you follow the link above, you'll find the following docum... |
gcc c89
I am came across this code.
```
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int32 uint64_t;
```
I am just wondering that is the __int32 I didn't think that was a type? Why the underscore?
Does this mean I could do things like this?
```
typedef __... |
The type is not standard, but is supported on your compiler.
Symbols that begin with an underscore or contain two underscores are reserved by the standard for your compiler's implementation.
SeeWhy do people use __(double underscore) so much in C++(The question is about C++ but the reason is the same)
|
Are there any portable open source libraries that support sample-based synthesis and encapsulate producing and mixing simple PCMs?
I really need something minimalistic and decoupled from operating system audio output mechanisms.
|
csoundhas aC apiand can handle PCM.ffmpegcan also convert lots of popular formats in PCM.
|
here is a code sample
```
void something()
{
char c[100];
scanf("%s",c);
char c2[100]=c;
}
```
my problem is when i do this assignment an error says that i can't assign
```
char * "c" to char[] "c2";
```
how can i achieve this assignment?
|
You'll have to usestrcpy()(or similar):
```
...
char c2[100];
strcpy(c2, c);
```
You can't assign arrays using the=operator.
|
```
#include <stdio.h>
int main() {
// Declarations
int iCount1, iCount2;
int iXXTest[4][3] = {{2, 3, 5}, {9, 8, 6}, {1, 8, 4}, {5, 9, 7}};
// Walk through 1st dimension
for (iCount1 = 0; iCount1 < 4; iCount1++) {
// Walk through 2nd dimension
for (iCount2 = 0; iCount2 < 3; iCount... |
It means that you've used the format of %d (for integer) but the argument is actually a pointer. Use %p instead.
|
I have a linux shared library (.so) compiled with a specific version of libc (GLIBC2.4) and I need to use it on a system with different version of libc. I do not have sources for the library in question so I cannot recompile for the new system. Is it somehow possible to change the dependencies in that library to a dif... |
If you need the .so on a system with an older glibc, you would need the source code and recompile/relink it with the older glibc. The alternative is to install the required glibc on the old system in a non-default location and adjust the LD_LIBRARY_PATH for the executable that needs this .so
If there's a newer glibc ... |
What's the best practice to include existing C Libraries into an iPhone Project? I searched the Internet and actually found some pieces but nothing that explains the exact way to do it.
I'm trying to include the followingCitrix XenServer SDK Library.
Any help is appreciated. Thanks!
|
You could try to build a static library and link against that.I didn't try that myself yet, but as far as I could see, libxenserver has libxml2 as its only dependency.libxml2 is available on the iPhone so you might have a chance.To get started, create a Cocoa touch static library project and drag the C files into the ... |
This question already has answers here:Why is main() in java void?(4 answers)Closed5 years ago.
With respect to C/C++ main() must always return an integer(zero to indicate success and non-zero to indicate failure). I can understand this as the program is run it becomes a process and every process should have an exit ... |
Designed when multi-threading was already a common thing, java said (by design) "good bye" to the idea that when 'main' returns the program is done. That's why there's no return value. As the others said useSystem.exitwhen you want to exit with return code.
|
How to calculate the length of a string in C efficiently (in time)?
Right now I'm doing:
```
int calculate_length(char *string) {
int length = 0;
while (string[length] != '\0') {
length++;
}
return length;
}
```
But it's very slow compared to strlen() for example, is there any other way to d... |
From theFreeBSD source code:
```
size_t
strlen(const char *str)
{
const char *s;
for (s = str; *s; ++s);
return(s - str);
}
```
Compared to your code, this probably maps very nicely to an assembler instruction, which can explain a big performance difference.
|
I have a custom allocator function which uses sbrk() to obtain memory.
How do I release this memory when it's no longer needed?
Is there a function equivalent to free() for malloc() ?
or do I have to use brk() to set the end of the data segment ?
|
You need to usebrkorsbrkagain to shrink.
In the end the only way you have to modify the amount of memory(apart from mmap like syscalls), is to increase or decrease the heap, so you move it up withsbrkorbrkand you move it down withbrkorsbrkwith a negative increment.
|
Is there a possibility that strcat can ever fail?
If we pass some incorrect buffer or string, then it might lead to memory corruption. But, apart from that is it possible that this function can return failure like strcat returning NULL even if destination string passed is Non-NULL? If no, why strcat has a return type... |
Returning a pointer to the target string makes it easy to use the output in this sort of (perhaps not-so-clever) way:
```
int len = strlen(strcat(firstString, secondString));
```
|
In C, I want a block of statements to be executed repeatedly everytseconds. How do I do this?
|
This cannot be done in standard C, you need to use some platform-specific API.
One popular choice is POSIX'alarm()function.
This is a "pure" aynchronuous solution. It's of course possible to measure and handle time in other ways, but they're still platform-dependent. You could usesleep()(again, POSIX) to just block.... |
Will the strlen() function below get called just once (with the value stored for further comparisons); or is it going to be called every time the comparison is performed?
```
for (i = 0; i < strlen(word); i++)
{ /* do stuff */ }
```
|
That's implementation-dependent. Usually, it gets called every time, but, if the compiler can see thatwordnever changes, and thatstrlenis a pure function (no side effects), it can lift the call.
See:http://underhanded.xcott.com/?page_id=15for a well-known example of this being exploited. :-)
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
```
if (0==strcmp(s, "abbccc"))
return "a1b2c3";
else
tip_the_interviewer(50);
```
Taken care of.
|
I wonder if we can get the file name including its path from the file object that we have created for the file name in C and in C++ respectively
```
FILE *fp = fopen(filename, mode); // in C
ofstream out(filename); // in C++
ifstream in(filename); // in C++
```
Thanks!
|
You can't, in general. The file may not ever have had a file name, as it may be standard input, output, or error, or a socket. The file may have also been deleted; on Unix at least, you can still read to or write from a file that has been deleted, as the process retains a reference to it so the underlying file itself ... |
I encountered a bug that has me beat. Fortunately, I found a work around here (not necessary reading to answer this q) -
http://lists.apple.com/archives/quartz-dev/2009/Oct/msg00088.html
The problem is, I don't understand all of it. I am ok with the event taps etc, but I am supposed to 'set up a thread-safe queue)... |
It'sone of the Multiprocessing Services APIs.
… [A] message queue… can be used to notify (that is, send) and wait for (that is, receive) messages consisting of three pointer-sized values in a preemptively safe manner.
|
Does anyone know how to save gdb settings (like "set print pretty on" or "set print elements 0", both fromhere)? I don't want to set my configuration every time that I will use gdb :/
I searched in google and SO, but I found nothing.
|
Add any commands you want to auto run in the.gdbinitfile in your home directory.
|
I want to be able to determine at runtime what the sector size is for a give filesystem. C code is acceptable. for example I format my Data partitions with a 32k sector size that have lots of large video files. I want to be able to get this value at runtime.
|
I think you wantstatvfs(if by pagesize you mean sector size?) which from what I remember works linux and OSX. I think you need to use the f_bsize field but I unfortunately do not have a linux box to test against atm.
For windows you want theGetDiskFreeSpacefunction.
|
I am new to GTK+ programming. I came across an API calledg_main_loop(). I have used it in my code but I am still unaware that how exactly it works. Can somebody explaing_main_loop()with small code snippet?
|
I recommendreading the documentation, starting with the linked-to functiong_main_loop_new().
Basically, letting glib "own" your application's main loop makes it easier to support things like "pluggable" event sources; where your application listens to both (for example) events coming from GTK+ widgets, and a network ... |
I saw this in some C code:
```
Wininfo W = { sizeof(Wininfo) };
```
What the heck does this mean?
|
This code is initializing astructusing funky C initializer syntax to initialize each field in order of declaration, seehttp://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=421. An important side-effect in the case of this example is that remaining fields one doesnt specify values for get initialized to zeros... |
I have a program that accepts two file names as arguments: it reads the first file in order to create the second file. How can I ensure that the program won't overwrite the first file?
Restrictions:
The method must keep working when the file system supports (soft or hard) linksFile permissions are fixed and it is on... |
On linux, open both files, and usefstatto check ifst_ino(edit:) andst_devare the same.openwill follow symbolic links. Don't usestatdirectly, to prevent race conditions.
|
is there an elegant way to start a 64 bit process from an 32 bit compiled application?
The problem is that i need to compile one part in 32bit Sparc V8 mode. The other part is written for a faster 64 bit environment (no emulation on 64bit multiplication). I want to synchronize them using semaphore and communicate via... |
Use fork() then exec(). Generally multi-process stuff remains the same even in a mixed environment.
|
I know I can convert SQL timestamp to unix timestamp, using the following way.
```
SELECT extract(epoch FROM now());
```
Now, I have a stored procedure function, which will directly return a table row to the caller. One of the row field is "timestamp" type.
In my application, I am using libpq. I wish to use libpq f... |
Why not simply (untested):
```
/* PostgreSQL sent "date" */
strptime(date, "%Y-%m-%d %H:%M:%S", &result);
```
then
```
strftime(epoch, MAX, "%s", result);
/* print epoch */
```
|
How can I lock a file for a specified period of time (10 seconds) using the C language in Ubuntu Linux ?
|
It works like this:
```
#include <io.h>
#include <sys/file.h>
...
int f = open ("filename", O_RDONLY);
if (f < 0)
error();
if (flock (f, LOCK_EX))
error();
sleep (10);
if (flock (f, LOCK_UN))
error();
...
```
|
I am trying to add a new IP address to a local network adapter in Windows using the Windows API. Are there functions to do this in the Windows API, and if so, what are they?
I am not trying to create virtual network adapters, but simply trying to assign multiple IP addresses to the same adapter.
|
Take a look atAddIPAddressandDeleteIPAddress.
|
I have a function which is called explicitly by 4 other functions in my code base. Then in turn each of these functions is called by at least 10 other functions throughout my code. Iknowthat I could, by hand, trace one of these function calls to the main function of my program (which has 30 function calls) but it se... |
doxygen, correctly configured, is able to output an HTML document with navigable caller list and called-by list for every function in your code. You can generate call graphs as well.
|
I have a simple C DLL (not COM). I have also a C# 2.0 application that runs it (dllimport). The dll is placed in the exe of the application. I know that the dll is ok and also that my application that calls it success reading it, but when I move them to another computer it says that it can load the dll.
The error : "... |
The C Dll can have various dependencies. Try using Dependency Walker tool to determine if there are any of them.
|
I am trying to understand what the following line of the worst-ever-seen C code (fromubootproject) mean:
```
rc = ((ulong (*)(bd_t *, int, char *[]))addr) (bd, --argc, &argv[1]);
```
What is it? A function call?
Can it be more readable?
Thanks in advance for your help!
|
Yes, it's a function call.
It casts the value inaddrto a function pointer which accepts(bd_t *, int, char *[])as arguments and returns aulong, and calls the function. It could be sugared into:
```
typedef ulong (*bd_function)(bd_t *bd, int argc, char *argv[]);
bd_function bdfunc = (bd_function) addr;
rc = bdfunc(b... |
Can someone explain how does less than op work in C?
In particular how it works when types of left hand side and right hand side operands are different?
Does it compare them based on type of the first one or the second one?
|
C specifies standard conversions for different types. The rules are a bit complex, but basically the "smaller" type gets temporarily converted to the larger type, So if you compare an int with a char, the char will be converted to an int, for the purposes of the comparison only.
|
A function returns an aray of integers and I want it to pass to another function which searches for some pattern. But the second function expects a string.
Example:
```
int IArray = {1, 2, 3};
// should be coverted into "123"
```
Is there a direct function available? If not, how do I convert the array of integers ... |
There is no direct function to do that.
You'll have to usesprintf.
|
I am developing C++ in NetBeans 6.7.1. When I press CTRL + space for autocomplete there is shown only method's signature. I am using JavaDoc for commenting my code but NetBeans doesn't show it. I have installed Doxygen plugin but it is only for generating complete documentation.
Is there any way how to force the IDE ... |
So I asked on NetBeans forum thisquestion( using friend's account because I don't have my own ) and there is the conclusion: It is impossible and it is in requests.
|
Is it possible to distribute only the bytecode version (.pyc file) of a Python script instead of the original .py file? My app embeds the Python interpreter and calls PyImport_Import to load a script. How can I tell it to look for a .pyc file and import that?
|
Use thefreezetool, which is included in the Python source tree asTools/freeze. It converts Python byte code to C arrays; with a C compiler you can embed all your modules into a new program, which is then linked with the standard Python modules.
Note that freeze requires a C compiler.
Other utilities:
1-PyInstaller
... |
In the book "Complete Reference of C" it is mentioned thatcharis by default unsigned.
But I am trying to verify this with GCC as well as Visual Studio. It is taking it assignedby default.
Which one is correct?
|
The book is wrong. The standard does not specify if plaincharis signed or unsigned.
In fact, the standard defines three distinct types:char,signed char, andunsigned char. If you#include <limits.h>and then look atCHAR_MIN, you can find out if plaincharissignedorunsigned(ifCHAR_MINis less than 0 or equal to 0), but e... |
how do you reverse and rotate hex numbers and return the number in C with bitwise operators?
for example:
```
0xabcd -> 0xdcba
0xabcd -> 0xdabc
```
|
It's hard to know where to begin with this question. Plus I smell homework.
Some points:
There is no such thing as a "hex number". Hex is just a notation. How do you reverse and rotate decimal numbers and return the number in C? For example:1776 -> 67711776 -> 6771?To solve this problem, you need a deep understa... |
I tried doing this in C:
```
int val = 0xCAFE;
int uc = val & 14;
if (val & 15 == 15 || val & 7 == 7 || val & 11 == 11|| val & 13 == 13 || val & 14 == 14){
printf("asdjfkadscjas \n");
}
```
However this is not printing the random string as it should. It worked for 15,7,11,13 tho.
If anyone knows of a better w... |
Alternative solution: You can put all your numbers into a binary-coded lookup table:
```
int AtleastThreeBits (int a)
{
return (0xe880>>(a&15))&1;
}
```
Each bit of the magic number represents an answer. In the constant 0xe880 bits 7,11,13,14 and 15 are set. You select the correct bit using a shift and mask it out... |
I have a custom allocator function which uses sbrk() to obtain memory.
How do I release this memory when it's no longer needed?
Is there a function equivalent to free() for malloc() ?
or do I have to use brk() to set the end of the data segment ?
|
You need to usebrkorsbrkagain to shrink.
In the end the only way you have to modify the amount of memory(apart from mmap like syscalls), is to increase or decrease the heap, so you move it up withsbrkorbrkand you move it down withbrkorsbrkwith a negative increment.
|
Is there a possibility that strcat can ever fail?
If we pass some incorrect buffer or string, then it might lead to memory corruption. But, apart from that is it possible that this function can return failure like strcat returning NULL even if destination string passed is Non-NULL? If no, why strcat has a return type... |
Returning a pointer to the target string makes it easy to use the output in this sort of (perhaps not-so-clever) way:
```
int len = strlen(strcat(firstString, secondString));
```
|
In C, I want a block of statements to be executed repeatedly everytseconds. How do I do this?
|
This cannot be done in standard C, you need to use some platform-specific API.
One popular choice is POSIX'alarm()function.
This is a "pure" aynchronuous solution. It's of course possible to measure and handle time in other ways, but they're still platform-dependent. You could usesleep()(again, POSIX) to just block.... |
Will the strlen() function below get called just once (with the value stored for further comparisons); or is it going to be called every time the comparison is performed?
```
for (i = 0; i < strlen(word); i++)
{ /* do stuff */ }
```
|
That's implementation-dependent. Usually, it gets called every time, but, if the compiler can see thatwordnever changes, and thatstrlenis a pure function (no side effects), it can lift the call.
See:http://underhanded.xcott.com/?page_id=15for a well-known example of this being exploited. :-)
|
I want to write a library for my Arduino(header and class files), but I don't know what tools to use for this job and how to test and debug them.
The Arduino IDE just helps in writing plain programs for direct bootloading, not full project management thing (correct me if I am wrong and guide appropriately with releva... |
The compiler supports the#includedirective, you can write your library, then#includeit. This is expanded onin this tutorial about writing libraries for the Arduino.
|
In C language, how to get struct's start address from its member's address?
```
struct type1 {
//...
int member1;
//...
};
struct type1 obj1;
```
Andptr1is the address of membermember1inobj1, how to definemacro#define start_add(ptr1, type1, member1)to get obj1'sstart address?
|
You can do this usingoffsetof:
```
#define start_add(ptr1, type1, member1) ((type1 *)((char *)(ptr1) - offsetof(type1, member1)))
```
|
I don't understand why the ABI is important context of developing user-space applications. Is the set of system calls for an operating system considered an ABI? But if so then aren't all the complexities regarding system calls encapsulated within standard libraries?
So then isABI compatibilityonly relevant for runnin... |
AnABIdefines a set of alignment, calling convention, and data types that are common to a system. This makes an ABI awfully important if you're doing any sort of dynamic linking; as without it code from one application has no way of calling code provided by another.
So, no. ABI compatibility is relevant for all dyna... |
I'm currently trying to patch theTotem Youtube plug-inand I'd like to determine the best quality available for the current played video (&fmt parameter). It's possible inJavaScriptbut the plug-in is developped in C.
Is that possible?
|
Are you playing the videos in the YouTube video player?
If so, you can query the quality levels through theActionScriptor JavaScript API,
seehttp://code.google.com/apis/youtube/js_api_reference.html#Playback_quality.
|
Why does the following code compile?
```
#include <stdio.h>
int main(void) {
getchar;
}
```
|
Because function names are aliases to function pointers to those functions, which are themselves values much like integers.. This is semantically very similar to
```
#include <stdio.h>
int main(void) {
42;
}
```
It is valid but pointless.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.