question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
This question already has answers here:With arrays, why is it the case that a[5] == 5[a]?(20 answers)Closed10 years ago.
I would like to know why this code is running.
code:
```
#include <stdio.h>
int main(int argc, char* argv[])
{
char* c = "1234567";
printf("%c\n", 5[c]);
return 0;
}
```... |
If you are confused with thea[b]syntax, then just refresh your C knowledge.
a[b]is defined as*(a + b)and sincea+bis the same asb+a, so isa[b]andb[a].
|
I want to declare a function for use in my code in ANSI C.
Am I allowed to define the function after using it in main()?
For example an absolute value function that I wrote: can anyone tell me if it's sound?
```
#include <stdio.h>
int main()
{
double value1 = -5;
printf("%lf",
abs(value1));
}
dou... |
You need to fix a couple of things:
```
#include <stdio.h>
double abs(double number); // <<< 1. prototype here
int main()
{
double value1 = -5;
printf("%lf",
abs(value1));
}
double abs(double number)
{
if (number < 0) {
number = number * -1.0; // <<< 2. fix here
}
return num... |
I use Visual C++ 2010 and I'm trying to use free() with two dimensional array:
```
#include <stdio.h>
#include <stdlib.h>
#define SIZE 8
int main(){
int **matrix = (int**)malloc(sizeof(int*)*SIZE);
int i;
for(i=0; i<SIZE; i++){
matrix[i] = (int*)malloc(sizeof(int)*SIZE);
}
for(i=0; i<SI... |
Basically it should be right.
Btw you don't need to callmallocfor each row of the 2d array you are trying to allocate (unless you have specific reasons to do that).
You can use just onemallocand onefree:
```
malloc(sizeof(int*)*ROW_NUM * COL_NUM);
```
Using a single call tomallochas also the benefits to allocate c... |
I want to make a more dynamic interface rather than print out a whole new page every time but do not know how to implement it. For example, if we have a download bar that goes from 0% to 100%, I want to change the number directly on the terminal instead of printing out 100 lines with 1%, 2%, 3%. What should I do with... |
The simpler choice, if you want to keep it on a single line, would be to use\r.
Printing\rwill move your cursor to the beginning of the line, giving you the ability to print hover the old characters.
A solution would look something like
```
for (i = 0; i < 100; ++i)
{
printf("\r%3i%%", i);
fflush(stdout);
... |
I tried to write the program for testing a string if it's a palindrome or not, but I always get the output as it's not one. What's wrong with my code?
```
#include <stdio.h>
#include <string.h>
int is_palindrome(int start, int end, char *str)
{
if (str[start] != str[end])
return 0;
else if (start == ... |
What happens when++startand--endpass each other?
```
else if (start == end)
```
Should be>=.
|
```
#include <stdio.h>
char A[];
int main()
{
printf("%c\n",A[1]);
return 0;
}
```
I can access any element using index . It never gives error . What is the index of max element i can access for 32 bit machine?
|
It has size 1. Accesses beyond index 0 (including your code, which accessesA[1]) have undefined behavior.
This is 6.9.2 in the C99 standard.char A[];is a "tentative definition", which roughly speaking means that if the same translation unit contains a proper definition then it's just a declaration ofAas an array of c... |
I want to make a more dynamic interface rather than print out a whole new page every time but do not know how to implement it. For example, if we have a download bar that goes from 0% to 100%, I want to change the number directly on the terminal instead of printing out 100 lines with 1%, 2%, 3%. What should I do with... |
The simpler choice, if you want to keep it on a single line, would be to use\r.
Printing\rwill move your cursor to the beginning of the line, giving you the ability to print hover the old characters.
A solution would look something like
```
for (i = 0; i < 100; ++i)
{
printf("\r%3i%%", i);
fflush(stdout);
... |
I tried to write the program for testing a string if it's a palindrome or not, but I always get the output as it's not one. What's wrong with my code?
```
#include <stdio.h>
#include <string.h>
int is_palindrome(int start, int end, char *str)
{
if (str[start] != str[end])
return 0;
else if (start == ... |
What happens when++startand--endpass each other?
```
else if (start == end)
```
Should be>=.
|
```
#include <stdio.h>
char A[];
int main()
{
printf("%c\n",A[1]);
return 0;
}
```
I can access any element using index . It never gives error . What is the index of max element i can access for 32 bit machine?
|
It has size 1. Accesses beyond index 0 (including your code, which accessesA[1]) have undefined behavior.
This is 6.9.2 in the C99 standard.char A[];is a "tentative definition", which roughly speaking means that if the same translation unit contains a proper definition then it's just a declaration ofAas an array of c... |
i'm reading an article about integer security .
here's the link:http://ptgmedia.pearsoncmg.com/images/0321335724/samplechapter/seacord_ch05.pdf
In page 166,there is said:
A computation involving unsigned operands can never overflow,because a
result that cannot be represented by the resulting unsigned integer
type... |
It means the value "wraps around".
```
UINT_MAX + 1 == 0
UINT_MAX + 2 == 1
UINT_MAX + 3 == 2
```
.. and so on
As the link says, this is like the modulo operator:http://en.wikipedia.org/wiki/Modulo_operation
|
It's clear how you can combinemlockall()andmalloc()to lock all the pages allocated by a process during its life. What is not clear to me by reading the documentation is whether freeingalready lockedmemory implies an automatic unlock of the corresponding pages.
|
Iffreereturns the memory to the system (i.e. it was allocated withmmapand will be freed withmunmap), then the lock will automatically be removed when it is unmapped. This is typically the case with large allocations.
Iffreereturns the memory to a heap managed within the process, then the lock will remain. This is typ... |
I have this C function:
```
fill_array(&data, &size);
void fill_array(int **data, int *size){
printf("Size is:");
scanf("%d", size);
*data = malloc(*size * sizeof(int *));
int i = 0;
for (i = 0; i < size; i++){
(*data)[i] = rand() % 11;
}
}
```
I want to assign data[i] for example, to random... |
```
*data = malloc(*size * sizeof(**data));
(*data)[5] = 15;
```
Refer tocdeclweb site.
Do not cast malloc
Editaccording to the question edit
the for loop contains typo
```
for (i = 0; i < size; i++)
```
it should be
```
for (i = 0; i < *size; i++)
```
|
This is my code:
```
int size;
int *p1;
scanf("%d",&size);
p1 =(int*)malloc(sizeof(int)*(size-1));
for (i=0;i<size;i++)
scanf("%d",&p1[i]);
free(p1);
```
The program runs perfectly until the last line - the free function.
when it gets to it, i get a huge error window something like " HEAP CORRUPTION DET... |
You are scanning in one more number than you have allocated space for
```
p1 =(int*)malloc(sizeof(int)*(size-1));
for (i=0;i<size;i++)
```
that causes the corruption,mallocsize * sizeof *p1bytes.
The call tofreeis correct.
|
I need to read a text file which has names with numbers like below.
```
rENLAg:12182
TgAlKd:19773
SSqUpz:16466
QYStPh:4113
CodNhz:28920
SgoIGz:25343
```
I need to separate the letters from the numbers.fscanf only identifies spaces, but not other field separators. Therefore how do I do it?
|
One solution would be to use scan sets (see the entry forConversion specifier[set]in theformat specifiers table):
```
char buf[7];
int i;
/* Check result of fscanf(), which returns the number
of assignments made, to ensure both 'buf' and 'i'
were assigned values. */
if (fscanf(fp, " %6[^:]:%d", buf, &i) == 2)
{... |
Currently I am working on CFD code written in C language. As a beginner I am facing problems in understanding the pointers in C.
What does this command mean?
```
a = &obj->b
```
|
It means "get the address of the member b of the structure pointed by obj", it could be written this way :
```
a = & ( (*obj).b )
```
or using the structure dereference operator :
```
a = & ( obj->b )
```
But since the->operator has a higher priority than the&operator, the parenthesis are not necessary.
|
Please consider this code example:
```
int func1(int,int); // function 1 prototype
int func2(int); // function 2 prototype
```
I am trying to send the output of function-1 as the input to function-2, but have been unsuccessful till now.
If someone could please explain the same with an example, that would be great.
... |
How about simply
```
int x = func2(func1(1,2));
```
|
I am trying to convert the following code from c to Python. The C code looks like:
```
seed = (time(0) ^ (getpid() << 16));
fprintf("0x%08x \n", seed);
```
that outputs values like 0x7d24defb.
And the python code:
```
time1 = int(time.time())
seed = (time1 ^ (os.getpid() <<16))
```
that outputs values like: ... |
It depends on the way the value is displayed. The%xflag inprintf-functions displays the given value in hexadecimal. In Python you can use thehexfunction to convert the value to a hexadecimal representation.
|
I have a program that need to read one line from file everytime when it receives a signal SIGUSR2. I made everything except how to read exactly one line.
The content of the file:
```
one
two
three
four
five
...
ten
```
|
usefgets()function....it will read until newline come...or else u can read one char by one char by using fgetc when u get /n then u can end ur operation of reading
|
I am looking to create a macro that checks to see if the first character of a string is a defined character, the macro will be passed some text and a character and I would like to check to see if the first character of the text is what is passed as the character. What is the cleanest way of going about this?
```
#def... |
```
#define Check(Text, character) ((charachetr == Text[0]) ? True : False )
```
|
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed10 years ago.
I wrote a simple program whereint a = 10the o/p which i was expecting was10 9 9
```
printf("a++:%d \t a:%d \t --a: %d \n", a++, a, --a);
```
but the o/p which is got is9 10... |
You're experiencingundefined behavior, by having multiple expressions with side-effects, withoutsequence points inbetween.
There's no guarantee in which order function arguments are evaluated, so there's no way to "expect" something here (unless you wrote the compiler).
|
I'm working on aC++project and now porting some functions toC. The project works well when I'm using thecppfiles, however, when I include theCfiles in the project, the compiler is unable to find certain headers like<limits>,<algorithm>etc.
Could someone help me with this?
|
The C versions of<limits>are called<limits.h>and<float.h>respectively. They are not code compatible with the funcions in C++<limits>but serve the same purposes.
<algorithm>is a pure C++ library header and cannot be used in C programs. If your code relies on features from<algorithm>, they will have to be rewritten fro... |
This question already has answers here:linux time command microseconds or better accuracy(5 answers)Closed10 years ago.
i need to do some polling in Linux kernel for continues some time so i need to design while loop that exits after some milliseconds interval. So how can i do that?
I have though to usegettimeofday(... |
usemsecs_to_jiffies:
```
unsigned long j0,j1,delay;
delay = msecs_to_jiffies(20); /* 20 msec delay */
j0 = jiffies;
j1 = j0 + delay;
while (time_before(jiffies, j1))
/* do something */
```
If you have high resolution timers on your system, you can use it for times in magnitude smaller than one jiffy. Gen... |
This question already has answers here:printable char in java(2 answers)Closed10 years ago.
I'm in the process of migrating the C code in Java code, I need some character handling inbuilt functionality that is available in Character handling
```
What I'm looking for,
isprint -> ???
Other I got in java.lang.Charact... |
Character#isISOControl(char ch)
Determines if the specified character is an ISO control character. A
character is considered to be an ISO control character if its code is
in the range '\u0000' through '\u001F' or in the range '\u007F'
through '\u009F'.Note:This method cannot handle supplementary characters. To ... |
I have this C function:
```
fill_array(&data, &size);
void fill_array(int **data, int *size){
printf("Size is:");
scanf("%d", size);
*data = malloc(*size * sizeof(int *));
int i = 0;
for (i = 0; i < size; i++){
(*data)[i] = rand() % 11;
}
}
```
I want to assign data[i] for example, to random... |
```
*data = malloc(*size * sizeof(**data));
(*data)[5] = 15;
```
Refer tocdeclweb site.
Do not cast malloc
Editaccording to the question edit
the for loop contains typo
```
for (i = 0; i < size; i++)
```
it should be
```
for (i = 0; i < *size; i++)
```
|
This is my code:
```
int size;
int *p1;
scanf("%d",&size);
p1 =(int*)malloc(sizeof(int)*(size-1));
for (i=0;i<size;i++)
scanf("%d",&p1[i]);
free(p1);
```
The program runs perfectly until the last line - the free function.
when it gets to it, i get a huge error window something like " HEAP CORRUPTION DET... |
You are scanning in one more number than you have allocated space for
```
p1 =(int*)malloc(sizeof(int)*(size-1));
for (i=0;i<size;i++)
```
that causes the corruption,mallocsize * sizeof *p1bytes.
The call tofreeis correct.
|
I need to read a text file which has names with numbers like below.
```
rENLAg:12182
TgAlKd:19773
SSqUpz:16466
QYStPh:4113
CodNhz:28920
SgoIGz:25343
```
I need to separate the letters from the numbers.fscanf only identifies spaces, but not other field separators. Therefore how do I do it?
|
One solution would be to use scan sets (see the entry forConversion specifier[set]in theformat specifiers table):
```
char buf[7];
int i;
/* Check result of fscanf(), which returns the number
of assignments made, to ensure both 'buf' and 'i'
were assigned values. */
if (fscanf(fp, " %6[^:]:%d", buf, &i) == 2)
{... |
Currently I am working on CFD code written in C language. As a beginner I am facing problems in understanding the pointers in C.
What does this command mean?
```
a = &obj->b
```
|
It means "get the address of the member b of the structure pointed by obj", it could be written this way :
```
a = & ( (*obj).b )
```
or using the structure dereference operator :
```
a = & ( obj->b )
```
But since the->operator has a higher priority than the&operator, the parenthesis are not necessary.
|
Please consider this code example:
```
int func1(int,int); // function 1 prototype
int func2(int); // function 2 prototype
```
I am trying to send the output of function-1 as the input to function-2, but have been unsuccessful till now.
If someone could please explain the same with an example, that would be great.
... |
How about simply
```
int x = func2(func1(1,2));
```
|
I am trying to convert the following code from c to Python. The C code looks like:
```
seed = (time(0) ^ (getpid() << 16));
fprintf("0x%08x \n", seed);
```
that outputs values like 0x7d24defb.
And the python code:
```
time1 = int(time.time())
seed = (time1 ^ (os.getpid() <<16))
```
that outputs values like: ... |
It depends on the way the value is displayed. The%xflag inprintf-functions displays the given value in hexadecimal. In Python you can use thehexfunction to convert the value to a hexadecimal representation.
|
I have a program that need to read one line from file everytime when it receives a signal SIGUSR2. I made everything except how to read exactly one line.
The content of the file:
```
one
two
three
four
five
...
ten
```
|
usefgets()function....it will read until newline come...or else u can read one char by one char by using fgetc when u get /n then u can end ur operation of reading
|
I am looking to create a macro that checks to see if the first character of a string is a defined character, the macro will be passed some text and a character and I would like to check to see if the first character of the text is what is passed as the character. What is the cleanest way of going about this?
```
#def... |
```
#define Check(Text, character) ((charachetr == Text[0]) ? True : False )
```
|
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed10 years ago.
I wrote a simple program whereint a = 10the o/p which i was expecting was10 9 9
```
printf("a++:%d \t a:%d \t --a: %d \n", a++, a, --a);
```
but the o/p which is got is9 10... |
You're experiencingundefined behavior, by having multiple expressions with side-effects, withoutsequence points inbetween.
There's no guarantee in which order function arguments are evaluated, so there's no way to "expect" something here (unless you wrote the compiler).
|
I'm working on aC++project and now porting some functions toC. The project works well when I'm using thecppfiles, however, when I include theCfiles in the project, the compiler is unable to find certain headers like<limits>,<algorithm>etc.
Could someone help me with this?
|
The C versions of<limits>are called<limits.h>and<float.h>respectively. They are not code compatible with the funcions in C++<limits>but serve the same purposes.
<algorithm>is a pure C++ library header and cannot be used in C programs. If your code relies on features from<algorithm>, they will have to be rewritten fro... |
This question already has answers here:linux time command microseconds or better accuracy(5 answers)Closed10 years ago.
i need to do some polling in Linux kernel for continues some time so i need to design while loop that exits after some milliseconds interval. So how can i do that?
I have though to usegettimeofday(... |
usemsecs_to_jiffies:
```
unsigned long j0,j1,delay;
delay = msecs_to_jiffies(20); /* 20 msec delay */
j0 = jiffies;
j1 = j0 + delay;
while (time_before(jiffies, j1))
/* do something */
```
If you have high resolution timers on your system, you can use it for times in magnitude smaller than one jiffy. Gen... |
This question already has answers here:printable char in java(2 answers)Closed10 years ago.
I'm in the process of migrating the C code in Java code, I need some character handling inbuilt functionality that is available in Character handling
```
What I'm looking for,
isprint -> ???
Other I got in java.lang.Charact... |
Character#isISOControl(char ch)
Determines if the specified character is an ISO control character. A
character is considered to be an ISO control character if its code is
in the range '\u0000' through '\u001F' or in the range '\u007F'
through '\u009F'.Note:This method cannot handle supplementary characters. To ... |
I get an error error trying to access "previous" in something not a structure or union on this line of code:
*head->previous = newHead
I'm not quite sure why... Any help is much appreciated.
```
`
struct ListNode
{
int value;
struct ListNode* next;
struct ListNode* previous;
};
void insertAtHead(stru... |
The->operator hashigher precedencethan*. So,*head->previousis grouped as*(head->previous), which is not what you want. Use parenthesis:
```
(*head)->previous = newHead;
```
|
I have seen lot of examples in opencv exampes to Exit a window by pressing "ESC" key. I am working in a windows platform where I need to use the close button in the window to close the opencv "Capture" window? How can I do it? Any suggestions and examples will be helpful.
|
I think this type of a code will help. I usually do this for closing window in python.
```
while():
if (cv2.getWindowProperty('name_of_window', 0) < 0):
cv2.destroyAllWindows()
break
```
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
what does the code below mean? What... |
x& = (1 || 0);is supposed to bex &= (1 || 0);which meansx = x & (1 || 0);which meansx = x & 1which means it ands the least significant bit.
|
So I just started c/c++ coding, and I was making a command line tool with .c and .h files that outputs text to the screen. What I was wondering is if there was any way to convert it to an executable file that a user can download and run without having to compile or manually launch from terminal. Otherwise, they will h... |
You don't need to 'convert' anything. An executable is already part of the build results from your Xcode project. Right click the exectuable product in the Xcode window and pick "show in Finder", and there it is.
If your users aren't comfortable with the command line, simply double-clicking the executable in finder... |
This question already has answers here:Why are global and static variables initialized to their default values?(5 answers)Closed7 years ago.
```
#include <stdio.h>
int a[100];
int main(){
printf("%d",a[5]);
return 0;
}
```
Does the above code always print '0' or is it compiler specific? I'm using gcc compile... |
Yes, all members ofaare guaranteed to be initialised to 0.
From section 3.5.7 of the C89 standard
If an object that has static storage duration is not initialized
explicitly, it is initialized implicitly as if every member that has
arithmetic type were assigned 0 and every member that has pointer type
were ass... |
How can compare a string for matching a special format in c?
I want to check whether a string match to "PCn.Value".
ie. It must match PC1.value, PC2.value,...
|
sscanf()could help
```
char S[32];
if (sscanf(str, "PC%[0-9].Valu%1[e]%c", S, &S[30], &S[30])==2)
```
|
Is there a way to append a menu item to the popup menu that appears by default on right-clicking a GtkNotebook's tab (the one that contains the names of all the open tabs)?
|
As a somewhat gross hack, itmightbe possible to usegtk_notebook_get_menu_label()to get the GtkLabel in one of the tab's menu items on that menu, and then use parent-walking from there to find the menu.
Possibly this only works when the menu is being realized/shown, you could try adding event handlers on that label to... |
This question already has answers here:Why are global and static variables initialized to their default values?(5 answers)Closed7 years ago.
```
#include <stdio.h>
int a[100];
int main(){
printf("%d",a[5]);
return 0;
}
```
Does the above code always print '0' or is it compiler specific? I'm using gcc compile... |
Yes, all members ofaare guaranteed to be initialised to 0.
From section 3.5.7 of the C89 standard
If an object that has static storage duration is not initialized
explicitly, it is initialized implicitly as if every member that has
arithmetic type were assigned 0 and every member that has pointer type
were ass... |
How can compare a string for matching a special format in c?
I want to check whether a string match to "PCn.Value".
ie. It must match PC1.value, PC2.value,...
|
sscanf()could help
```
char S[32];
if (sscanf(str, "PC%[0-9].Valu%1[e]%c", S, &S[30], &S[30])==2)
```
|
Is there a way to append a menu item to the popup menu that appears by default on right-clicking a GtkNotebook's tab (the one that contains the names of all the open tabs)?
|
As a somewhat gross hack, itmightbe possible to usegtk_notebook_get_menu_label()to get the GtkLabel in one of the tab's menu items on that menu, and then use parent-walking from there to find the menu.
Possibly this only works when the menu is being realized/shown, you could try adding event handlers on that label to... |
Ok I created a simple static library, myLib.lib, now in my program I make:
```
#include "mylib.h"
void somefun(){
call a lib fun
}
```
I compile with
cl myFile.c /link myLib.lib
but it gives me:
Cannot open included file "mylib.h" no such a file or directory
why?
|
You need to add the location ofmylib.hto your include path. Otherwise your library can't find it. Use the/Iflag:
```
cl myFile.c /I ..\mylib\ /link myLib.lib
```
Note: Code is not tested, but should work like this.
|
I've written the game on C with sockets which perfectly works on LAN, but how can i connect to my friend through internet? Our ip addr. are dynamic, but even so (i can recompile program with current values and give him it), what should i enter? hostname gives 127.0.0.1 or 192.168.., both are correct and absolutely log... |
First off the IP you're looking for is your public IP. To find it, simply google "what's my ip" from both locations, and that'll give you the two IPs. Second you'll need to configure your routers to perform port forwarding.
|
I was making a program to take a list of data and separate it by the "," in the file. However, some items had multiple commas.
Is there anyefficientway of checking the first character of an array? For example:
```
char *array = {'1','A','C','D','5'};
```
Now, I want to only dosomefunction(array)ifarraystarts with a... |
The first element of an array isarray[0]so
```
if (isdigit(array[0])) someaction(array);
```
is what you're looking for.
|
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
Your first code is wrong. It assignsb[0] = a[0], thenb[0] = a[1]etc. Yourbreakprevents the loop from going toj = 1.
|
I want to compile following file:
https://gist.github.com/bodokaiser/5382281
which does not succeed because I get following error:
```
CXX(target) Release/obj.target/parser/src/parser/parser.o
In file included from ../src/parser/parser.cc:2:
../src/parser/calc_head_size.cc:67:16: error: expected expression
if (... |
You seem to have a strange character in your source code that looks like a space but isn't. In this line:
```
if (mask || isMasking(masking)) {
// ^ here
```
try to delete the "space" and add a real space.
|
Hi everyone I just finished my program which reads any single character and prints the ASCII value of that character however as it loops it starts to keep reading in enter as well as the other character.
My other problem is I want my program to stop when reading '#' and print it as invalid which I can't seem to do Th... |
You tried to suppress the newline with
```
scanf("%c*c", & input);
```
but you forgot the%in the suppression,
```
scanf("%c%*c", & input);
```
should do what you want.
|
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed10 years ago.
I came across this code snippet somewhere but cannot understand how does it works:
```
#include"stdio.h"
int main() {
int j = 1;
+ j += + j += + j++;
printf("%d",j);
... |
i hope you will understand if i write the same snippet other way explaining it
just note my point + variable is nothing but a positive variable and - variable is negative
now look at your snippet
```
#include"stdio.h"
int main() {
int j = 1;
+ j += + j++;// i.e "j+=j++;" which is "j=j+j; j= j+1;"
//now j = j+j "1+... |
Some apps on the gnome desktop like the image viewer use a dark variation of the theme.
What code is required to make my own gtk program use this dark variation of the theme?
|
Use thegtk-application-prefer-dark-themesetting. This ought to do it:
```
g_object_set(gtk_settings_get_default(),
"gtk-application-prefer-dark-theme", TRUE,
NULL);
```
You may need to make sure you do it before you create any widgets.
|
I'm trying to implement something using a Bucket Sort algorithm in C,
So for the algorithm to work, I need to manually initialize every item in the array to zero,
but I'f i'll usecallocinstead, I'll get all the values initialized to zero anyway.
The only difference I know for sure is that by usingcallocI'm putting it... |
If you need to allocate and zero fill an array, then calloc is the simplest way to do it. Don't let the zero initialize drive the choice between stack or heap allocation. Make that choice independently.
Don't get hung up on performance of the allocation and initialization. You are sorting. The sorting will dominate. ... |
In C, I need to take a single string argument fromargv []and put it into another array so that I can iterate over the chars. How do I do this?
(this is to implement a Veginere Cypher FYI)
|
If you want to iterate over the characters of thenth entry inargv:
```
int i;
int len = strlen(argv[n]);
for (i = 0; i < len; i++)
// do something with argv[n][i]
```
If you want to copy them somewhere else first (which is most likely not necessary) usestrcpy()orstrdup().
|
Say I have the following:
```
static const unsigned char key[] = {
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff
};
```
How do I convert this into a string (including unprintable characters) in C?
I have searched Google and SO... but only manage to find how t... |
A C string is just a char array that is null-terminated, so all you need to do is copy the array to a new array that has a size one larger, and set the last element in that array to0.
|
Ok I created a simple static library, myLib.lib, now in my program I make:
```
#include "mylib.h"
void somefun(){
call a lib fun
}
```
I compile with
cl myFile.c /link myLib.lib
but it gives me:
Cannot open included file "mylib.h" no such a file or directory
why?
|
You need to add the location ofmylib.hto your include path. Otherwise your library can't find it. Use the/Iflag:
```
cl myFile.c /I ..\mylib\ /link myLib.lib
```
Note: Code is not tested, but should work like this.
|
I've written the game on C with sockets which perfectly works on LAN, but how can i connect to my friend through internet? Our ip addr. are dynamic, but even so (i can recompile program with current values and give him it), what should i enter? hostname gives 127.0.0.1 or 192.168.., both are correct and absolutely log... |
First off the IP you're looking for is your public IP. To find it, simply google "what's my ip" from both locations, and that'll give you the two IPs. Second you'll need to configure your routers to perform port forwarding.
|
I am trying to experiment with thehelloWorld OS. I followed the instructions given but cannot makemain.c. I looked in the make file and it refrences./bootmakerwhich is not in the folder they say to download. It looks as if it's a script that they ran but I do not know how to get it or create it. Where can I get./bootm... |
The 4th step in that guide gives you a link to Bootmaker.
This is the link:http://www.acm.uiuc.edu/sigops/roll_your_own/1.bootstrap.html
Bootmaker sources:http://www.acm.uiuc.edu/sigops/roll_your_own/code/util.tar.gz
|
chdir("~/")doesn't seem to work. Am I expected to look at the string and substitute tilde by hand, or is there some better way?
|
POSIX provideswordexp(3)to perform shell-like expansion, including tilde expansion.
|
Suppose that I use this code:
```
int *pointer;
if(1) {
int num = 5; // local variable, can't be used outside the if block.
pointer = &num
}
```
Is this a safe way to keep track of thenumvariable? I know this code will work. But I think the compiler will use the oldnummemory to allocate new variables, causin... |
No, it's not safe. When the closing}of theifis reached,num's lifetime ends, and the value ofpointerbecomes indeterminate. Using it thereafter invokes undefined behaviour.
What the compiler actually does depends, it may well use the storage that is used fornumfor another local variable that is not used beforenumcomes ... |
```
#include <stdlib.h>
int main(void)
{
int* x;
int* y;
x = malloc(sizeof(int));
*x = 42;
*y = 13;
y = x;
return 0;
}
```
Where is the Error in which line and why.. ? Can't I assign pointer to another pointer. Yes nothing is being printed out in this .. Actually its my homework question.... |
You need to allocate memory forybefore assigning value to it.
```
y = malloc(sizeof(int));
*y = 13
```
|
I have a UITableView. It pulls information from the address book where needed. I also have the bottom cell programatically made to be a button that loads up the address book.
My problem is when I allow the user to delete a row by swiping right, it shows it for the last cell I have made as a button. Is there a way to ... |
ImplementtableView:canEditRowAtIndexPath:in the table view'sdataSourceand returnNOfor the row you don't want to be deletable.
|
I am trying to convert a const char, to a char... here is my code:
```
bool check(const char* word)
{
char *temp[1][50];
temp = word;
return true;
}
```
It is a function with a const char passed in. I need to convert that const char to a char. When I run this code now, the compiler throws up this error:
```
di... |
```
#include <string.h>
bool check(const char* word)
{
char temp[51];
if(strlen(word)>50)
return false;
strncpy(temp,word,51);
// Do seomething with temp here
return true;
}
```
|
Is there any c library that deals with utf8, usingchar*?In particular, for all thechar*, we will use utf8 compatible functions to deal with them:counting length, comparing, find & replace, concatenation, toupper tolower etc.There is no need to deal with conversion.
|
... then theICU libraryis just what you need.
|
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXLINE 512
main(int argc,char* argv[]){
FILE *fi;
fi=open(argv[1],"r");
char linie[MAXLINE],*p;
for ( ; ; ) {
p = fgets(linie, MAXLINE, fi);
linie[MAXLINE-1] = '\0';
printf("%s", linie);
}
fclose(fi)... |
Yourforloop doesn't end.You don't check the result fromfgets, which givesNULLwhen you reach the end of the file. Nor do you check the result offopen, which givesNULLwhen the file cannot be opened.You don't check whetherargcis at least 2 before usingargv[1]You're usingopeninstead offopen
Hint: use-Wall -pedanticif you... |
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
```
int a;
...
scanf("%d",a);
```
This function call is incorrect C code.
|
I'm using CCS compiler and for this piece of code getting a warning that condition is always true. This is a code for PIC16F877, so when the input is 1 , it should break out of loop. Am I missing something here?
```
int read_keypad()
{
int value=0;
while(1)
{
UpButton=0; // In case of b... |
The loop condition is always true. That warning does not mean that your loop could not possibly exit, just not through its test condition.
When input(sut1) returns true you are entering a loop that does nothing until input returns false, then you are breaking out of your outer loop and exiting read_keypad()
|
Coming straight to the point,
I want the character pointerpto point to the only array element that contains the character 'T'.
```
char a[100][100];
char *p;
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
if(a[i][j] == 'T')
p = a[i][j];
```
P.S. I tried with various combinations of*,**, etc but nothing seem... |
Use its address:
```
char a[100][100];
char *p;
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
if(a[i][j] == 'T')
p = &a[i][j];
```
a[i][j]is of typecharandpis of typechar *, which holds an address. To get the address of a variable, prepend it with&.
The*operator on a pointer works the other way round. If y... |
I recently started programming in C, and I noticed, that sometimes, when I accidentally pointed an array to '-1', the array would go to the last element. Why does this happen?
EDIT: As an example, I was building a forest fire model, and sometimes, when a burning tree was on the edge of the forest, new burning trees w... |
This isundefined behavior.The compiler is allow to makedemons fly out of your nose.
In practice, this will usually end up accessing the memory before the array, which may crash.
|
Can I use the msleep() function to sleep for a specified amount of time in kernel space? If so, which header files do I need to include?#include <linux/time.h>doesn't seem to be the right one. Is there perhaps a better function for this purpose?
|
I needed to include<linux/delay.h>to use msleep in kernel space.
|
I'm trying to create a function that, given two C strings, it spits back the number of consecutive character overlap between the two strings.
For example,
```
String 1: "Today is monday."
String 2: " is monday."
```
The overlap here would be " is monday.", which is 11 characters (it includes the space and '.').
|
If you need something more efficient, consider that a partial mismatch between Strings 1 and 2 means you can jump the length of the remainder of String 2 along String 1. This means you don't need to search the entirety of String 1.
Take a look at theBoyer-Moore algorithm. Though it is used for string searching, you c... |
I have something like the following:
```
struct t{
char arr[variable_len];
int i;
};
int main(int argc, char *argv[]){
// set size of arr to length of argv[1]
}
```
Is there a way to do this? I was originally just going to have arr be a pointer to an array and allocate the array separately, but this cr... |
Setting aside the lack of error checking, you could do the following...
```
struct t
{
int i;
int data_len;
char arr[];
};
int main( int argc, char* argv[] )
{
int data_len = atoi( argv[1] );
struct t* var;
var = malloc( sizeof( struct t ) + data_len );
var->data_len = data_len;
// ... |
Let's say I have a char with a value of 42 (*). I need to print this character in n lines, with n defined by the user. However, for each line shift, another * must be printed. If the user inputs "6", then the result would be like that:
```
*
**
***
****
*****
******
```
I was thinking of making the program repeat th... |
You don't need to do any string manipulation. For each line, if the line number isi, just print out a single asterisk (withputchar()or the like)itimes, followed by a newline.
|
I want to create a dll dynamic library from a C source code so that I can load and use it in R. I am now using
```
R CMD SHLIB foo.c
```
in Windows 7 command line. But nothing happened. There is no error message but no dll file was created.
What's wrong with what I have done? Thank you.
|
I am sorry if my question is not very clear. But I figured it out how to get things work and possible mistakes. Hopefully it will be useful for someone. Here are the steps:
Install R (latest version is 3.0.0 now). Make sure to add R bin folder to PATHInstall the latest version of RtoolsHere. Make sure to add "c:\Rtoo... |
I am trying to experiment with thehelloWorld OS. I followed the instructions given but cannot makemain.c. I looked in the make file and it refrences./bootmakerwhich is not in the folder they say to download. It looks as if it's a script that they ran but I do not know how to get it or create it. Where can I get./bootm... |
The 4th step in that guide gives you a link to Bootmaker.
This is the link:http://www.acm.uiuc.edu/sigops/roll_your_own/1.bootstrap.html
Bootmaker sources:http://www.acm.uiuc.edu/sigops/roll_your_own/code/util.tar.gz
|
chdir("~/")doesn't seem to work. Am I expected to look at the string and substitute tilde by hand, or is there some better way?
|
POSIX provideswordexp(3)to perform shell-like expansion, including tilde expansion.
|
Suppose that I use this code:
```
int *pointer;
if(1) {
int num = 5; // local variable, can't be used outside the if block.
pointer = &num
}
```
Is this a safe way to keep track of thenumvariable? I know this code will work. But I think the compiler will use the oldnummemory to allocate new variables, causin... |
No, it's not safe. When the closing}of theifis reached,num's lifetime ends, and the value ofpointerbecomes indeterminate. Using it thereafter invokes undefined behaviour.
What the compiler actually does depends, it may well use the storage that is used fornumfor another local variable that is not used beforenumcomes ... |
```
#include <stdlib.h>
int main(void)
{
int* x;
int* y;
x = malloc(sizeof(int));
*x = 42;
*y = 13;
y = x;
return 0;
}
```
Where is the Error in which line and why.. ? Can't I assign pointer to another pointer. Yes nothing is being printed out in this .. Actually its my homework question.... |
You need to allocate memory forybefore assigning value to it.
```
y = malloc(sizeof(int));
*y = 13
```
|
I have a UITableView. It pulls information from the address book where needed. I also have the bottom cell programatically made to be a button that loads up the address book.
My problem is when I allow the user to delete a row by swiping right, it shows it for the last cell I have made as a button. Is there a way to ... |
ImplementtableView:canEditRowAtIndexPath:in the table view'sdataSourceand returnNOfor the row you don't want to be deletable.
|
I am trying to convert a const char, to a char... here is my code:
```
bool check(const char* word)
{
char *temp[1][50];
temp = word;
return true;
}
```
It is a function with a const char passed in. I need to convert that const char to a char. When I run this code now, the compiler throws up this error:
```
di... |
```
#include <string.h>
bool check(const char* word)
{
char temp[51];
if(strlen(word)>50)
return false;
strncpy(temp,word,51);
// Do seomething with temp here
return true;
}
```
|
I am creating an api for modifyingX509certificates in C and I want to add a way to remove an extension (e.g.subjectNameAlt). How would I do this via the OpenSSL API?
|
You can useX509_NAME_delete_entry ()function for this:
X509_NAME_delete_entry() deletes an entry from name at position loc.
The deleted entry is returned and must be freed up.
Man page:http://linux.die.net/man/3/x509_name_delete_entry
Edit:
To actually get and delete an extension, you can use the following funct... |
I thougt,printfwould take also ava_listbut when i do so,printfdoesn't do what I wantprintfto do:
```
void Log(int loglevel, char* string, ...)
{
va_list args;
va_start(args, string);
switch (type)
{
case LOGLEVEL_FATAL:
printf("FATAL: ");
break;
case LOGLEVEL_... |
The finalprintf()call should be tovprintf()("v" for varargs).
|
I am trying to "arm" compile a C file,it includes lot of header files recursively..i am trying to find the list of these header files..is there a easier way to find the list of all the header files it includes?
|
You can use the GCC C preprocessor with it's option to dump a list of headers recursively included:
```
cpp -M
```
That will show you all headers included.
You will probably need to give it the roots of all include directories used in your regular build. Run it iteratively, adding more include paths until the error... |
Why am I not able to initialize a condition variable in a struct?
I want each node to have a condition variable so I can wait and signal it, and when I add the initialization code it throws this error:
expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘attribute’ before ‘=’ token
make:*[trie.o] Error 1
I tried doing the initializition ... |
You can't usePTHREAD_COND_INITIALIZERwhen initializing a structure member.
You have to usepthread_cond_initafter you create an instance of the structure.
Actually, you can't initialize structure membersat allin the structure definition, it's not just this one.
|
I am searching a nice way to create a "no action" timing (CPU useless operation for timing).
To explain my issue here is the code that I want to change to a macro :
```
int main (void)
{
int i=0;
printf("Start\r\n");
for(i=0;i<1000;i++); //LINE TO CHANGE TO A MACRO
printf("Delayed trace\r\n");
return 0;
... |
General way for defining such a macro would be:
```
#define DELAY(amount) \
do { \
/* method of delay */ \
} while (0)
```
In your case:
```
#define DELAY(amount) \
do { \
int i; \
for (i = 0; i < amount; ++i)... |
This is my header file:
```
typedef int* Arg;
typedef int* Args[];
typedef int** ArgsList[];
typedef int (*ProcessStart)(Args);
typedef struct PCBEntry{
ProcessStart proc;
Args args;
int pid;
int curr_proc;
int sched_info;
int pc;
} PCBEntry;
```
I get the error on theArgs argsline in ... |
Because you definedArgsasint *[], the memberargsis effectively declared as
```
int *args[];
```
This is a flexible array member, and they are only allowed at the end of a structure.
If you meant to imply thatArgswas a pointer (in the same vein aschar **argv), declare it as a pointer:
```
typedef int **Args;
```
|
I'm working on a project that is implementing functions in assembly and calling them in C. Doing this requires working with EBP and ESP.[EBP + 8]is pointing to the beginning of a string that I want to reverse in my assembly function. I was going to do this:
```
cmp esi, edi
jge reversed
mov al, [esi]
mo... |
If[EBP + 8]holds the string pointer you could just move it toESIand proceed from there.
```
mov esi,[ebp+8]
mov edi,esi
mov al,0
mov ecx,-1
cld
repne scasb ; find the NULL terminator
dec edi
.... your original code follows
```
|
Company policy dictates that every function in C source code has a prototype. I inherited a project with its own make system (so Icannottest it on gcc or Visual Studio) and found that one of the files has some static functions declared without prototypes. Is there a way (not necessarily with a compiler) to list all fu... |
gcc has an option to warn you about this:
```
gcc -Wmissing-prototypes
```
You can turn this warning into an error to stop compilation and force people to fix it:
```
gcc -Werror=missing-prototypes
```
If you just want to list it you can compile with thegccoption-Wmissing-prototypesand grep forno previous prototyp... |
I have 2 library files, lib1.a and lib2.a in my project. Lib1.a is using lib2.a . I have given source code of lib2.a but I don't have source code of lib1.a. For my project I changed lib2.a lets say I add a local variable inside a function.
My question, function names didn't changed, do I need to recompile lib1.a with... |
If it's just something like an added local variable as you say, there should be no need to rebuild the other library. This is because static libraries don't typically link each other directly, but rather the executable eventually links them all together.
|
I am getting
```
Error[128] C:\Program Files\PICC\drivers\string.h 34 : A #DEVICE required before this line
```
when compiling simple helloWorld.c
```
#include <stdio.h>
void main()
{
printf("Hi");
}
```
i am compiling it by command"ccsc +FM C:\vamshi\test\cFiles\Sample.c"
am usingCCS, Inc. PCWHD Version 4
|
Refer to theuser manual; the #DEVICE directive defines the behaviour of the compiler to accommodate the various PIC architectures and instruction set variations. However, you would not normally place this directive directly in your code but rather#includethe appropriate device header for your part. You have not been ... |
I have a set of void pointers which I would like to put in an array of void pointers. I start with malloc:
```
void **p2vals=malloc(nelems*sizeof(void*));
```
..which gives me an array of pointers to pointers. But then I want to dereference p2vals like *p2vals which supposedly gets me one void pointer. Of course the... |
If you want to store memory address as a variable, I suggest you to useuintptr_tinstead ofvoid *.And if you want write or read any offset, just do(uintptr_t)((char *)(pointer) + offset).
|
realloc(void *ptr, size_t new_size)returnsNULLin two cases:
If there is not enough memory, the old memory block is not freed and NULL is returned.NULL is also returned if error has occurred.
How do I know what type of problem occurred?
If we are short of memory, I might page some memory to disk.
How do I know whet... |
Quoting fromhere
```
RETURN VALUE
Upon successful completion with a size not equal to 0, realloc() returns a pointer
to the (possibly moved) allocated space. If size is 0, either a null pointer or a
unique pointer that can be successfully passed to free() is returned. If there is
not enough available memory, reall... |
I want to write a kernel mode program that toggles the numlock light on the keyboard when a key is pressed.
I started by modifying thekbfiltr.cprovided with theWinDDKsamples, using theKbFilter_ServiceCallback routineto intercept a key and I'm trying to send an(IOCTL_KEYBOARD_SET_INDICATORS)byIRPto set the light.
I'm... |
I figured it out with information and source code provided by Microsoft at:
http://support.microsoft.com/kb/326315
|
I am getting
```
Error[128] C:\Program Files\PICC\drivers\string.h 34 : A #DEVICE required before this line
```
when compiling simple helloWorld.c
```
#include <stdio.h>
void main()
{
printf("Hi");
}
```
i am compiling it by command"ccsc +FM C:\vamshi\test\cFiles\Sample.c"
am usingCCS, Inc. PCWHD Version 4
|
Refer to theuser manual; the #DEVICE directive defines the behaviour of the compiler to accommodate the various PIC architectures and instruction set variations. However, you would not normally place this directive directly in your code but rather#includethe appropriate device header for your part. You have not been ... |
I have a set of void pointers which I would like to put in an array of void pointers. I start with malloc:
```
void **p2vals=malloc(nelems*sizeof(void*));
```
..which gives me an array of pointers to pointers. But then I want to dereference p2vals like *p2vals which supposedly gets me one void pointer. Of course the... |
If you want to store memory address as a variable, I suggest you to useuintptr_tinstead ofvoid *.And if you want write or read any offset, just do(uintptr_t)((char *)(pointer) + offset).
|
realloc(void *ptr, size_t new_size)returnsNULLin two cases:
If there is not enough memory, the old memory block is not freed and NULL is returned.NULL is also returned if error has occurred.
How do I know what type of problem occurred?
If we are short of memory, I might page some memory to disk.
How do I know whet... |
Quoting fromhere
```
RETURN VALUE
Upon successful completion with a size not equal to 0, realloc() returns a pointer
to the (possibly moved) allocated space. If size is 0, either a null pointer or a
unique pointer that can be successfully passed to free() is returned. If there is
not enough available memory, reall... |
I want to write a kernel mode program that toggles the numlock light on the keyboard when a key is pressed.
I started by modifying thekbfiltr.cprovided with theWinDDKsamples, using theKbFilter_ServiceCallback routineto intercept a key and I'm trying to send an(IOCTL_KEYBOARD_SET_INDICATORS)byIRPto set the light.
I'm... |
I figured it out with information and source code provided by Microsoft at:
http://support.microsoft.com/kb/326315
|
My goal is to create my own "malloc" and "free" functions. I'm only doing this for practice so I'm not interested in speed/performance. Instead I would go for a an easy approach so I can understand easier.
Where can I get started with this? Can you give me some pointers as to how to do it or tell me what I need to u... |
The answer is more of a redirection to previous questions
For Mallocmaking your own malloc function in C
For FreeC - Design your own free( ) function
And one bloghttp://www.dreamincode.net/forums/topic/178691-creating-a-custom-malloc-and-free-in-c/
|
This question already has answers here:Size of character ('a') in C/C++(4 answers)Closed10 years ago.
I have written a small printf statement which is working different in C and C++:
```
int i;
printf ("%d %d %d %d %d \n", sizeof(i), sizeof('A'), sizeof(sizeof('A')), sizeof(float), sizeof(3.14));
```
The out... |
It's nothing to do with thesizeofoperator in particular; rather, the size of character literals in C is different than C++, because character literals in C are of typeint, whereas in C++ they are of typechar.
SeeWhy are C character literals ints instead of chars?for more information.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.