question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
My program executes with two arguments (put inargv) like below:
```
$ myProgram input output
```
How do I redirect allprintf(..)to the output file? I saw some suggestion about usingfflush(stdout)but I haven't used it before. Could anyone please show me an example?
|
If you are trying to redirect the output of your program then that can be done easily from the command line itself with out adding any additional code to your program. Just modify the command like this.
```
$ myProgram input output > example.txt
```
And if you want to append the output to the end of your output file then the command will be like this.
```
$ myProgram input output >> output
```
However in both cases nothing will be printed on the screen. The entire output of the program will be written in the file.
|
When I run this program and give laks as input I get laks as output plus one extra character.Also if I want to break the program as soon as a new line is entered i.e when I press enter I want the loop to discontinue but while statement does not seem to work.
```
# include <stdio.h>
# include <conio.h>
# include <ctype.h>
void main()
{
clrscr();
char person[5];
int i;
printf("enter person name \n");
for(i=0;i<5;i++)
{
scanf("%c",&person[i]);
//while(person[i]!='/n')
}
printf("%s",person);
getch();
}
```
|
You are not null terminating your string
So have
```
person[i] = '\0';
```
after the for loop.
I would have
```
char person[6] = "";
```
and later do a scan
|
suppose we got a void function include pointers:void order(double *smp, double *lgp)
when we call the function in main, it'sorder(&num1, &num2);
My question is when we define the function, it is "double *", which means its a value of the pointee. But when we call the function, it's "&num1", which is address of num1. How do they match up?
Is it the same as when we define pointer:double *p = &value;, just memorize it?
|
The*has different meanings based on where it's used. When in a variable definition it's not dereferencing the pointer (getting the value it's pointing to), it's saying that it is a pointer to the specfied type.
```
double *p = &value; // * is used to declare a pointer
printf("%f", *p); // * is used to get the value p is pointing to
int i = 2*3; // * is used as a multiplication operator
```
|
I have a function which the return type is double.
my return statement is
```
return sum / (double)(weight/100);
```
where sum is a double and weight is a int.
I wrote printf statements before the return to check the values
sum was 25.000 and (double)(weight/100) gave me .500but the return statement gave me "inf"
what is wrong with it ?
|
You are doing integer division betweenweightand 100. How about:
```
return 100 * sum / weight;
```
With this way you multiply 100 andsumand you get a double again sincesumis double. Then you divide the double result with the integer weight and you don't face the problem of integer division.
|
I am trying to implement an application like Skype. I am a little confused ifI will need a server to store the clients machine ip address, so they know how to locate each other. Or there is some more better technique so the clients machine can locate each other.
I was thinking at UDP multicast, hence the need for the ips. I will be using c# or C, so any code is welcome.
|
You need to store the IP addresses on the server, the computers will connect to the server. The server should associate states to IP addresses, like Active, Idle, Busy and stuff and the client should get the list of users accordingly. Messages should be sent to the server, which, in turn would forward them to the recipient(s).
|
This question already has answers here:Why is printf round floating point numbers up?(3 answers)Closed6 years ago.
```
#include<stdio.h>
void main()
{
float f = 2.5367;
printf("%3.3f",f);
}
```
Output is :2.537But how?
I think output should be2.536but the output is2.537.
|
Because 2.5367 is closer to 2.537. Delta from 2.536 is 0.007 while delta from 2.537 is just 0.003.
What you want to do is just deleting last character of its string representation and is wrong in math.
|
I just installed visual studio 2013 and gonna try a simple code. So I write this one:
```
int main(void) {
int length = 0;
int *array ;
printf("Enter the number of input: ");
scanf_s("%d", &length);
printf("%d", length);
for (int i = 0; i < length; i++){
scanf_s("%d", array + i);
}
printf("shoting ........ ");
getc;
return 0;
}
```
When I compile this code, it says local variable "array" is not initialized .
Am I missing something ?
|
The statementint *array ;declares a pointer. But you don't know where it points to. You can allocate some space using memory allocation functions likemalloc()etc. or make it point to some other pre-allocated space. As you are asking user for the input length (i.e. don't know your memory requirement at compile time), dynamic memory allocation likemalloc()would be the way to go.
|
suppose we got a void function include pointers:void order(double *smp, double *lgp)
when we call the function in main, it'sorder(&num1, &num2);
My question is when we define the function, it is "double *", which means its a value of the pointee. But when we call the function, it's "&num1", which is address of num1. How do they match up?
Is it the same as when we define pointer:double *p = &value;, just memorize it?
|
The*has different meanings based on where it's used. When in a variable definition it's not dereferencing the pointer (getting the value it's pointing to), it's saying that it is a pointer to the specfied type.
```
double *p = &value; // * is used to declare a pointer
printf("%f", *p); // * is used to get the value p is pointing to
int i = 2*3; // * is used as a multiplication operator
```
|
I have a function which the return type is double.
my return statement is
```
return sum / (double)(weight/100);
```
where sum is a double and weight is a int.
I wrote printf statements before the return to check the values
sum was 25.000 and (double)(weight/100) gave me .500but the return statement gave me "inf"
what is wrong with it ?
|
You are doing integer division betweenweightand 100. How about:
```
return 100 * sum / weight;
```
With this way you multiply 100 andsumand you get a double again sincesumis double. Then you divide the double result with the integer weight and you don't face the problem of integer division.
|
I really want to know right way of using header file.Belows are two ways of using header file which i think either of them is good way.notice : Destroy.c also use stdio.h, stdlib.h1.
2.
Please advice me. Thanks
|
Do not establish unnecessary dependencies!
There is no need to include any system headers intodestroy.h. If needed by code indestroy.cinclude them there.
Use header-guards.Only include what is needed where it is needed.Include system/library headers 1st. There are very rare conditions to not stick to this rule.Update on why inlcude system header 1st:The system headers declare the "frame-work" the program wants to use. So the program should "know" about this "frame-work"beforedeclaring its own stuff, as it might rely on what the system provides.The systen mostly never relies on what the program provides.Same for libraries, from the program's perspective, those are just additions to the system.
|
This question already has answers here:3 plus symbols between two variables (like a+++b) in C [duplicate](3 answers)Closed8 years ago.
```
int x = 2;
int y = 5;
int z = x +++ y;
printf("%d",z);
```
Both VC++ and GCC give 7 as output. My confusion here is, it could be x++ + y, or x + ++y. Is this defined?
|
In both C and C++, the principle of lexical analysis is, the longest sequence of characters that can form a valid token is taken as one (also known as "maximal munch"). Sox+++yis unambiguously parsed as(x++) + y.
2.4/(3.3)-- Otherwise, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token, even if that would cause further lexical analysis to fail.
|
This question already has answers here:Program didn't crash when buffer overflow(2 answers)Closed8 years ago.
I have this code for tests purposes
```
char *name;
name = (char *) malloc(21); // 20 char + '\0' byte
printf("Input your name: ");
gets(name);
printf("%s\n", name);
```
If I understood, malloc has allocated 21 bytes of some block memory and I casted to be a char pointer.
I inputed in my tests some big length strings (more than 21 char) but I did not get a buffer overflow.
What is the concept I am not grasping?
|
A buffer overflow occurs as soon as you write the 22nd character toname. That character is stored in a memory location beyond the storage allocated forname. The effect of overflowing the buffer isundefined behaviorwhich has a nasty habit of doing nothing notable especially in a simple application.
|
I have just started getting involved with GCC.
Lets say we have a text file written by vim labaled helloworld.c
Why would SWIM (someone who isn't me) compile it with
gcc helloworld.cin comparison togcc -c helloworld.cand thengcc -o helloWorld helloworld.o?
|
For one single file, there is no use.
But if you compile a larger project, you may not want to recompile all files, if you only changed one for instance. And thus, gain compile time.
Using intermediate.ofiles lets you only recompile what needs to be recompiled, and link the final binary with all those objects files.
Another usecase is if you want to use a custom link script, for instance to choose the location of your sections or code. Then you need to get the actual code from.ofiles.
|
if I have something like
```
struct Node *root;
struct Node *q;
root = malloc( sizeof(struct Node));
q = root;
free(q);
```
is the node q is pointing to freed?? or would I have to passrootto thefreefunction?
|
Bothrootandqhave the same value, that is to say, they point to the same memory location. After the call tofree(q), both of them are dangling pointers because the thing they both point to has been freed but they still point to that location.
To de-reference either would invoke undefined behaviour. This includes callingfreeon either of them.
|
I'm making an archive file, which I am then trying to include in my code, but when I try to#include 'libutils.h', I get an error:
```
src/indexer.h:8:10: fatal error: 'libutils.h' file not found
#include "libutils.h"
```
my make command is:
```
gcc -g -std=c11 -Wall -pedantic -o indexer src/indexer.c -L. -lutils.a
```
my file structure is:
```
Indexer/
libsutil.a obj/ src/ makefile
obj/
web.o list.o hashtable.o //These are the files in the archive file
src/
web.c web.h list.c list.h hashtable.c hashtable.h indexer.c indexer.h
```
|
You don't need toincludeanything, remove the
```
#include "libutils.h"
```
from the.cfile, and your compilation command will be
```
gcc -g -std=c11 -Wall -pedantic -o indexer src/indexer.c -L. -lutils
```
|
Here is the structure
```
typedef struct PSetting
{
unsigned char Level;
unsigned int Mall;
unsigned int Many;
WCHAR* Name; // optional
} PSetting;
PSetting p;
p.Name = L"NewName";
p.Level = 5;
p.Mall= 0;
p.Mall= 0;
```
I am required to create a member for the structure and pass it to this API:
```
PSettingAPI(proxy, PSetting **p, NULL)
```
However, I have this error when I do so:
```
no suitable conversion function from "PSetting" to "Psetting **" exists.
```
|
You are trying to pass an object of typePSettingdirectly. The API function expects a pointer to a pointer toPSetting(PSetting **p) as the second parameter.
```
PSetting p;
PSetting* pointerToPSetting = &p;
PSetting** pointerToPointerToPSetting = &pointerToPSetting;
```
Now pass pointerToPointerToPSetting to the function. Note that this could be a two-dimensional array ofPSetting.
|
For example:
```
int main(int argc, char *argv[]) {
if (strncmp(argv[1], "password")) {
printf("Incorrect password\n");
}
return 0;
}
```
Can I disassemble the binary for this compiled program and see the string "password" somewhere in the binary or is it only visible during run-time?
|
Typically, yes. Moreover, you don't need to "disassemble" anything. Most of the time you will be able to see it right in the compiled binary by opening it in a text or hex editor.
|
I have a text file where each line is terminated by a "\n". Like so
```
0000
0000
0000
0000
```
Now, a file initially starts like above but a line can be overwritten with another line of variable length. I am usingfseek()in order to set the position indicator of the stream. I have no problems moving to a line and replacing for example0000with1111.
Now lets say I want to replace the first line with1111 1111. I do the following
```
char *str = "1111 1111\n";
fwrite(str, 1, strlen(str), file);
```
This deletes line 2 and 1 byte from line 3 like so
```
1111 1111
000
0000
```
What is the cause of this?
|
If you think of your file like:
"0000\n0000\n0000\n0000\n"
It will be easier to understand that when you overwrite first line you are overwriting first n-number of chars really.
So that is why your second line disappears.
|
i'm trying to take the first element of a linked list and move it to the last position. I did that using this code :
```
pend=pstart;
while(pend->next != NULL) // go to the last element
{
pend = pend->next;
}
pend->next=pstart;
pend=pstart;
pstart=pstart->next;
pend->next=NULL;
```
but it seems that i might be missing something, because i'm not getting the result i want. So, my question is : is this code correct ? if not please help me fix it. Thank you.
|
Your code is correct. You have messed up somewhere else.
The best way to solve such problems is to draw the linked list using boxes (nodes) and arrows (links).
|
I am usinguthash.hfor hash implementation in C. I am using the hash-table for a basic word count exercise. I have a file containing words and I have to count frequency of each word. The implementation ofuthash.hrequires me to generate an integer id for each entry, and I wanted to calculate a unique integer corresponding to each string. I tried using md5 hash algorithm, but it generates strings with digits and alphabets, so its no use.Can anybody suggest me such an algorithm.
|
Use Robert Sedgewick'salgorithmfor hashing
```
unsigned int GenerateHash(char* str, unsigned int len)
{
unsigned int result = 0;
unsigned int b = 378551;
unsigned int a = 63689;
unsigned int i = 0;
for(i=0; i<len; str++, i++)
{
result = result*a + (*str);
a = a*b;
}
return result;
}
```
|
I am attempting to put a particular device into suspended mode, and have been unable to find a way to do this.
I see in the kernel that a suspend command can be defined, but what is the user space analog to it, if there is one?
In this case, it is to allow me to mask an interrupt in a touchscreen controller before its power is removed.
edited to add additional info:
Additional information: This is for an embedded device, using linux kernel 2.6
|
the typical sequence is to send a command to the device to put it into 'suspend' mode, then close the open file descriptor to that device.
|
I have the following C Code
```
#include <stdio.h>
int main(void){
char c[] = "ABC"
printf("%s ", c);
c[1] = 'B';
printf("%s", c);
return 0;
}
```
The output I want isABC BBCbut the output I get isABC ABC. How can I replace the first character in an String / char array?
|
Indexing in C arrays start from0. So you have to replacec[1] = 'B'withc[0] = 'B'.
Also, see similar question from today:Smiles in output C++- I've put a more detailed description there :)
|
I have the following program:
```
#include <stdio.h>
#include <stdlib.h>
char* getStr(int length) {
char* chars = malloc(length + 1);
int i;
for(i = 0; i < length; i++)
chars[i] = 'X';
chars[i] = '\0';
// no call to free()
return chars;
}
int main(int argc, char** argv) {
char* str;
str = getStr(10);
printf("%s\n", str);
free(str);
return EXIT_SUCCESS;
}
```
It prints 10X's, as I expected.
Would it behave like this on any platform with any compiler?
Is the memory still malloced aftergetStr()returns?
(I don't want to pass the pointer as argument :D)
|
Yes, the code looks valid and the behavior should be reliable with any C compiler.
And, yes, the memory is still allocated aftergetStr()returns. So the call tofree()is also correct.
Don't forget to check ifmalloc()returnsNULL, in the event there is insufficient memory.
|
I want to be able to callrecv()without having to block, so I want to make it non-blocking, but I do not want it to be non blocking when sending data. So can a socket be made non-blocking only for therecv()function, or does the blocking/non-blocking mode affects all of the socket functions?
|
For windows, you can useioctlsocket()to set the socket in non-blocking mode. Unfortunately these settings apply to all operations on the socket. So for your case you'll have to switch it between the receivings and the sendings.
For the records:For linux, you could have used theMSG_DONTWAITflag in therecv()call arguments. The single call will then be non blocking.
|
If I do
```
sum2=(((p/2)%m)*((p+1)%m))%m;
sum2=(sum2 * (p%m))%m;
```
I get the right answer but if I do
```
sum2=((p%m)*(((p/2)%m)*((p+1)%m))%m)%m;
```
I get the wrong answer. What is the reason?
All variables are of unsigned long long integer type and m<=10000000.
PS:Question updated because of typo.
|
sum2=((p%m)*((((p/2)%m)*((p+1)%m))%m))%m;This should work for you.There was a problem with parentheses.
|
When i used this code to find the volume of cylinder i got the error
'invalid operands to binary ^ have( 'float' and 'ínt' ) can somebody explain me why i get this error.
```
float r,vol;
printf("Enter the parameters to be calculated:\n");
scanf("%f",&r);
vol = (4*3.14*(r^3))/3;
printf("The Vol of the cylinder is : %f\n",vol);
return 0;
```
|
You cant use^for power inC.This is not the power it isbitwise xor.USe this instead-
```
#include <math.h>
#include<stdio.h>
int main()
{
float r,vol;
printf("Enter the parameters to be calculated:\n");
scanf("%f",&r);
vol = (4*3.14*(pow(r,3)))/3;
printf("The Vol of the cylinder is : %f\n",vol);
return 0;
}
```
|
I'm reading the code of a project and I found a part that I couldn't understand:
```
void (*pEpInt_OUT[7])(void) =
{
EP1_OUT_Callback,
EP2_OUT_Callback,
EP3_OUT_Callback,
EP4_OUT_Callback,
EP5_OUT_Callback,
EP6_OUT_Callback,
EP7_OUT_Callback,
};
```
Is it a function? If yes, what is its name? Or is it something else?
|
It is an array of 7 function pointers. Each of the entries points to a function which takes void and returns void;void EP1_OUT_Callback( void ).
|
My compiler (DSP SHARC) is very picky. When I build with remarks I get this error:
```
[cc1123] foo.c:1511 {D} remark: comparison of unsigned type
with signed type
while (taille > 0)
```
Two solutions:
The compiler is right and I should writesize_t taille;
...
while(taille > (size_t)0)The compiler is stupid and I should ignore this remarkAnother solution that may involve ISO or MISRA standards
What should I do with this remark?
EDIT
Actually I might better write this example like
```
while(taille) {...}
```
But, this is not related to my initial question
|
IMO, the compiler is weak or at least pedantic. To quiet this unneeded warning, use:
```
while (taille > 0u)
```
BTW: Love the "Two solutions: 1. 2.and3."
Late credit: Now see@Wintermutecommented similarly on this earlier than myself.
|
```
int sum(int n)
{
if(n==0)
return n;
else
return n+sum(n-1); /*self call to function sum() */
}
```
Can anyone please explain to me how it sums up with the previous value each time it enters the sum(int n) function. I mean, in 'return n+sum(n-1)', how does the 'n+' part gets into the next cycle when sum(n-1) is invoked?
|
```
n+sum(n-1)
```
Let's say n=4
```
4 + sum(3)
4 + 3 + sum(2)
4 + 3 + 2 + sum(1)
4 + 3 + 2 + 1 + sum(0)
4 + 3 + 2 + 1 + 0 = 10
```
|
I came across this line of code in legacy code:
```
#define func(x,y) if(strcmp(x,#y)==0)
```
Anyone have an idea of the purpose for the#symbol precedingy?
|
as mentioned in the comments, this seems likestringificationin a c macro.
here is a little example that uses your sample code:
```
#define doif(x, y) \
if(strcmp(x,#y)==0) { \
printf("doing! %s\n",x); \
}\
else { \
printf("not doing!\n"); \
}
int main()
{
char x[] = "test";
doif (x, test);
doif (x, something);
return 0;
}
```
the stringification operator actually pastesyvariable as a string before the compilation stage
|
When I am calling the c read function the perror function tells me that it is an Undefined error: 0.
This is the snippet of the code that it is exiting due to error:
```
if( read(fd,&head_data->npts,sizeof(int)) <= 0 )
{
perror("File read error in reading data\n");
exit(1);
}
```
head_data is a struct and npts is an int member of that struct.
I've looked through the opengroup and the linux man pages but could not find any information on the undefined error. I dont know if it makes any difference but I am compiling and running on Mac OS 10.9.5.
|
From theread(2)man page:
If successful, the number of bytes actually read is returned. Upon reading end-of-file, zero is returned. Otherwise, a -1 is returned and the global variable errno is set to indicate the error.
So you just read 0 bytes - meaning end of file.
|
How would I go about making an enum into a string using a case such as
enum {Ace,....King} face;
to a case that would convert it to say "Ace" rather than a 0 or 1.
|
```
char const* faceToString(face f)
{
switch (f)
{
case Ace:
return "Ace";
case Two:
return "Two";
...
case King:
return "King"
}
}
```
|
Why does the following program compile withgcc, ...
```
#include<stdio.h>
#include<math.h>
void foo(double x) {
printf("%f", sin(2));
}
int main() {
foo(1);
}
```
... while this other program doesn't?
```
#include<stdio.h>
#include<math.h>
void foo(double x) {
printf("%f", sin(x));
}
int main() {
foo(1);
}
```
It gives the following error message:
```
/tmp/ccVT7jlb.o: nella funzione "foo":
fun.c:(.text+0x1b): riferimento non definito a "sin"
collect2: error: ld returned 1 exit status*
```
|
You need to link tolibm.solike this
```
gcc -Wall -Wextra -Werror source.c -o executable -lm
```
see the-lm
|
Every Ruby object is of typeVALUEin C. How do I print it in a readable way?
Any other tips concerning debugging of Ruby C extensions are welcome.
|
You can callpon Ruby objects with the C functionrb_p. For example:
```
VALUE empty_array = rb_ary_new();
rb_p(empty_array); // prints out "[]"
```
|
This question already has answers here:Split string with delimiters in C(25 answers)Closed8 years ago.
I have a string"some random data/1000". Now, I want the number(1000) alone without storing the first part anywhere. I should directly get the last part i.e the number. How to do this in C language?
Here'/'is delimiter.
|
If you're certain there's only one delimiter, I would simply usestrrchr()1to find it. Then either directly convert the number to integer (using e.g.strtol()) or allocate a new string and copy the trailing part of the first in there.
1Please note that middler, it's searchingbackwards.
|
This question already has answers here:Structure padding and packing(11 answers)Closed8 years ago.
Can anyone please explain me this?
Apparently there is a space containing two bytes that is beeing unused after field a. Can someone tell my why is this happening and is there a way to "turn off" such behavior? I really need it to work normally.
|
This IS "working normally". Your compiler aligns the second memberbto optimize for speed. The default alignment for anunsigned inton your platform is 4 bytes, so padding bytes are added aftera.
To turn this off, you can usepragmas depending on your compiler, but don't call this "abnormal behavior".
|
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.Closed8 years ago.Improve this question
```
#include<stdio.h>
#include<string.h>
int main()
{
char source[]="Sayonara";
char target[8];
strcpy(target,source);
printf("source string= %s\n",source);
printf("target string= %s\n",target);
return 0;
}
```
OUTPUT:- source string=target string=Sayonara
|
The length ofsourceis 9, because it has a null-terminator\0. You are copying beyond the bounds oftarget, which invokesundefined behaviour.
You need to maketargetthe same length or longer to ensure it is null-terminated after the copy and no out of bounds access occurs.
```
char source[]="Sayonara";
char target[9];
strcpy(target,source);
```
|
What is the difference between sending a string directly than sending a pointer to a string to a function?
For example:
```
void foo(char * a){//suppose foo reads and/or writes to the passed string
...
}
int main(){
foo("asdf");//what is the difference between this
char a[]="asdf";
foo(a);//and this?
}
```
With the first I'm getting all sorts of access violation errors while with the second I don't, so what is the difference between the two?
|
In the first case, you pass a string literal to the function. String literals are immutable meaning that you cannot change any part of it. This, is astaticarray stored in read-only memory segment. Attempting to alter this string results inUndefined Behavior.
In the second case, you construct an array, initialize it with"asdf"and pass it to the function. In this case, the characters in the array can be modified.
Seequestion 1.32 of the comp.lang.FAQfor more info.
|
I am trying to setup Balde (http://balde.io).
I referredtheir docs, downloaded the latest stable release, installed fastcgi dev kit and apache with mod fcgi.
Then I built balde.
Then I tried the example and compiled it withgcc hello.c `pkg-config --libs --cflags balde` -o hello
Then I set the following site-available:
```
<VirtualHost *:80>
ServerName https://${C9_HOSTNAME}
ScriptAlias / /home/ubuntu/workspace/try/hello/
<Directory /path/to>
Order allow,deny
Allow from all
Options ExecCGI
SetHandler fcgid-script
</Directory>
</VirtualHost>
```
Also the permission ofhellois 777 (temporarily)
Yet I get 403 Forbidden when I visithttps://balde-meghprkh.c9.io/. Can you tell me where am I wrong?
|
You must change<Directory /path/to>to<Directory /home/ubuntu/workspace/try>. This should fix your issue
|
I want to know if there is any way to escape macro name and actually show the real name :
```
#define BUFF_SIZE 500
printf("%d", BUFF_SIZE);
```
Is it possible to not expandBUFF_SIZEhere without removing the define?
|
Stringification:
Sometimes you may want to convert a macro argument into a string
constant. Parameters are not replaced inside string constants, but you
can use the ‘#’ preprocessing operator instead. When a macro parameter
is used with a leading ‘#’, the preprocessor replaces it with the
literal text of the actual argument, converted to a string constant.
Unlike normal parameter replacement, the argument is not
macro-expanded first. This is called stringification.
```
#include <stdio.h>
#define BUFF_SIZE 500
#define STR(x) #x
int main(void)
{
printf("%s\n", STR(BUFF_SIZE));
return 0;
}
```
Note that you can't print a string with%d, use%s.
|
What are the different syntax of c structure? How do decode this :
```
struct p {
char a[1];
int b;
int *a;
int value;
};
struct p q[] = {
{"a", 0, &b, C},
{"J", 0, &k, l}
};
```
I found a another discussionherebut didn't encounter this type.
|
qis the array of structure of typep.
phas following elements:
char pointerany type (int,char,short etc. even a pointer is possible)pointer to any typeshould be a constant
The syntax is actually initializingq[0]andq[1]
|
I am learning pointers.
```
int main() {
int a = 2;
cal(&a);
}
void cal(int* a) {
//Here:
//What does the value of a mean?
//What does the value of &a mean?
}
```
As you see above, inmain(), I passed the address of a to functioncal(int* a).
I am wondering what is the meaning of valueaand&aincal(int*)?
Isaincal(int*)represents the address ofainmain()?
Is&aincal(int*)represents only the address which points to the address ofainmain()?
|
What does the value of &a mean?
Take the address ofa. This is done by applying the address-operator&to theintvariablea.
What does the value of a mean?
Insidecal()arepresents the address of anintas having been passed when callingcal().
|
In C, on any micro controller when we initialize a float variable to 0
```
float var = 0.0f;
```
Is 'var' exactly equal to zero or does it depend on the min & max float resolution of the processor?
|
Happily, zero is actually zero no matter what: IEEE-754 (the usual standard for floats) sets aside the all-zeroes bit pattern as meaning identically zero.
|
I have files something like this:
file1_a_etc.txt,file1_b_etc.txtfile2_a_z.txtfile2_b_z.txt
I want to get the size of files with "a" i.e. file2_a_z.txt & file1_a_etc.txt
I have got a large number of files this way, so cant specify each name individually.
I am a beginner at C.I know how to read the size of a single file. And I am working on windows.
```
#include <stdio.h>
#include <sys/stat.h> // For struct stat and stat()
struct stat attr;
void main()
{
if(stat("filename.txt", &attr) == 0)
{
float x;
x=(attr.st_size)/1048576.0; //1MB=1048576 bytes
printf("Filesize: %.2f MB", x);
}
else
{
// couldn't open the file
printf("Couldn't get file attributes...");
}
}
```
|
For Windows console there is function_findfirst. For first parameter put*a*.txt.
|
So I'm unable to get printf to output anything while being in nested for loops
for example:
```
printf("hello ");
for(int i =0; i< 4; i++)
for(int j = 0; j < 5; j++)
printf("world");
```
This would only out the word hello without being able to output the word "world". I tried fflush(stdout), but it seem that the command was unable to solve the problem. I'm using a Mac. Can some one give a suggestion on how to fix this?
|
The problem with your code provided in the linklinkis that
```
for( i = 0; i > m; i++)
```
The condition you have used isi > mwhen it should have beeni < m.
|
I have#define MAX_PERSONS = 20;after my headers.
I'm trying to do an if statement, where I compare an int p to MAX_PERSONS
```
int checkString(char string[]){
int p = strlen(string);
printf("\n\t\t%s is %d characters long\n", string, p);
if (p < MAX_PERSONS){
return 1;
}
if (p > 20){
return 0;
}
}
```
I receive this errormenu.c:80:10: error: expected expression before ‘=’ token.
However, if I switch MAX_PERSONS to 20 like how I did with the second if statement, it works.
I was wondering if someone could let me know why this is happening and how I can use the constant value. Thanks!
|
Replace
```
#define MAX_PERSONS = 20;
```
with
```
#define MAX_PERSONS 20
```
#defineis a pr-processor directive which replacesMAX_PERSONSwith the followed text before compilation.
|
This question already has answers here:How to generate a random int in C?(32 answers)Closed8 years ago.
I'm writing a code that will return a random number between 5 and 20, and i'm running into a problem where it will always produce the same number over again and i can't seem to solve it.
```
#include <stdlib.h>
#include <stdio.h>
int random = 0;
int randomnumbergen() {
srand(12345);
random = rand() % (20 - 15) + 15;
return random;
}
```
|
First, you'll want to call srand() at the beginning of your program one time.
Next, you'll want to replace
```
srand(12345);
```
with
```
srand (time(NULL));
```
|
trying to get this loop to run but it just has the cursor blinking. I am new to programing. Can you please help?
```
#include<stdio.h>
int main()
{
int i;
i = 0
while (i <= 5);
{
printf ( "i = %d" );
i += 1;
}
}
```
|
Notice how there was also a missing semicolon afteri = 0, this will throw an error and prevent your program from continuing. Also, remove the semicolon after your while loop, it will not run the code inside with it present (And will just sit idle after skipping it). Your program should look like:
```
#include<stdio.h>
int main()
{
int i;
i = 0;
while (i <= 5)
{
printf ( "i = %d" );
i += 1;
}
}
```
|
Hello i'm trying to use an old legacy C library that uses buffers (unsigned char []) to transform the data. The main issue here is that I couldn't find a way to transform a String to a CUnsignedChar and then be able to alloc that buffer to a UnsafeMutablePointer
|
If you want to convert a Swift string to an immutable C string to pass to a C function, try this:
```
let s: String = "hello, world!"
s.nulTerminatedUTF8.withUnsafeBufferPointer { p -> Void in
puts(UnsafePointer<Int8>(p.baseAddress))
Void()
}
```
You may need to useUnsafePointer<UInt8>if your function takes anunsigned char *.
|
```
int myFunc(int a, int b, int c, int d[][c]) {
//code
}
```
I've tried this:
```
int myFunc(int, int, int, int *);
```
And this:
```
int myFunc(int, int, int, int *[int]);
```
And this:
```
int myFunc(int, int, int, int **);
```
But none of them seem to work. I think I'm having trouble pinning down the last parameter's type. Any help would be greatly appreciated.
|
Now try this
```
int myFunc(int a, int b, int c, int (*)[c]);
```
|
I saw some C code, and I'm not sure what it does.
```
*dest++ = *src++;
```
I do not have this code in a context unfortunately (I was reading an article), but I assume src and dest were defined earlier. So I know an asterisk on a variable definition means a pointer to the memory location of that variable. But what does the asterisk mean in the context of a computation?
|
Here is a very common context*for an operation like this:
```
void strcpy(char *dest, const char *src) {
while (*dest++ = *src++)
;
}
```
This is an implementation of C string copying algorithm. An asterisk in each expression meanspointer dereference, i.e. obtaining the value stored at the location pointed to by the pointer.
*Second edition ofK&R, page 88.
|
We develop code for embedded PowerPC architectures.
Our compiler supports something called asm Macros.
Here an excerpt from the handbook:
asm Macro SyntaxAn asm macro definition looks much like a function definition, including a return type and parameter list, and function body.The syntax is:asm [volatile] [return-type] macro-name ( [ parameter-list ] )
{
% storage-mode-list (must start in column 1)
! register-list (“!” must be first non-whitespace)
asm-code
} (must start in column 1
Is this standard C? My compiler does not list this as an extension in his handbook.
Clarification after first answer:
I'm aware the part withen{ }is not defined by standard C. I meant the function like construct afterasmand before the closing).
|
No, it is not standard C. Anything architecture-specific, like assembly code, is going to be an implementation-specific extension just about by definition.
|
The following write() is received by the client correctly:
```
char *foo = "ABC";
write(sock, foo, strlen(foo));
```
But when I extend the foo string to 4 or 5 characters, write() will pad the string with garbage until it has 6 characters. Example of a write that gets extra padding:
```
char *foo = "ABCD";
write(sock, foo, strlen(foo));
```
Anybody know why this happens?
|
I suspect as apparently all the others, that you are reading the characters on the other side of the connection and printing them withprintf()which expects anulterminated sequence of bytes, i.e. a string, so either write thenulbyte like this
```
write(sock, foo, 1 + strlen(foo));
```
or where you recieve it, do it like this
```
int count;
char array[LARGER_THAN_POSSIBLE_COUNT];
count = read(sock, array, sizeof(array));
if (count > 0)
fwrite(array, 1, count, stdout);
fprintf(stdout, "\n");
```
|
I am making an interface using GTK and C. I've put an entry text in my interface, the user will type only numbers. And I need to get the entered numbers to use them later. However, using the functiongtk_entry_get_textwill stock the entered text in aconstgcharvariable. How can I get what the user typed as a number?
The code to get the text is:
```
static void ok_clicked(GtkWidget *widget, GtkWidget *entry){
const gchar *get_text;
get_text = gtk_entry_get_text(GTK_ENTRY(entry));
printf("entry contents: %s\n",get_text); }
```
|
You could useguint64 g_ascii_strtoll (const gchar *nptr,gchar **endptr,guint base);which converts a string to a gint64 value. This function behaves like the standard strtoll() function does in the C locale. For double you could use
```
gdouble g_ascii_strtod (const gchar *nptr, gchar **endptr); I hope this helps.
```
|
Is there any way to Count number of arguments passed toscanf()in C ? Specially, while assigningintarrays throughscanf().
Example:
```
int array[1000], i;
for(i=0;i<1000;i++)
scanf("%d",&array[i]);
```
I need to count how many values are inserted by user
|
I don't think there's a built in way to do this, but why not just create a counter that increments when scanf returns successfully and break the loop otherwise?
```
int scanf_counter = 0;
int array[1000], i;
for(i=0;i<1000;i++) {
if(scanf("%d",&array[i] > 0) {
scanf_counter++;
} else {
break;
}
}
```
Although I'm not sure I understand your question exactly because you could always just find the size of the array by doing this
```
int size = sizeof(array)/sizeof(array[0])
```
|
This question already has answers here:How to generate a random int in C?(32 answers)Closed8 years ago.
I'm writing a code that will return a random number between 5 and 20, and i'm running into a problem where it will always produce the same number over again and i can't seem to solve it.
```
#include <stdlib.h>
#include <stdio.h>
int random = 0;
int randomnumbergen() {
srand(12345);
random = rand() % (20 - 15) + 15;
return random;
}
```
|
First, you'll want to call srand() at the beginning of your program one time.
Next, you'll want to replace
```
srand(12345);
```
with
```
srand (time(NULL));
```
|
trying to get this loop to run but it just has the cursor blinking. I am new to programing. Can you please help?
```
#include<stdio.h>
int main()
{
int i;
i = 0
while (i <= 5);
{
printf ( "i = %d" );
i += 1;
}
}
```
|
Notice how there was also a missing semicolon afteri = 0, this will throw an error and prevent your program from continuing. Also, remove the semicolon after your while loop, it will not run the code inside with it present (And will just sit idle after skipping it). Your program should look like:
```
#include<stdio.h>
int main()
{
int i;
i = 0;
while (i <= 5)
{
printf ( "i = %d" );
i += 1;
}
}
```
|
Hello i'm trying to use an old legacy C library that uses buffers (unsigned char []) to transform the data. The main issue here is that I couldn't find a way to transform a String to a CUnsignedChar and then be able to alloc that buffer to a UnsafeMutablePointer
|
If you want to convert a Swift string to an immutable C string to pass to a C function, try this:
```
let s: String = "hello, world!"
s.nulTerminatedUTF8.withUnsafeBufferPointer { p -> Void in
puts(UnsafePointer<Int8>(p.baseAddress))
Void()
}
```
You may need to useUnsafePointer<UInt8>if your function takes anunsigned char *.
|
can we access the bits shifted by bit shifting operators(<<, >>) in C, C++?
For example:
23>>1
can we access the last bit shifted(1 in this case)?
|
No, the shift operators only give the value after shifting. You'll need to do other bitwise operations to extract the bits that are shifted out of the value; for example:
```
unsigned all_lost = value & ((1 << shift)-1); // all bits to be removed by shift
unsigned last_lost = (value >> (shift-1)) & 1; // last bit to be removed by shift
unsigned remaining = value >> shift; // lose those bits
```
|
Supposing I have a code like this:
```
#include <stdio.h>
#include <stdint.h>
int main(int argc, char *argv[]) {
typedef struct{
uint16_t x : 9;
uint8_t y : 7;
} z;
printf("sizeof(z) = %lu\n",sizeof(z));
}
```
I have different results for clang on Mac (2) and someone told me on Windows it returned (3). Not sure if I understand it well, but I see that while first compiler compresses the struct to 9+7 = 16 bits, the other uses 16 bits of uint16_t and 8 of uint8_t. Could you advise?
|
Not sure if I understand it well, but I see that while first compiler compresses the struct to 9+7 = 16 bits, the other uses 16 bits of uint16_t and 8 of uint8_t. Could you advise?
The first thing to remember about bit-field is this phrase from K&R, 2nd:
(6.9 Bit-fields) "Almost everything about fields is implementation-dependent."
It includes padding, alignment and bit endianness.
|
It´s possible using Macros in ironPython?
I have a dll with macros in C and I would like access it from IronPython.
Any ideas?
Thank you.
|
You can't access C macros from a DLL - they're handled by the C preprocessor, so they never reach the compiler and thus can't part of the DLL. You can access functions exported from the DLL in IronPython using the standard Pythonctypesmodule.
|
I need to convert arguments given at command line such as: $ myprogram hello world
and the words need to be printed in CAPS. I am able to to do everything except access the double pointer array to make the changes with toupper()
```
static char **duplicateArgs(int argc, char **argv)
{
char **copy = malloc(argc * sizeof (*argv));
if(copy == NULL){
perror("malloc returned NULL");
exit(1);
}
int i;
for(i = 0; i<argc; i++){
copy[i] = argv[i];
}
char **temp;
temp = ©[1];
*temp = toupper(copy[1]);
return copy;
}
```
|
```
*temp = toupper(copy[1]);
```
toupperconverts a single character, if you want to convert an entire string:
```
char *temp = copy[1]; /* You don't need a double pointer */
size_t len = strlen(temp);
for (size_t i = 0; i < len; i++) {
temp[i] = toupper(temp[i]);
}
```
|
can we access the bits shifted by bit shifting operators(<<, >>) in C, C++?
For example:
23>>1
can we access the last bit shifted(1 in this case)?
|
No, the shift operators only give the value after shifting. You'll need to do other bitwise operations to extract the bits that are shifted out of the value; for example:
```
unsigned all_lost = value & ((1 << shift)-1); // all bits to be removed by shift
unsigned last_lost = (value >> (shift-1)) & 1; // last bit to be removed by shift
unsigned remaining = value >> shift; // lose those bits
```
|
Supposing I have a code like this:
```
#include <stdio.h>
#include <stdint.h>
int main(int argc, char *argv[]) {
typedef struct{
uint16_t x : 9;
uint8_t y : 7;
} z;
printf("sizeof(z) = %lu\n",sizeof(z));
}
```
I have different results for clang on Mac (2) and someone told me on Windows it returned (3). Not sure if I understand it well, but I see that while first compiler compresses the struct to 9+7 = 16 bits, the other uses 16 bits of uint16_t and 8 of uint8_t. Could you advise?
|
Not sure if I understand it well, but I see that while first compiler compresses the struct to 9+7 = 16 bits, the other uses 16 bits of uint16_t and 8 of uint8_t. Could you advise?
The first thing to remember about bit-field is this phrase from K&R, 2nd:
(6.9 Bit-fields) "Almost everything about fields is implementation-dependent."
It includes padding, alignment and bit endianness.
|
It´s possible using Macros in ironPython?
I have a dll with macros in C and I would like access it from IronPython.
Any ideas?
Thank you.
|
You can't access C macros from a DLL - they're handled by the C preprocessor, so they never reach the compiler and thus can't part of the DLL. You can access functions exported from the DLL in IronPython using the standard Pythonctypesmodule.
|
I need to convert arguments given at command line such as: $ myprogram hello world
and the words need to be printed in CAPS. I am able to to do everything except access the double pointer array to make the changes with toupper()
```
static char **duplicateArgs(int argc, char **argv)
{
char **copy = malloc(argc * sizeof (*argv));
if(copy == NULL){
perror("malloc returned NULL");
exit(1);
}
int i;
for(i = 0; i<argc; i++){
copy[i] = argv[i];
}
char **temp;
temp = ©[1];
*temp = toupper(copy[1]);
return copy;
}
```
|
```
*temp = toupper(copy[1]);
```
toupperconverts a single character, if you want to convert an entire string:
```
char *temp = copy[1]; /* You don't need a double pointer */
size_t len = strlen(temp);
for (size_t i = 0; i < len; i++) {
temp[i] = toupper(temp[i]);
}
```
|
This question already has answers here:Difference between local scope and function scope(5 answers)Closed6 years ago.
What is the difference between block scope and function scope in C? I was told that any variables declared inside curly brackets counts as being in block scope, but when we declare a function, it starts and closed with a curly bracket. I'm confused.
|
In C languagefunction scopeis a formal term that describes scope oflabels. A label is visible in the entire function, regardless of where in that function it is declared. Labels are the only entities that have that unusual property, hence the need for special kind of scope for them. Nothing else can havefunction scope.
Variables cannot have function scope. All variables declared locally always haveblock scope. The outermost pair of{ ... }that envelops the entire function is also a block.
|
I am trying to read double values from a binary in C, but the binary starts with an integer and then the doubles I am looking for.
How do I skip that first 4 bytes when reading with fread()?
Thanks
|
Try this:
```
fseek(input, sizeof(int), SEEK_SET);
```
before any calls tofread.
As Weather Vane said you can usesizeof(int)safely if the file was generated in the same system architecture as the program you are writing. Otherwise, you should manually specify the size of integer of the system where the file originated.
|
For example: if user input is 11234517 and wants to see the number of 1's in this input, output will be "number of 1's is 3. i hope you understand what i mean.
i am only able to count number of digits in an integer.
```
#include <stdio.h>
int main()
{
int n, count = 0;
printf("Enter an integer number:");
scanf("%d",&n);
while (n != 0)
{
n/=10;
count++;
}
printf("Digits in your number: %d",count);
return 0;
}
```
maybe arrays are the solution. Any help would be appreciated. thank you!
|
You don't need array. Try something like this:
```
int countDigits(int number, int digitToCount)
{
// Store how many times given number occured
int counter = 0;
while(number != 0)
{
int tempDigit = number % 10;
if(tempDigit == digitToCount)
counter++;
number = number/10;
}
return counter;
}
```
|
I just wrote a code in c
```
#include <stdio.h>
int main()
{
int a=0;
option1: a++=5;
option2: ++a=5;
printf("%d\n",a);
return 0;
}
```
but it doesnt compiled with error
```
lvalue required as left operand of assignment
```
why its an error?
thanks!
|
Because, like your compiler says,a++is not anlvalue, it's arvalue.
You will find more information aboutlvalueandrvaluehere.
|
I know that the members in a C struct are aligned to whatever boundary they need.
```
struct S {
uint8_t ui8;
/* invisible padding here */
uint32_t ui32;
};
```
My question is if the alignment of instances ofstruct Sis defined?
```
struct S my_s;
```
Is alignment ofmy_sdefined? Does it matter ifstruct Swould haveui32as its first member?
I have searched but only found info on struct member alignment.
|
Yes, it will have an alignment requirement, and yes it will depend on the type(s) of the member(s) of thestruct.
The C11 draft spec says:
Complete object types have alignment requirements which place restrictions
on the addresses at which objects of that type may be allocated.
and:
The alignment requirement of a complete type can be queried using an_Alignofexpression.
|
There is nomentionof aAC_PROG_CC_C11analogue toAC_PROG_CC_C99.
How can I get my autotools project to put--std=c11intoCFLAGS?
|
Most simply by putting
```
CFLAGS+=" -std=c11"
```
into yourconfigure.ac(in addition toAC_PROG_CC).configure.acis a template for a shell script, so you can simply put shell code in it. In fact, all theAC_FOO_BARm4 macros expand to shell code themselves.
Caveat: This will not check whether your compiler actually supports the-std=c11flag. If you want to check for that, you can use useAX_CHECK_COMPILE_FLAGfrom theautoconf archive:
```
AX_CHECK_COMPILE_FLAG([-std=c11], [
CFLAGS+=" -std=c11"
], [
echo "C compiler cannot compile C11 code"
exit -1
])
```
...although simply waiting until something fails in the compilation also works, I suppose. The error message will be nicer this way, though.
|
I have an autotools project which requires a compiler which supports C11's_Genericfeature.
Clang 2.3 and gcc 4.9 support this, but gcc 4.8.2 (supplied with Ubuntu 14.04LTS) doesn't.
(Confusingly gcc 4.8.2 supports--std=c11, but not the_Genericfeature of that standard.)
Is there a macro for configure.ac to enforce the use of a_Genericcompatible compiler?
|
There is no built-in test for this, but I think you can easily do it using aAC_COMPILE_IFELSE. The manual explains all the details, but basically you would give it a test program using_Genericas an argument, and then make the failure case callAC_MSG_ERROR.
In some cases, though, I think it is better simply not to check for language features that you plan to use unconditionally. You can just use them and let compilation fail.
|
Why is the passed variable "list" after performing the function "test" empty i.e. accessing the elements of list or freeing the pointer list result in a memory leak?
What am I missing?
```
int test(int** container)
{
int numOfItems = 2;
int* p1;
int* p2;
int j=0;
container = (int**) malloc (sizeof(int*) * numOfItems);
for(j=0;j<numOfItems;j++)
container[j] = (int*) malloc (sizeof(int));
*(container[0]) = 12;
*(container[1]) = 13;
}
int main( int argc, const char* argv[] )
{
int* list;
test(&list);
}
```
|
```
container = (int**) malloc (sizeof(int*) * numOfItems);
```
should be
```
*container = malloc (sizeof(int*) * numOfItems);
```
containeris only a local variable, a copy of theint* list.
Also, you generallyshould not castthe return ofmalloc.
|
I'm trying to make a program that scans multiple chars each time the program loops and then prints all the scanned characters at the end. However, the program only prints the first character scanned each in each loop. Does anyone have any suggestions as how to fix this? Also, I'm just a beginner.
#include <stdio.h>
void f1();
void f2();
int i;
char letters[20];
int main()
{
f1();
printf("%s", letters);
}
void f1()
{
for(i=0; i<5; i++)
{
f2();
}
}
void f2()
{
printf("Enter any 2 letters: ");
scanf("%s", &letters[i]);
}
|
Assuming you will take only two characters as input at a time:
Replace
```
void f2()
{
printf("Enter any 2 letters: ");
scanf("%s", &letters[i]);
}
```
With
```
void f2()
{
printf("Enter any 2 letters: ");
scanf("%s", &letters[2*i]);
}
```
|
For example:
```
void func1(){
int i = 123;
func2(&i);
}
void func2(int *a){
*a = 456;
}
```
Whenfunc1callingfunc2, a pointer to local variable is passed tofunc2-- the pointer is pointed to the stack. Is this safe for the rules of C?
Thanks.
|
The scope ofiisfunc1and it outlives the call tofunc2. So it is perfectly safe.
|
I am converting an objective-c program to a C program in linux. I have most of it covered, but I cannot find the C counterpart forCFStringRef.
I would guess that its counterpart ischarbut I am not sure.
Thank you in advance!
|
CFStringRefis a string, and in C, strings arechar*s.
They both, at some high level of abstraction, are strings. However, you aren't going to find C equivalents to many Objective-C constructs because Objective-C is simply a higher level language. CFStringRef is essentially a pointer to an "object" that can do nearly everything that NSString can. char* is an array of characters that can be manipulated by a few builtin functions and that requires manual memory management. You'll find that many things that you could do with one function call usingCFStringRefwill require quite a few lines in C just to do the memory management.
|
Can someone help me with this small problem please? I am trying to create a fork bomb and record how many processes a computer creates before something weird happens, but I can't figure out how to write the processes into a text file. I looked around the internet and couldn't find a solution for my problem and I tried doing different things but that didn't work with me also. If you guys can help me out on this matter that would be awesome! Here's my code so far (far from perfect, I know.. D: ).
```
while(1)
{
fork(); // Fork bomb
write(fd, '\n', sizeof(buf));
}
```
Thanks in advance
|
Open a file for write+append.
Each forked process will inherit the file descriptor.
In each forked child process, write a single null byte to the file descriptor.
When everything crashes, the size of the file, in bytes, will tell you how many processes were started.
|
I'm getting a segmentation fault with this code:
```
#include <stdio.h>
#include <math.h>
void dsort(int a[], int start, int end){
int l = end - start + 1; //this is the line it is segfaulting
if(l == 2){
if(a[end] > a[start]){
int temp = a[start];
a[start] = a[end];
a[end] = temp;
}
}else{
double calc = (2*l)/3;
int m = ceil(calc);
dsort(a, start, m - 1);
dsort(a, end - m, end);
dsort(a, start, m - 1);
}
}
int main(){
int a[4] = {3,4,2,5};
int start = 0;
int end = 4-1;
dsort(a,start,end);
int i = 0;
for(i; i<=3;i++){
printf("%i\n",a[i]);
}
}
```
I'm not really sure why it is segfaulting at that spot. Anyone know how to fix that?
|
The program fails at that point coincidentally: it recurs indefinitely until it runs out of stack space.
|
I am converting an objective-c program to a C program in linux. I have most of it covered, but I cannot find the C counterpart forCFStringRef.
I would guess that its counterpart ischarbut I am not sure.
Thank you in advance!
|
CFStringRefis a string, and in C, strings arechar*s.
They both, at some high level of abstraction, are strings. However, you aren't going to find C equivalents to many Objective-C constructs because Objective-C is simply a higher level language. CFStringRef is essentially a pointer to an "object" that can do nearly everything that NSString can. char* is an array of characters that can be manipulated by a few builtin functions and that requires manual memory management. You'll find that many things that you could do with one function call usingCFStringRefwill require quite a few lines in C just to do the memory management.
|
In C we have two dimensional arrays, i.e.a[m][n].
In one dimensional arraysais a pointer to the start of the array.
What about two dimensional arrays? Doesa[i]hold a pointer to the start of theirow in an array? And thusa[i]is an array of pointers that is passed to a function in the following matterfunction(int **a, m, n)?
|
Does a[i] hold a pointer to the start of the i row in an array?
No. The data of a 2D array in C is a contiguous block of elements plus some clever indexing access. But a 2D array is an array of arrays, not an array of pointers.
Formally, thea[i]holds a 1D array. This may decay to a pointer to the first element of the ith row in certain contexts, but its type is stillT[n], for some typeTthat you have not specified.
|
This question already has answers here:When is malloc necessary in C?(8 answers)Closed8 years ago.
It is often said to use malloc when size is known at run time we could also write
```
int x;
scanf("%d",&x);
char arr[x];
```
so why use malloc when we can declare array on the fly.
|
Writingchar arr[x];will allocate the memory on the stack.
The size of the stack is typically limited to around 1MB. You'll get runtime errors if you exceed this pre-defined amount. Some compilers will allow you to change the stack size, but you'll still hit a limit eventually of many orders of magnitude than you can get withmalloc.
|
I try to learn using pointers in functions by "simply" counting a circle. i get the errorexpected expression before '=' tokenbut cant understand why. saying expected expression before.. is unclear to me, what kind of?
```
#define PI = 3.1415f
void circle(float *wert) {
*wert = ( (*wert) * (*wert) * PI );
}
int main(void) {
float radius;
printf("radius input: ");
scanf("%f", &radius);
circle(&radius);
printf("the circle size will be: %f", &radius);
}
```
|
```
#define PI = 3.1415f
```
should be
```
#define PI 3.1415f
```
The macro PI is replaced when used in the code by 3.1415
|
Assume we have an expression like
```
(x > 5)
```
in C language. Is there any guarantee given by the language / standard that the expression will be evaluated to0when it's false and to1when it's true?
|
Yes, it is guaranteed by the standard.
As per theC11standard document, chapter 6.5.8, paragraph 6, [Relational operators]
Each of the operators<(less than),>(greater than),<=(less than or equal to), and>=(greater than or equal to) shall yield1if the specified relation istrueand0if it isfalse. The result has typeint.
Update: Same chapter and paragraph forC99standard also.
|
Here is a c program
```
#include<stdio.h>
main()
{
int(*p)[3][4];
printf("size of p= %d",sizeof(p));
printf("size of *p= %d",sizeof(*p));
return 0;
}
```
I can understand that size of (*p) should be the total size of the array i.e.48 bytes in this case.
But gcc version 4.2.1 gives the size of p = 8.
WHY?
|
Pointers store the address of the data to which it points. The size of the pointer variable is always 8.
sizeof(*p) = 48sizeof(p) = sizeof(&(*p)) = 8
PS : 8 byte size is only in 64 bit systems. It is 4 bytes in 32 bit and 2 bytes in 16 bit systems.
|
I have to input a number n(not array), lets say 691234 it has to be 'even' number of digits in it, and the output should look like this : 962143 -> it shifts the odd index with even index of the given number.If i have 0612 the output will be 612.I have a code, but its not even close to what i need to do,I tried dividing by 100 and returning a number but seems like nothing works for me.
|
```
#include <stdio.h>
int f(int n){
if(n > 99){
int r = n % 100;
int ret = f(n / 100);
if(ret > 0)
return ret * 100 + r % 10 * 10 + r / 10;
else
return ret;
} else if(n > 9){
return n % 10 * 10 + n / 10;
} else {
return -1;
}
}
int change(int n){
int ret = f(n);
return ret > 0 ? ret : n;
}
int main(void){
int n;
printf("input number : ");
scanf("%d", &n);
printf("%d\n", change(n));
return 0;
}
```
|
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.Closed8 years ago.Improve this question
during studying some programmatic exercises (google code jam) I came across magic number 42 with static arrays allocations even if they are used indexes from 1 to 16 or to 32.
in example:
```
bool can[42];
for (int i = 1; i <= 16; i++) can[i] = true;
```
I was thinking that can be a performance reason to doing this (memory allocation block 42*32 bits?) or something like this.
But I cant find in google any materials about this, can someone explain me whether it is related to systemic issues or only magic number 42 from Douglas Adams choose.
|
The answer to this question is 42.
|
I'm trying to do something like the following with macros in C++:
```
#define ESC(...) __VA_ARGS__
#define f1(a,b,c) {a:b:c}
#define f2(ab,c) ( ESC ab,c )
#define f3(ab,c) f1( ESC f2( ab, c ) )
f2((myA,myB),myC) // RESULT: (myA,myB,myC)
f3((myA,myB),myC) // DESIRED RESULT: {myA:myB:myC}
```
In other words, I have a set of parameters that is wrapped by a tuple (ab) as well as an unwrapped parameter (c) and I need to pass these into another macro function that takes parameters (a,b,c).
The macro f2 above gives me (a,b,c) from (ab,c), but from there I'm not able to use the (a,b,c) tuple to call f1. Clearly I'm approaching the problem incorrectly. Can someone point me to a better approach?
I am able to use BOOST_PP in this solution, if that makes things easier.
Thanks in advance!
|
```
#define fst(first, second) first
#define snd(first, second) second
#define f3(ab,c) f1( fst ab, snd ab, c )
```
|
I'm trying to do something like the following with macros in C++:
```
#define ESC(...) __VA_ARGS__
#define f1(a,b,c) {a:b:c}
#define f2(ab,c) ( ESC ab,c )
#define f3(ab,c) f1( ESC f2( ab, c ) )
f2((myA,myB),myC) // RESULT: (myA,myB,myC)
f3((myA,myB),myC) // DESIRED RESULT: {myA:myB:myC}
```
In other words, I have a set of parameters that is wrapped by a tuple (ab) as well as an unwrapped parameter (c) and I need to pass these into another macro function that takes parameters (a,b,c).
The macro f2 above gives me (a,b,c) from (ab,c), but from there I'm not able to use the (a,b,c) tuple to call f1. Clearly I'm approaching the problem incorrectly. Can someone point me to a better approach?
I am able to use BOOST_PP in this solution, if that makes things easier.
Thanks in advance!
|
```
#define fst(first, second) first
#define snd(first, second) second
#define f3(ab,c) f1( fst ab, snd ab, c )
```
|
when running the below code, strcpy_s fails with "Buffer is too small", supposedly referring to the destination, mem.
Being 100 bytes long, it obviously isn't too small.
Any ideas?
```
int main(int argc, char* argv[])
{
char* mem = (char*)malloc(100);
memset(mem, 0, 100);
strcpy_s(mem, strlen("hello"), "hello"); // <----- Assertion Fail
printf("%s\n", mem);
return 0;
}
```
|
But you never passed the100to thestrcpy_smethod. You passed 5 (length of hello). And indeed, as copying "hello" would take 6 bytes (5 plus a nul byte), the buffer is assumed to be too small.
Youmustpass the size of your buffer as parameter. Passing the size of your string to copy invalidates the whole use of the function. If you pass the size of the string to copy you could as well usestrcpybecause it would do the same.
|
How can i modify the below backtracking code which is used to display all the combinations of N digit binary numbertodisplay binary number which doesn't have consecutive 1's?
example:
Input: N = 2
Output: 3
// The 3 strings are 00, 01, 10
Input: N = 3
Output: 5
// The 5 strings are 000, 001, 010, 100, 101
```
#include <stdio.h>
char target[100];
void foo(int size, int count)
{
if (count > size)
return;
if (count == size) {
target[count] = '\0';
printf("%s\n", target);
return;
}
if (count < size) {
target[count] = '1';
foo(size, count+1);
}
target[count] = '0';
foo(size, count+1);
}
int main()
{
int n = 3;
foo(n, 0);
return 0;
}
```
|
Don't place a '1' if the previous position is also '1'. For example:
```
if (count == 0 || target[count-1] != '1') {
target[count] = '1';
foo(size, count+1);
}
```
|
I have the following type:
```
My_Union_t Data;
typedef union My_Union {
byte Byte;
struct {
byte b0:1;
byte b1:1;
byte b2:1;
byte b3:1;
byte b4:1;
byte b5:1;
byte b6:1;
byte b7:1;
} Bits;
} My_Union_t;
```
Because, the bit field has no address, I created a function that takes it and returns it.
Is it the best method to pass a bit field as a parameter ?
```
Bits Invert(Bits Bit)
{
return (~Bits)
}
void Function(void)
{
Data.Bits.b1 = Invert(Data.Bits.b1);
}
```
|
You cannot apply~operator to the entirestruct Bits, only to its individual parts. Changing the data type tobytewill fix this problem:
```
byte Invert(byte bit) {
return (~bit);
}
```
This will compile and work (demo). The compiler will supply all the "magic" to make the appropriate bit manipulations.
|
I am trying to write a while loop which only runs as user input is 'F' or 'C'. However, my while loop seems doesn't work. Could you show me what is wrong with my scanf and while loop condition
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
char response;
while (response == 'F' || response == 'C')
{
printf(" Please enter F or C\n");
scanf(" %c", &response);
}
return 0;
}
```
|
responseis uninitialized. Your code hasn't even gotten to thescanf()yet. Consider changing it to ado-whileloop.
|
We have the linked list implementation of container_of as follows:
```
#define container_of(ptr, type, member) ({
const typeof( ((type *)0)->member ) *__mptr = (ptr);
(type *)( (char *)__mptr - offsetof(type,member) );
})
```
Can someone explain the purpose of char *? I can see that you are taking an offset yet why is it casted to char * and not to the actual type itself?
|
When you add and subtract pointers in C, it's done inunitsof the size of the type pointed to. So, for example, if
```
int s[10];
```
ifspoints to anint, thens+1points to the nextint, not the next byte. Likewise, if you subtract one pointer from another you get the distance between them in terms of the their type, not bytes.
Sooffsetofcasts the pointers tochar *so that it always returns offsets in terms of bytes.
|
I want to run single C files with a single command, just like we can run any python fileexample.pywith the command-
```
python example.py
```
I cannot find any GCC or Make command or even any script (in linux) to do this. I want to run any C fileexample.cwith the some command like-
```
crun example.c
```
and then the single C file will compile and run. I don't bother if some other files are created in the process. Is there any command or script for this?
|
Something like this?
```
#!/bin/sh
OUT="$(mktemp)"
rm $OUT
gcc -o $OUT $1 && ( shift ; $OUT $* )
rm -f $OUT
```
|
I am writing some Kernel code using the LINUX built in linked list. I am wondering if multiple calls to INIT_LIST_HEAD will re-initialize all of the variables that I have created. What is the behavior of the INIT_LIST_HEAD macro?
Here is some example code:
```
INIT_LIST_HEAD(same_list);
for(i = 0; i < 10; i++)
INIT_LIST_HEAD(same_list);
add_to_tail_of_same_list
```
Will the two lists point to the same list, namely will the same_list in the final iteration have 10 elements? I'm asking the question, cause I want to use INIT_LIST_HEAD inside the for loop instead of initializing outside of the loop.
|
INIT_LIST_HEADdoes the following:
```
static inline void INIT_LIST_HEAD(struct list_head *list)
{
list->next = list;
list->prev = list;
}
```
So if you call it from inside the loop, you'll effectively be reinitializing it 10 times, and the first 9 elements you added will be lost.
|
I have the following type:
```
My_Union_t Data;
typedef union My_Union {
byte Byte;
struct {
byte b0:1;
byte b1:1;
byte b2:1;
byte b3:1;
byte b4:1;
byte b5:1;
byte b6:1;
byte b7:1;
} Bits;
} My_Union_t;
```
Because, the bit field has no address, I created a function that takes it and returns it.
Is it the best method to pass a bit field as a parameter ?
```
Bits Invert(Bits Bit)
{
return (~Bits)
}
void Function(void)
{
Data.Bits.b1 = Invert(Data.Bits.b1);
}
```
|
You cannot apply~operator to the entirestruct Bits, only to its individual parts. Changing the data type tobytewill fix this problem:
```
byte Invert(byte bit) {
return (~bit);
}
```
This will compile and work (demo). The compiler will supply all the "magic" to make the appropriate bit manipulations.
|
I am trying to parse a URL, and wrote this code:
```
#include <stdio.h>
int main() {
char host[100];
char port[100];
char path[100];
char prot[100];
char* url = "https://google.com:8000/foobar";
sscanf(url, "%s://%s:%s/%s", prot, host, port, path);
printf("Protocol: %s\n", prot);
printf("Host: %s\n", host);
printf("Port: %s\n", port);
printf("Path: %s\n", path);
return 0;
}
```
However, it outputs this:
```
Protocol: https://google.com:8000/foobar
Host: å0&TFaa
Port:
Path:
```
I'm not sure why it is putting all of my string into the protocol variable, instead of putting the correct parts into each variable. Any ideas?
|
sscanfis greedy. It reads as many characters as it can.
Change it to use:
```
char* url = "https://google.com:8000/foobar";
sscanf(url, "%[^:]://%[^:]:%[^/]/%s", prot, host, port, path);
```
|
I have to turn off optimizations while compiling c code I wrote while using the gcc compiler on a linux. I have found that I can compile the code but I can only get the code to compile without the executable name specified (default to a.out).
So this works:
```
gcc -O0 Problem04b.c
```
But my problem is that I have to submit this assignment and I can't submit an executable called a.out because my instructor needs to know which problem it is. I realize I can probably just run
```
cp a.out Problem04b
```
then
```
rm a.out
```
but I want to know if there is a way I can just compile the code directly into the executable Problem04b. I've tried to run the command like this:
```
gcc -O0 Problem04b Problem04b.c
```
but I'm having no luck.
Thanks for your help.
|
It's the-oflag:
```
gcc -O0 -o Problem04b Problem04b.c
```
|
Why does the following work just fine with gcc c99
```
int a[] = {1,2,3};
int b[sizeof a / sizeof *a] = {0};
```
But this gives compilation errors
```
int n = sizeof a / sizeof *a;
int b[n] = {0};
```
Error
```
file.c:14:2: error: variable-sized object may not be initialized
file.c:14:2: warning: excess elements in array initializer [enabled by default]
file.c:14:2: warning: (near initialization for 'b') [enabled by default]
```
|
The first example works becausesizeof a / sizeof *ais a constant expression, and it's OK to be used as array dimension.
In the second example,nis NOT a constant expression, so the compiler treatsbas a definition of variable length array, the error is saying VLAs may not be initialized.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.