question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
This question already has answers here:ARC forbids Objective-C objects in structs or unions despite marking the file -fno-objc-arc(4 answers)Closed9 years ago.
That's the problem, when I try to build my xcproject xcode show me an error on the 3rd row of the following code :
```
typedef struct
{
NSArray *array;
... |
I had simmilar issue and I sorted it by added__unsafe_unretainedkeyword like that:
```
typedef struct
{
__unsafe_unretained NSArray *array;
__unsafe_unretained NSString *string;
}WYnot;
```
Try it should help.
|
I try to compile a dummy AVX2 program on my Mac OS 10.9 with gcc version 4.9.0 20131201
```
//dummy program
#include <immintrin.h> // AVX2
#include <stdio.h>
int main(int argc, char* argv[]) {
__m256i reg = _mm256_set1_epi8(1);
__m256i result = _mm256_max_epu8(reg,reg);
printf("%d",((int *)&result)[0]);
}
`... |
To compile for a target with AVX2, use-mavx2.
|
Im sure Im missing something simple, and obvious, but I am tired of searching for the answer. Im using aPIC16F688andXC8compiler.
The compiler user manual says that there is adelay function __delay_ms(). It says that_XTAL_FREQmust be defined.
Here is my code, but it does not accept the command. What is wrong?
```... |
They are right, the problem was experienced by older versions of the IDE's. I have found it helpful to use:
```
while(1){
//Invert LED state
LED = !LED;
//Delay ~1 second (4MHz Internal Clock)
_delay(1000000); //specify clock cycles directly
}
```
To solve the problem.
|
I'm trying to do IO usingstdio.hon a Commodore 64, but I'm having with even the following program:
```
#include <stdio.h>
void main(void)
{
printf("Foo\n");
printf("Bar\n");
/* printf("Foo\n"); */
/* printf("Bar\n"); */
}
```
The problem is, if I leave 2printfs uncommented, then it works as expected... |
After following @Devolus's suggestion to do sanity checking withsleep, it turned out nothing, in general, was working properly. I've downgraded my CC65 installation from 2.13.9-svn5804 to 2.13.3, and that seems to have solved my problem.
|
I have a network programming c code that can retrieve a HTTP page, the thing is I want to remove GET response header that come with the actual data of the page, I know that I have to look for the first "\r\n\r\n" but all the thing that I've tried so far didn't work !
so how can I strip these response header line from ... |
As the GET response header is at the beggining of the buffer, you may try to find the first occurence of "\r\n\r\n" using a function like strstr:
```
char *p = strstr(buffer, "\r\n\r\n");
```
and then return p+4, because p will point to the first \r. p+4 will point to whatever is after the "\r\n\r\n". To return it f... |
I Need to write the following struct to a fifo:
```
struct msg_t {
int length;
char* msg;
};
```
I malloc the struct and the char* inside it and I write like this:
(let's assume msg is the variable name)
write(fifo_fd, &msg, sizeof(msg_t));
The length is read from the other end just fine.
The string isn't..
H... |
you will just be writing the length and the pointer address, which I doubt is what you will want at the other end. My guess is what you actually want is something like this:
```
struct msg_t msg;
// Initialise msg
write( fifo_fd, &(msg.length), sizeof(int) );
write( fifo_fd, msg.msg, msg.length );
```
|
Should I use the header ctgmath? It automatically includes cmath and ccomplex. It has some predefined macros. Should its inclusion affect my code or usage of these macros decrease the efficacy?
|
No, Simply including the headers in your code doesn't decrease the efficiency... Also macro inclusion doesn't change the speed cos, macro expansion happens during compile time not at run time.
|
I just downloaded Visual Studio 2013. When I compile C, it doesn't show me my output. The output screen will show up for a brief second and then disappears.
```
#include <stdio.h>
int main()
{
printf("hi");
return 0;
}
```
"The program '[5688] Project1.exe' has exited with code 0 (0x0)."
I know my code work... |
You can run the application in debug mode and in release mode. NormallyCtrl + F5will run the application without debugger. AndF5just runs the application.
If you doCtrl+F5("Start without Debugging"), the console remains open at the end and asks you toPress any key to continue . . .here you can see the output.
If you... |
I've looked at__attribute__((constructor)) equivalent in VC?andCRT Initialization, which were both helpful regarding the gcc-specific__attribute__((constructor)). But what about__attribute__((destructor))? Is there a VC equivalent?
|
If you're making a dynamic link library, you can make yourDllMain entry pointhandle this:
```
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
if (fdwReason == DLL_PROCESS_ATTACH)
{
// equivalent of __attribute__((constructor))...
// return TRUE if succeeded, FAL... |
I have following code in C:
```
pthread_cleanup_push(pthread_mutex_unlock, &mutex);
```
however when I compile it, I get the following warning:
```
warning: initialization from incompatible pointer type
```
What's wrong? It looks like the cleanup handler should return void*, not int. Is there any way to bypass thi... |
The expressionpthread_mutex_unlockdoes not have typevoid (*)(void *). You need to wrap it:
```
static void cleanup_unlock_mutex(void *p)
{
pthread_mutex_unlock(p);
}
```
and pass this function's address topthread_cleanup_push.
Others may advise you to just castpthread_mutex_unlock, but this is incorrect and uns... |
My code:
```
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = (int *)malloc(sizeof(int));
free(p);
*p = 42;
return 0;
}
```
I created a pointer, then I pointed it to allocated space and finally I had assigned 42 to it.
In my opinion it should not work, it should cause a segmentation ... |
Pure luck. The behavior in this case isundefined. I.e.: no expectations can be made as to what may happen.
|
The code is pretty simple. I don't understand why my program crashes when I try to print outpointok2. Maybe I don't see the problem because I am tired or something. A little help would be appreciated.
Tokmainwill always be of the format "word word".
```
scanf("%s",&tokmain);
for(i=0;i<50;i++) {
if (tokmain[i]=='... |
scanf()truncates at the space. So,tokmainwill only have "word" when you enter "word word".
Try
```
scanf("%49[^\n]s",&tokmain); /*Notice the format string*/
for(i=0;i<50;i++) {
if (tokmain[i]=='\n') {
tokmain[i]='\0';
lettercount=i;
break;
}
}
pointok1=strtok(tokmain,delim);
pointok2... |
I'm trying to add a file to index to create a commit with libgit2.
The repo and index are like that:
```
git_repository *repo;
git_index *my_repo_index;
git_repository_open(&repo, ".");
git_repository_index(&my_repo_index, repo);
git_index_add_bypath(my_repo_index,"a.txt");
//all functions are returning 0, or succes... |
Changes to the index are not immediately written to disk. You might, for example, wish to perform a number of actions and save them all at once. In order to save the index:
```
git_index_write(my_repo_index);
```
|
I read string from file if the string in the file is:
```
"User1 User2 User3 User4 User5"
"test1"
```
i want to read only the first line from the file,my code is:
```
if (in_fp != NULL)
{
while (fscanf(in_fp, "%s", &user)!=EOF)
{
temp = (char*)malloc(sizeof user);
strcpy(temp,user);
}
fcl... |
a way
```
if (in_fp != NULL){
while (fscanf(in_fp, "%s%c", user, &ch)==2){
temp = (char*)malloc(sizeof user);
strcpy(temp, user);
//do something
printf("%s\n", user);
free(temp);
if(ch == '\n')
break;
}
fcl... |
Is this a right way to allocate memory in order to store two concatenated strings?
```
size_t len1 = strlen(first);
size_t len2 = strlen(second);
char * s = malloc(len1 + len2 + 2);
```
or should I usemalloc(len1 + len2 + 1)?
|
Let's look at what's necessary to store a string:
one byte per character (assuming non-wide chars)one trailing NUL byte ('\0', or just0)
That makes itstrlen(first) + strlen(second) + 1:
```
char *s = malloc(len1 + len2 + 1);
```
|
Can someone explain this behavior?
Using the compiler flagstd=c99I get the following errors:
"initializer element is not constant" for b1."expected expression before '.' token" for b2b3 is OK.
When not using-std=c99all lines are OK.
When not using static b1 is ok.
I'm using GCC.
```
typedef struct A_tag {
int... |
(B){.super={.v=100}, .x=10}is not a "cast" but as a whole this is a "compound literal" a temporary object that only lives inside the corresponding expression (basically). Since this is not a constant but a temporary object, by the standard you can't initialize with it.
|
From my understanding you need opening and closing braces for any 'standard construct in the language' (eg. a for loop/if statement etc. I don't know the real word for it) that contains multiple statements. So, why is this K&R C valid...
```
while((len = getline(line, MAXLINE)) > 0)
if(len > max) {
max = len;
... |
In your case, there's only one statement under your while loop which is theifcondition. In that case, this code is correct.
|
I am recently doing a school homework and I am stuck, in creating dynamic array of structs. I was looking everywhere, but no answer helped me, so can you please look at my code and help me, what is wrong?
I keep getting error:
C:\kof\test1\main.c|29|error: request for member 'lenght' in something not a structure or u... |
Since*failis a pointer of type struct journey, you access its elements using the '->' notation and not using the.notation as statedhere
|
I have a program with two processes and two files and I want to read a var with the code of the second file by shared memory but I only get the "testing" word, not the text. the code of first file of the program:
```
a=shmget(key, 200, 0666|IPC_CREAT);
text=(char *)shmat(a,0,0);
text=&words[0];
if ((P2=fork())==... |
You never put anything in the shared memory; you just changed the value oftextto point to something other than the shared memory.
Instead of:
```
text=&words[0];
```
You probably wanted something like:
```
memcpy(text, &words[0], strlen(words[0]) + 1);
```
|
I am trying to remove the negative numbers from array with the following code. Unfortunately, not getting the results. It just prints the first element over and over. Can someone please let me know where am I going wrong?
```
#include <stdio.h>
void removenegative(int a[],int *p, int *q);
int main()
{
int a[] = {... |
```
for(i=0;i<6;i++)
{
printf("%2d", *p);
}
```
You're not changingp!
|
I read string from file if the string in the file is:
```
"User1 User2 User3 User4 User5"
"test1"
```
i want to read only the first line from the file,my code is:
```
if (in_fp != NULL)
{
while (fscanf(in_fp, "%s", &user)!=EOF)
{
temp = (char*)malloc(sizeof user);
strcpy(temp,user);
}
fcl... |
a way
```
if (in_fp != NULL){
while (fscanf(in_fp, "%s%c", user, &ch)==2){
temp = (char*)malloc(sizeof user);
strcpy(temp, user);
//do something
printf("%s\n", user);
free(temp);
if(ch == '\n')
break;
}
fcl... |
Is this a right way to allocate memory in order to store two concatenated strings?
```
size_t len1 = strlen(first);
size_t len2 = strlen(second);
char * s = malloc(len1 + len2 + 2);
```
or should I usemalloc(len1 + len2 + 1)?
|
Let's look at what's necessary to store a string:
one byte per character (assuming non-wide chars)one trailing NUL byte ('\0', or just0)
That makes itstrlen(first) + strlen(second) + 1:
```
char *s = malloc(len1 + len2 + 1);
```
|
Can someone explain this behavior?
Using the compiler flagstd=c99I get the following errors:
"initializer element is not constant" for b1."expected expression before '.' token" for b2b3 is OK.
When not using-std=c99all lines are OK.
When not using static b1 is ok.
I'm using GCC.
```
typedef struct A_tag {
int... |
(B){.super={.v=100}, .x=10}is not a "cast" but as a whole this is a "compound literal" a temporary object that only lives inside the corresponding expression (basically). Since this is not a constant but a temporary object, by the standard you can't initialize with it.
|
From my understanding you need opening and closing braces for any 'standard construct in the language' (eg. a for loop/if statement etc. I don't know the real word for it) that contains multiple statements. So, why is this K&R C valid...
```
while((len = getline(line, MAXLINE)) > 0)
if(len > max) {
max = len;
... |
In your case, there's only one statement under your while loop which is theifcondition. In that case, this code is correct.
|
I am recently doing a school homework and I am stuck, in creating dynamic array of structs. I was looking everywhere, but no answer helped me, so can you please look at my code and help me, what is wrong?
I keep getting error:
C:\kof\test1\main.c|29|error: request for member 'lenght' in something not a structure or u... |
Since*failis a pointer of type struct journey, you access its elements using the '->' notation and not using the.notation as statedhere
|
I have a program with two processes and two files and I want to read a var with the code of the second file by shared memory but I only get the "testing" word, not the text. the code of first file of the program:
```
a=shmget(key, 200, 0666|IPC_CREAT);
text=(char *)shmat(a,0,0);
text=&words[0];
if ((P2=fork())==... |
You never put anything in the shared memory; you just changed the value oftextto point to something other than the shared memory.
Instead of:
```
text=&words[0];
```
You probably wanted something like:
```
memcpy(text, &words[0], strlen(words[0]) + 1);
```
|
I am trying to remove the negative numbers from array with the following code. Unfortunately, not getting the results. It just prints the first element over and over. Can someone please let me know where am I going wrong?
```
#include <stdio.h>
void removenegative(int a[],int *p, int *q);
int main()
{
int a[] = {... |
```
for(i=0;i<6;i++)
{
printf("%2d", *p);
}
```
You're not changingp!
|
I am new toObjective-C, here I came acrossstringWithUTF8Stringclass method.
So, I search the method at apple developer library and I came to this sentence
Returns a string created by copying the data from a given C array of UTF8-encoded bytes.
After reading I do not have a single clue what the sentence is saying.
I... |
It simply creates a Cocoa NSString from an utf8 encoded (http://en.wikipedia.org/wiki/UTF8) c string (a char*).
```
const char* cstr = "I am a c string";
NSString* str = [NSString stringWithUTF8String:cstr];
```
|
What the difference of twodefine?
```
#define NUM 123
#define NUM_TO_STRING1(x) #x
#define NUM_TO_STRING(x) NUM_TO_STRING1(x)
printf("NUM_TO_STRING1: %s\n", NUM_TO_STRING1(NUM));
printf("NUM_TO_STRING: %s\n", NUM_TO_STRING(NUM));
```
result:
```
NUM_TO_STRING1: NUM
NUM_TO_STRING: 123
```
Wh... |
With the#, you're asking it not to. All#does is tostringifythe thing that immediately follows it. The idiom that I think you're trying to exploit is a common one:
```
#define STR(_a) #_a
#define XSTR(_a) STR(_a)
#define BAR foo
```
With things set up like this,
```
STR(BAR)
```
Will give you"BAR"and
```
XSTR(... |
This question already has answers here:How would one write object-oriented code in C? [closed](32 answers)Closed9 years ago.
I have seen that we can implement multiple inheritance in ANSI C?
As we can create any class like
```
struct sampleClass {
int size;
struct sampleClass *ptr1;
};
```
As I tred to cre... |
It depends what you mean by "implementinginheritancein C".
It has certainly been done with macros, coding guidelines and styles, andstructof function pointers (mimickingvirtual method table) and othermetadata. A good example comes fromGTKwith itsGObjectlayer.
|
I am new toObjective-C, here I came acrossstringWithUTF8Stringclass method.
So, I search the method at apple developer library and I came to this sentence
Returns a string created by copying the data from a given C array of UTF8-encoded bytes.
After reading I do not have a single clue what the sentence is saying.
I... |
It simply creates a Cocoa NSString from an utf8 encoded (http://en.wikipedia.org/wiki/UTF8) c string (a char*).
```
const char* cstr = "I am a c string";
NSString* str = [NSString stringWithUTF8String:cstr];
```
|
What the difference of twodefine?
```
#define NUM 123
#define NUM_TO_STRING1(x) #x
#define NUM_TO_STRING(x) NUM_TO_STRING1(x)
printf("NUM_TO_STRING1: %s\n", NUM_TO_STRING1(NUM));
printf("NUM_TO_STRING: %s\n", NUM_TO_STRING(NUM));
```
result:
```
NUM_TO_STRING1: NUM
NUM_TO_STRING: 123
```
Wh... |
With the#, you're asking it not to. All#does is tostringifythe thing that immediately follows it. The idiom that I think you're trying to exploit is a common one:
```
#define STR(_a) #_a
#define XSTR(_a) STR(_a)
#define BAR foo
```
With things set up like this,
```
STR(BAR)
```
Will give you"BAR"and
```
XSTR(... |
This question already has answers here:How would one write object-oriented code in C? [closed](32 answers)Closed9 years ago.
I have seen that we can implement multiple inheritance in ANSI C?
As we can create any class like
```
struct sampleClass {
int size;
struct sampleClass *ptr1;
};
```
As I tred to cre... |
It depends what you mean by "implementinginheritancein C".
It has certainly been done with macros, coding guidelines and styles, andstructof function pointers (mimickingvirtual method table) and othermetadata. A good example comes fromGTKwith itsGObjectlayer.
|
I am using DirectFB(without X, using fbcon driver(with vesafb) to write to screen buffer). I can do keyboard input, but I want to use my mouse.(Get cursor coordinates/Show cursor/Click events)
Can someone give example code or tell me how it's done? Also do I need GPM for it? I tried mplayer which is based on directfb... |
I just tried SDL. Works like a charm, no X needed or anything else for that matter, just one executable plus libraries. No GPM needed too. I am so happy right now :)
|
Why
```
printf("%s\n","\061");
```
prints1in output. I expect something like=
|
061 octal == 49 decimal == 0x31 hex. That's the ASCII code for the character'1'
Why do you expect'='?
|
I have this instruction:
```
asm("message: .byte 'Hello, World!', 0x0A");
```
For some reason the compiler saysjunk at end of line, first recognized character is 'e'. I tried replacing the.bytewithdbaccording to other examples on the web. Then the output wasno such instruction: 'db 72ello, World!440x0A'(notice the n... |
.byteonly works for a single byte, like 0xFA, or 'F'.dbis intel syntax, inline assembly uses GNU syntax.As mentioned above,.byteonly works for one byte. To use strings, use either.asciior.asciz-- the former is a simple array of bytes, while the latter is null terminated.
ie.asm("message: .asciz \"Hello, World!\n\"");... |
I came across a question in the book and it asked me to write the output of the following program.
```
#include<stdio.h>
int main()
{
int j=4;
( !j != 1 ? printf("\nWelcome") : printf("GooD Bye"));
return 0;
}
```
I am not able to understand basically how the Welcome is printed on running the program... |
The line
```
( !j != 1 ? printf("\nWelcome") : printf("GooD Bye"));
```
is equivalent to
```
if(!j != 1)
printf("\nWelcome);
else
printf("Good Bye");
```
Here!jevaluates to0therefore the condition!j != 1will always be true and it will printWelcome.
|
Is there linux system call similar to fsync but uses file path instead of file descriptor?
I modify file modification time using utime, the file is in USB, I need to make sure the time is flushed to usb after setting utime.
|
As far as I know there isn't.
To do so you need to
open()the filecallfsync()on the fd returned by 1.close()the fd returned by 1.open()the containing directorycallfsync()on the fd returned by 4.close()the fd returned by 4.
As you are after updating the file's meta-data the steps 4 to 6arenecessary to get the directo... |
I want to copy a set of characters from an array, from an index to another.
For example i have an arraychar array[64]and I want to select characters from let's say 5-15 and store them in another char array.
I could do that with a for loop, but is there any function that does that? Like the C# method Substring. Thanks ... |
You can always usememcpyto achieve that and it would be more efficient anyway.
```
char a[100] = {0};
char b[100] = {1};
memcpy(&a[10], &b[30], 10);
```
|
I doinclude<stdlib.h>where qsort_r is given. And I usegcc -std=c99 -O3 myfun.c -o myfunto compile.
It compiles, links and runs well. I don't know why I got this warning and what is potential risk of this warning ?
BTW, my compiler isgcc version 4.7.3 (Ubuntu/Linaro 4.7.3-1ubuntu1)
|
It does so because you use-std=c99, there's no qsort_r function in stdlib.h in c99.
Use-std=gnu99to make the extensions available, or add a#define _GNU_SOURCEto your source files before including the header files.
|
Currently,strstrfunction returns the starting location of the found string; but I want to search for multiple strings and it should return me the location of the found string otherwise return NULL. Can anyone help how I can do that?
|
Store the answer, and callstrstr()again, starting at the returned location + the length of the search string. Continue until it returnsNULL.
|
I have my piece of code which is shown below
```
#include<cstdlib>
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
int main()
{
int a;
printf("Please select a choice \n1.Enter New Artist\n2.List All Artist information\n3. Show sorted List of Artists\n4.Add Album to existin... |
Yourscanfstatement is wrong. You are not passing argument (pointer) to it.
Change
```
scanf("%d,&a");
```
to
```
scanf("%d",&a);
```
|
I am going through the Linux kernel source code. I found following statements,
```
#ifdef CONFIG_REFCOUNT
typedef struct {
int counter;
} ato_unchecked_t;
#else
typedef int ato_unchecked_t;
#endif
```
What would be the purpose of having a structure with one int member or just
a typedef'd int like this ?
|
The only benefit to having a structure would be if all the code whereCONFIG_REFCOUNTis defined is designated as user customizable. More fields can be added to the structure that are logically related and used for user specific functionality.
|
I'm not sure why this is happening, I think I'm doing everything correctly.. Maybe someone can help point me in the right direction.
```
unsigned short* x;
int textLeft[16];
x = shm->textLeft;
```
These are spaced out in the program so I didn't want to copy a bunch of code but if more is needed please let ... |
No, this should not work, because you're assigning anint*value to anunsigned short*variable, which causes undefined behavior per the Cstrict aliasing rule.
The way to make this work without changing the types is to
cast the pointer,x = (unsigned short *)(shm->textLeft);, andcompile with GCC's-fno-strict-aliasingto t... |
I came across the following code snippet
```
if( 0 != ( x ^ 0x1 ) )
encode( x, m );
```
What doesx ^ 0x1mean? Is this some standard technique?
|
The XOR operation (x ^ 0x1) inverts bit 0. So the expression effectively means: if bit 0 of x is 0, or any other bit of x is 1, then the expression is true.
Conversely the expression is false if x == 1.
So the test is the same as:
```
if (x != 1)
```
and is therefore (arguably) unnecessarily obfuscated.
|
I am traversing through linux kernel code. I found a macro defined as#define __async_inline __always_inline. I searched for__always_inline,I found the following statement#define __always_inline inline. My question is why they need to do like this? They can directly useinlineinstead of this macro's?
|
The code says this:
```
#ifdef CONFIG_HAS_DMA
#define __async_inline
#else
#define __async_inline __always_inline
#endif
```
It is self-explained.__async_inlinewill be replaced byinlineifCONFIG_HAS_DMAis not defined.
|
I need to extract modulus, private exponent, public exponent, primes, etc. from an RSA private key given in PEM format. This is for an embedded system where I cannot install any crypto or RSA libraries on the target system, so everything should be done in native C. Any pointers to existing code or hints how this is ef... |
PEM file contains der encoded RSA Private Key in base64 format.
First you have to base64 decode it to get the original der encoded bytes. Then you have to parse the der encoded data.
As suggested byLie Ryan, you can statically link some C libraries to do this. Or you can refer to the source codes of an existing libr... |
Is it possible to modify and assemble the.sfile which can be generated by Intel's C compiler?
I know that it is possible with gcc via:
gcc -S file.cmodifyfile.sas file.s -o file.o
However, if I try exactly the same with Intel's icc it will result in several errors and warnings. What am I missing here? Thanks.
|
The problem with the assembly language is that there is no standard syntax, the most popular 2 syntax used to write assembly are the AT&T and Intel one.
Guess which one is being used by gcc, by default, and which one by Intel .
I suggest to use Intel syntax under gcc too so you can use just 1 syntax.
An example on ... |
I am completly lost and have no clue how to get the integers from a file to be inputted into an array. if a file looks like:
```
1 2 3
4 5 6
7 8 9
```
and I want an arraya[9] = {1,2,3,4,5,6,7,8,9}then how do I even go about doing this?
would something along the lines of this work?
```
int a[9];
int i;
infile = fo... |
Why not
```
for (int i = 0; fscanf(infile, "%d", &a[i]) == 1; ++i);
```
|
I am trying to just delete duplicates from a linked list so if the list started as [1,1,2,3,4,4,4,5], then the appended list would be [1,2,3,4,5]. Code is below.
```
struct node_h
{
int data;
struct node_h* next;
} node;
void remove_h(node* head)
{
while (head != NULL)
{
if (head->data == hea... |
The culprit isif (head->data == head->next->data)... ifhead->nextis null, this must segfault.
Check for this condition first, no duplicate is possible, if it is true: Just addif (head->next == NULL) break;as a first statement in the while or adapt the while condition.
|
According to thereference for wcstombs, wcstombs will translate wide-characters "until a wide character translates into a null character."
So what wide-characters are translated into a null multibyte? Is it a specific character? Or any character outside a given range?
|
Thewcstombsfunction will translate until theL'\0'character (the wide character NUL) is encountered in the wide string (or until the destination multibyte string is filled). That documentation describes what it does when it encounters an error.
|
I have been searching for some time and haven't found a definitive answer yet. The only link I found till now which sheds some light on this ishere.
|
According to thePOSIX Specificationsyslog(), openlog() and closelog() are thread safe.
There's another thread that answers this question as well and it is dated as far back as 2009. Here's the linksyslog_r for Linux?.
|
a simple question for you guys:
I wrote this loop that prints some values of an array.
i want space between every value but i would not like to have a space after the last value that the code prints.
any idea how do i do this without complicating too much?
```
for (i_talltrees=1; i_talltrees<=numtrees; i_talltrees+... |
Try this:
```
int flag = 0;
if (talltrees[pre]<talltrees[i_talltrees]&&talltrees[i_talltrees]>talltrees[post])
{
if(flag)
{
printf(" ");
flag = 0;
}
printf("%d", talltrees[i_talltrees]);
flag = 1;
}
```
|
I am getting error
```
pa_simple_new() failed: Connection refused
```
while trying to callpa_simple_newfunction. Here is the code.
```
int error;
static const pa_sample_spec ss = {
.format = PA_SAMPLE_S16LE,
.rate = 44100,
.channels = 2
};
/* Create the recording stream */
if (!(m_pAudioIn = pa_simple_... |
Reinstalling PulseAudio fix the issue
|
```
int main ()
{
float Num = 3254.4;
printf("%06.4f",Num);
return 0;
}
```
Why it doesn't print003254.3999as my expectation, but3254.3999?
I've completely read this referencebefore posting.
|
From your Reference:
width:
Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
Note that this counts all characters including the . and the four decimal places
6 to the ... |
Need to make int from hex representation string like"0xFA"or better"FA". Need something likeatoi("FA"). Is there are any standard solutions for that?
|
Try to usestrtol():
```
strtol("FA", NULL, 16);
```
|
I have a functionint handle_request(server* server, int conn_fd);that takes in 2 arguments.
How do I assign it to this function pointer?void (*func)(void* input, void* output)
I've been trying to do things like
void (*func)(void* input, void* output) = handle_request;
and tried thesebut I always get
warning: initi... |
As mentionied in your question if the function prototype returns int, then the pointer must match it. If the retuzrn type should be void, then the pointer is also to be void.
```
void handle_request(void* input, void* output)
{
}
int main(int argc, _TCHAR* argv[])
{
void (*func)(void* input, void* output) = hand... |
log.txt :
```
Hello world
world is not enough
to show our knowledge
```
cpp file :
```
#include <stdio.h>
#include <string.h>
int main()
{
char szLine[512+1]={0};
FILE *fp=fopen("log.txt", "r");
while(!feof(fp))
{
fscanf(fp, "%512[^\n]", szLine);
puts(szLine);
getchar();
}
ret... |
you can change your program like this:
```
#include <stdio.h>
#include <string.h>
int main()
{
char szLine[512+1]={0};
FILE *fp=fopen("log.txt", "r");
while(!feof(fp))
{
fgets(szLine,512,fp);
puts(szLine);
getchar();
}
return 0;
}
```
|
Can we allocate dynamic memory in bits? I knowmalloc()requires size of memory in bytes. Can we write a kernel module that allocates memory in bits? and this module should be called by user program to allocate memory in bits.If you guys say yes, I'll start working on it.
|
First of all you cannot allocate a bit (not even a byte in modern systems) because you can't address it. A memory address always gives data with the width of the data-bus (eg.64Bit).
If you want to emulate bitwise allocation @godel9 is right. I'd prefer
```
ptr = malloc((numbits % 8) + 1).
```
|
When I initialize variables, I do bellow.
```
int i = 0;
char *myText = NULL;
```
Then, haw can I initializestruct sockaddr_intype variables?
```
struct sockaddr_in addr = ?;
```
|
If you want to set all fields to zero in a declaration, no matter the structure, then do e.g.
```
struct some_struct var = { 0 };
```
|
When is thesetbuffunction useful (except the NULL value)?
I try to invent the examples, but I can't still.I understand howsetvbufcan be useful, but I don't understand withsetbuf.
|
Basically,setvbufis a newer API to the same logic assetbuf.setbufexists for compatibility with programs that were written beforesetvbufexisted.
So in other words, unless you're dealing with code that already usessetbuf, just ignore that it exists.
Reference:
Function:void setbuf (FILE *stream, char *buf)Ifbufis a ... |
If I run this code it will crash with a stack dump:
```
int * a = (int *) malloc(sizeof(int) * 10);
a++;
free(a);
```
Why doesn't it work?
Why does it need the pointer returned bymalloc()?
What records does the resource management system behind it keep?
Is it the length of the array? Is it the last cell's address? ... |
When memory is allocated, the size of allocated memory is stored in a block adjacent to the allocated block.
```
Why doesn't it work?
int * a = (int *) malloc(sizeof(int) * 10);
a++;
free(a);
```
This will not work because, free searchs for the adjacent block which has the size of allocated memory.
```
Why does it ... |
Need to make int from hex representation string like"0xFA"or better"FA". Need something likeatoi("FA"). Is there are any standard solutions for that?
|
Try to usestrtol():
```
strtol("FA", NULL, 16);
```
|
I have a functionint handle_request(server* server, int conn_fd);that takes in 2 arguments.
How do I assign it to this function pointer?void (*func)(void* input, void* output)
I've been trying to do things like
void (*func)(void* input, void* output) = handle_request;
and tried thesebut I always get
warning: initi... |
As mentionied in your question if the function prototype returns int, then the pointer must match it. If the retuzrn type should be void, then the pointer is also to be void.
```
void handle_request(void* input, void* output)
{
}
int main(int argc, _TCHAR* argv[])
{
void (*func)(void* input, void* output) = hand... |
log.txt :
```
Hello world
world is not enough
to show our knowledge
```
cpp file :
```
#include <stdio.h>
#include <string.h>
int main()
{
char szLine[512+1]={0};
FILE *fp=fopen("log.txt", "r");
while(!feof(fp))
{
fscanf(fp, "%512[^\n]", szLine);
puts(szLine);
getchar();
}
ret... |
you can change your program like this:
```
#include <stdio.h>
#include <string.h>
int main()
{
char szLine[512+1]={0};
FILE *fp=fopen("log.txt", "r");
while(!feof(fp))
{
fgets(szLine,512,fp);
puts(szLine);
getchar();
}
return 0;
}
```
|
Generally, is it a good idea to copy the source code of the PHP interpreter and use it on your C/C++ program, or something is wrong with this in terms of performance and reliability?
|
I would say that it is probably not useful in many cases because PHP handles data with its own Variant and you probably won't have those in your C/C++ program.
However, using the work they've done and implementing your own version is certainly a good idea but really only from elaborate PHP functions. For example, for... |
I'm trying to installclang completeto vim on my Mac, but when I open a .c file I get the following error:
```
Loading libclang failed, completion won't be available
Consider setting g:clang_library_path
```
Where do I set theg:clang_library_path? Is this something that goes in~/.vimrc?
My understanding is that I ne... |
Yes, you will need to put this in~/.vimrc.
I had a similar problem when I upgraded to Mavericks andadded some extra loggingto track it down at the time.
I put the following in$MYVIMRC:
```
let s:clang_library_path='/Library/Developer/CommandLineTools/usr/lib'
if isdirectory(s:clang_library_path)
let g:clang_lib... |
SomeCcode I am working in has anintset to -145. Depending on the format, the value returns as either0.00or-145. Take the following
```
int a = -145;
printf("%.2lf", a); // returns 0.00
printf("%.2ld", a); // returns -145
```
First question is how is it that the first line is returning0.00? Second question is how to... |
```
int a = -145;
printf("%.2lf", a); // returns 0.00
printf("%.2ld", a); // returns -145
```
Both function calls invoke undefined behavior. The correct conversion specifier to print anintisdnotlf(fordouble), notld(forlong).
|
I was wondering how do C programmers usually extract data from a string? I read a lot aboutstrtok, but I personally dislike the way the function works. Having to call it again withNULLas parameter seems odd to me. I once stumbled upon this little piece of code which I find pretty sleek :
```
sscanf(data, "%*[^=]%*c%[... |
IMHO thebest way is the most readable and understandable way.sscanfandstrtoktotally disqualify with your user/pw extraction from an URL.
Instead, look for the boundaries of the strings you are looking for (in an URL the slash, the at-sign, the colon, what have you) withstrchrandstrrchr, then memcpy from start to end ... |
I am trying to store data from a CSV file and ran into an access violation. The first image was shows how the memory is allocated, the second shows the problem area and the third is the spot in the csv where the problem occurred. Any help is appreciated.
|
It looks like the first loop that does the "pre-allocation" may have an error. The following allocation:
```
AllCurrentData[newLineCOunt].data = malloc(COLUMNS * sizeof(char));
```
should, I believe, be this:
```
AllCurrentData[newLineCOunt].data = malloc(COLUMNS * sizeof(char*));
```
|
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.Closed9 years ago.Improve this question
There are some problems in algorithms contests (or problems on e.g. SPOJ) with unknown number of test cases... |
OK, I got it:
```
while(scanf("%d", &n) != EOF) {
//...
}
```
|
I want to read some data using pyserial and then send the output to a C program using subprocess.
Here is my code (in progress):
```
from serial import Serial
import subprocess
process = subprocess.Popen("./print",stdin=subprocess.PIPE)
ser = Serial("/dev/ttyAMA0",9600,timeout=2)
while True:
if ser.inWaiting!=0:... |
Write tostdinofPopen. It's a file object.
```
process.stdin.write(ser.read())
```
|
SomeCcode I am working in has anintset to -145. Depending on the format, the value returns as either0.00or-145. Take the following
```
int a = -145;
printf("%.2lf", a); // returns 0.00
printf("%.2ld", a); // returns -145
```
First question is how is it that the first line is returning0.00? Second question is how to... |
```
int a = -145;
printf("%.2lf", a); // returns 0.00
printf("%.2ld", a); // returns -145
```
Both function calls invoke undefined behavior. The correct conversion specifier to print anintisdnotlf(fordouble), notld(forlong).
|
I was wondering how do C programmers usually extract data from a string? I read a lot aboutstrtok, but I personally dislike the way the function works. Having to call it again withNULLas parameter seems odd to me. I once stumbled upon this little piece of code which I find pretty sleek :
```
sscanf(data, "%*[^=]%*c%[... |
IMHO thebest way is the most readable and understandable way.sscanfandstrtoktotally disqualify with your user/pw extraction from an URL.
Instead, look for the boundaries of the strings you are looking for (in an URL the slash, the at-sign, the colon, what have you) withstrchrandstrrchr, then memcpy from start to end ... |
I am trying to store data from a CSV file and ran into an access violation. The first image was shows how the memory is allocated, the second shows the problem area and the third is the spot in the csv where the problem occurred. Any help is appreciated.
|
It looks like the first loop that does the "pre-allocation" may have an error. The following allocation:
```
AllCurrentData[newLineCOunt].data = malloc(COLUMNS * sizeof(char));
```
should, I believe, be this:
```
AllCurrentData[newLineCOunt].data = malloc(COLUMNS * sizeof(char*));
```
|
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.Closed9 years ago.Improve this question
There are some problems in algorithms contests (or problems on e.g. SPOJ) with unknown number of test cases... |
OK, I got it:
```
while(scanf("%d", &n) != EOF) {
//...
}
```
|
I want to read some data using pyserial and then send the output to a C program using subprocess.
Here is my code (in progress):
```
from serial import Serial
import subprocess
process = subprocess.Popen("./print",stdin=subprocess.PIPE)
ser = Serial("/dev/ttyAMA0",9600,timeout=2)
while True:
if ser.inWaiting!=0:... |
Write tostdinofPopen. It's a file object.
```
process.stdin.write(ser.read())
```
|
I have two unsigned long long numbersl1andl2.
I cast those numbers to float and save them asf1andf2.
```
f1 = (float) l1;
f2 = (float) l2;
```
Now considerl1>l2by some arbitrary amount, say 100.
Can there be a case such thatf1<f2?. (Heref1is converted froml1which is greater thanl2). If yes, can you please demonstr... |
Can there be a case such that f1 < f2
No: For any rounding mode, the conversion from integer to float is increasing. As long as you do not change the rounding mode between the conversion of l1 and that of l2, f1 and f2 are in the same order as l1 and l2 (they may be equal where l1 and l2 were different, though).
|
I think it may be called literal?
```
enum packet_structures{
PacketOne,
PacketTwo,
PacketThree
};
struct PacketOne{
unsigned int packet_id;
};
struct PacketTwo{
unsigned int packet_id;
};
struct PacketThree{
unsigned int packet_id;
};
```
And let's say I have a general packet.
```
struct PacketGenera... |
No you cannot. Enums are used for storing literals and not identifiers.
|
I need to know how to use the ICU4C version 52 C API to display the locale Currency Symbol and code. i.e. ($ - USD)
|
There is probably more than one way how to do this. Here is one, that I think should work (untested):
Get the number formatandformat the value using it:
```
UErrorCode success = U_ZERO_ERROR;
UNumberFormat *nf;
const char* myLocale = "fr_FR";
// get locale specific number format
nf = unum_open( UNUM_CURRENCY, m... |
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
You can't override operators in C, so you're out of luck I'm afraid.
Operatoroverloadingis for C++
|
I tried the following code to read number from a string to another string using regex
```
char des[25]={0};
char *src="1234567890";
sscanf(src, "%[[0-9]{1,5}]s", des);
sscanf(src, "%[^[0-9]{1,5}$]s", des);
```
I want only the first 5 digits. I'm not getting the desired output in either sscanf.
|
This will read the first 5 digits fromsrctodes
```
#include <stdio.h>
main() {
char des[25]={0};
char *src="1234567890";
sscanf(src, "%5s\0", des);
puts(des);
}
```
To read just numbers, replace thesscanfwith:
```
sscanf(src, "%5[0-9]", des);
```
|
Looking atffmpegexamples/muxing.c. When I encodemp3, in 2/3 casesgot_packetis zero and if it's zero for the last frame, I have noAVPacketto write to the file.
How to tellffmpegto flush the remaining data to a packet?
|
Call avcodec_encode_audio2() with null frame
when flushing an encoder that has the CODEC_CAP_DELAY capability set
|
I have declared the one static member inside the static method. like as follws:
```
static void temp1(param..){
static gint x,y ;
#TODO what you needed
values get changed here for x,y;
}
```
And I want to access this Two in other static method within the same file.
```
static void temp2... |
This might almost be what you want:
```
static gint x,y ;
static void temp1(param..){
/* TODO what you needed */
values get changed here for x,y;
}
static void temp2 ( param .......){
/* accessing the x,y */
}
```
x and y are globally accessible,but only within the file,just like your static procedures. I ... |
suppose I have a class with one of the method member name is close,
and inside the class, I'm using C function to open and close file
thus, I will have two completely different function with the same name, but one is C and another is C++.
Thus, when I call close, seems compiler is confused
```
s = socket(PF_INET, ... |
Your member function:
```
close(s)
```
Function in global namespace:
```
::close(s)
```
|
In linux kernel there's astruct XXwhich contains astruct list_head YY.
Now given a pointer to astruct XXobject, I want to find allXXstruct in the linked list. So I will go through the list_head struct, then find the corresponding parent struct.
But the second step here seems not applicable. So I'm not sure if it's p... |
You should use thecontainer_ofmacro (LDD3 chapter 3: The open method).
|
sqrt()andpow()functions ofmath.hlibrary inCare not defined forintegertypes but they don'tthrowanyerrorbut works fine forintegerarguments, how does this work?
|
Integers, when used in a context that expects floating point values, are implicitly converted to floating point values. And that's exactly what happens in your scenario, with functions that accept floating point parameters.
So, when you write:
```
#include <math.h>
....
int i;
double d = sqrt(i);
```
the integeriis... |
```
#include <stdio.h>
int _area(), _vol(), (*fnptr)();// declare the functions and the function pointer here
_area(a,b)
int a, b;
{
return (a*b); //The return value of _area after parameters are passed to it
}
_vol(fnptr,c) //engaging the function pointer as a parameter
int c;
{
fnptr = _area(); //initializi... |
```
**int k = (*fnptr)(8,9);** should be int **k = (*fnptr)(8,9);
```
|
Recently, I get a strange problem when i usedpopen(3)andpclose(3). Just like this:
```
//a.sh
#!/bin/bash
cat /etc/issue
sleep 3
//b.sh
#!/bin/bash
cat /etc/issue
echo "before sleep"
sleep 3
```
my C program:
```
#include <stdio.h>
int main(void) {
1: FILE *fl = popen("sh a.sh", "r");
2: FILE *fl = popen("sh... |
You should use theWEXITSTATUSmacro to get the real return code.
|
Following is the array of function pointers
```
(int) (*a[5]) (int);
int f1(int){};
...
```
is the following way of definition correct?
```
a = f1;
a + 1 = f2;
a + 2 = f3;
...
```
how do we call these functions?
```
*a(1) // is this correct???
*(a+1) (2)
```
|
```
#include <stdio.h>
int f1(int i) { return i; }
int f2(int i) { return i; }
int main() {
int (*a[5]) (int);
a[0] = f1;
a[1] = f2;
printf("%d\n", a[0](2));
printf("%d\n", a[1](5));
}
```
|
I need to read astructfrom a file but my code doesnt work.
How can I reach end of file
```
#include<stdio.h>
typedef struct elements {
char CallType;
int noofcparty,nooPartyBcalling,id,number_of_packets,roaming_option;
} Elements;
int main()
{
Elements e;
FILE *ptr_file;
char buf[1000];
p... |
i assume the file is in CSV (Comma-separated values).
example: b,100,200,800,45.
```
char line[200];
int max_size_line=200;
while(fgets(line,max_size_line,ptr_file)!=0)//read line by line until the end
{ sscanf(line,"%c,%d,%d,%d,%d,%d",&CallType,&noofcparty,&nooPartyBcalling,&id,&number_of_packets,&roaming_op... |
This is my code it is for my Sainsmart Arduino Uno.:
```
void buttonChange() {
if (digitalRead(button) == LOW) {
ltp2 = ltp;
ltp = millis();
if (number == 0 || ltp -= ltp2 > 500){
number += 1;
displayNumber();
}
}
}
```
I receive this error:
```
counter.ino: In function 'void button... |
You need some parentheses here:
```
if (number == 0 || ltp -= ltp2 > 500){
```
Change it to:
```
if (number == 0 || (ltp -= ltp2) > 500){
```
|
Ok, I need to use this for graphical programming, GUI, for cs 349 uwaterloo first assignment. I see random Xlib.h and Xutil.h files lying around on google search results. But no where does it say how I install or download Xlib from some website of something. I even tried to copy paste the Xlib.h onto a new files I cre... |
Simpliest way is to installcygwin- you'll get gcc + other tools (binutils, make, autotools) and X server and client libraries.
If C/C++ language is not a requirement I suggest to look atpythonorjavascriptclients - both are easy to install and don't require X runtime at all (they implement X11 wire protocol themselves... |
I am usingqsort()in my program to sort an array so i can usebsearch()to find a certain element.
I have theqsort()working correctly for the array and as my array is not full at time of sort it returns similar to this
before sorta[0] = value,
a[1] = value,
a[2] = NULL,
a[3] = NULL,
After Sorta[0] = ... |
No. There are multiple original arrays that would sort to the same output array. How would you know which one to choose?
If you want the original, then you'll need to make a copy, and sort that instead. (Or alternatively, create an array of pointers to the original elements, and sort that instead.)
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
you can use something like
```
(\w{3})([^\s])(#+)
```
|
```
#include <stdio.h>
int _area(), _vol(), (*fnptr)();// declare the functions and the function pointer here
_area(a,b)
int a, b;
{
return (a*b); //The return value of _area after parameters are passed to it
}
_vol(fnptr,c) //engaging the function pointer as a parameter
int c;
{
fnptr = _area(); //initializi... |
```
**int k = (*fnptr)(8,9);** should be int **k = (*fnptr)(8,9);
```
|
Recently, I get a strange problem when i usedpopen(3)andpclose(3). Just like this:
```
//a.sh
#!/bin/bash
cat /etc/issue
sleep 3
//b.sh
#!/bin/bash
cat /etc/issue
echo "before sleep"
sleep 3
```
my C program:
```
#include <stdio.h>
int main(void) {
1: FILE *fl = popen("sh a.sh", "r");
2: FILE *fl = popen("sh... |
You should use theWEXITSTATUSmacro to get the real return code.
|
Following is the array of function pointers
```
(int) (*a[5]) (int);
int f1(int){};
...
```
is the following way of definition correct?
```
a = f1;
a + 1 = f2;
a + 2 = f3;
...
```
how do we call these functions?
```
*a(1) // is this correct???
*(a+1) (2)
```
|
```
#include <stdio.h>
int f1(int i) { return i; }
int f2(int i) { return i; }
int main() {
int (*a[5]) (int);
a[0] = f1;
a[1] = f2;
printf("%d\n", a[0](2));
printf("%d\n", a[1](5));
}
```
|
Is it safe to doconnect()in blocking and after that, make the socket nonblock and do all nonblocking stuff for exampleepoll()/select()?
Does it cause to lack of some nonblocking operation that might I'm not considering?
|
It's perfectly safe so long as you make sure to check the return value offnctlfor an error. If not, then you could find your program halting unexpectedly.
|
The C99 standard gives the following definition for undefined behavior:
Behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements.
If you're working on a project that will never be required to be portable, that is, the compi... |
You can always look foradditionalguarantees from your hardware, OS and compiler vendors. "Undefined behaviour" leaves room for conforming implementations toaddguarantees and rules.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.