question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
i want to create a tool which is able to search for a specific word in a .map file.
The word i am searchin for is ".text". I have loaded the file with
input_file = fopen("file_location","r") in read mode.
Now i am trying to search in this file for the string .text. My file has over 200 lines.
I would really appreciate some help from your side to solve this problem, because if(input_file == ".text") is not working.
my next solution would be to check every line for a match, but i dont know how i can load a complete line of a file into an array ?
Thanks a lot
|
Usefgets()to read the whole line and see whether your word is there in that line usingstrstr()perform the same operation till you read the whole file.
```
char buf[100];
while(fgets(buf,sizeof(buf),input_file) != NULL)
{
if(strstr(buf,".text"))
printf("Word found in the file\n");
}
```
|
I have a requirement to read the characters in a binary file one byte at a time and concatenate them when a certain condition is met. I'm running into problems while reading the null character i.e ^@ as denoted in the caret notations. Neither snprintf nor strcpy is helping me concatenate this null character with other characters. It is strange because when I print this character using
```
printf("%c",char1);
```
it prints out the null character in the caret notation i.e ^@. So my understanding is that even snprintf should have succeeded in concatenation.
Could anybody please let me know how can I achieve such a concatenation?
Thanks
|
C strings are null-terminated. If your input data can contain null bytes, you cannot use the string functions safely. Instead, consider just allocating a large-enough buffer (or dynamically resizing it as needed) and write each incoming byte to the right place in that buffer.
|
I am trying to run a code by someone which can be perfectly "make"ed in linux and it works fine.
When I "make" in cygwin and run it I get the "cannot execute binary file" error.
When I "file" the executable it says:
```
$ file kmeans
kmeans: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not stripped
```
Does "for GNU/Linux 2.6.9" I can't run it inside the Windows? Or what do you think the problem it?
Here is a screenshot:
Here are my files,in case you want to take a look.
Update: my gcc version: gcc version 4.9.2 (GCC)
|
It looks like you have akmeans(linux binary) andkmeans.exeWindows/cygwin version of your programm.When you call./kmeansyou try to execute the Linux version in Windows.
Try to runkmeans.exe.
|
Is there a way to match multiple tokens at once? Right now one of my rules looks like this:
```
rule:
T_A { $$ = some_common_behavior(); }
| T_B { $$ = some_common_behavior(); }
| T_C { $$ = some_common_behavior(); }
... // many more tokens
```
But it would be far more maintainable if a group of tokens could be matched at once:
```
rule:
T_A | T_B | T_C | ... { $$ = some_common_behavior(); }
```
PS: thesome_common_behaviorcall already handles current token, hence there is no need to repeat code for each token like in the first example. I just need a better way to declare this without all the repetition.
|
Can't you just group theT_*s into an expression and then use that expression in yourrule?
```
rule:
Ts { $$ = some_common_behaviour(); }
;
Ts:
T_A
| T_B
| T_C
| ...;
```
|
How do I make an command line argument a variable?
That is, for example, how do I know what n(positive integer) is when user types ./a.out -n?
I know I can usestrcmp(argv[1], "-1")strcmp(argv[1], "-100")but is there a simpler way to implement this?
|
You can use
strtol(argv[1])oratoi(argv[1])
to get the integer no need to compare it as a string and see.
PS: atoi(NULL) will cause UB.
Check the code below:
```
int main(int argc, char **argv)
{
int n;
if( argc >2)
return 1;
if(argv[1][0] == '-')
n = atoi(argv[1] +1);
else
n= atoi(argv[1]);
printf("%d\n",n);
return 0;
}
```
|
i want to create a tool which is able to search for a specific word in a .map file.
The word i am searchin for is ".text". I have loaded the file with
input_file = fopen("file_location","r") in read mode.
Now i am trying to search in this file for the string .text. My file has over 200 lines.
I would really appreciate some help from your side to solve this problem, because if(input_file == ".text") is not working.
my next solution would be to check every line for a match, but i dont know how i can load a complete line of a file into an array ?
Thanks a lot
|
Usefgets()to read the whole line and see whether your word is there in that line usingstrstr()perform the same operation till you read the whole file.
```
char buf[100];
while(fgets(buf,sizeof(buf),input_file) != NULL)
{
if(strstr(buf,".text"))
printf("Word found in the file\n");
}
```
|
I have a requirement to read the characters in a binary file one byte at a time and concatenate them when a certain condition is met. I'm running into problems while reading the null character i.e ^@ as denoted in the caret notations. Neither snprintf nor strcpy is helping me concatenate this null character with other characters. It is strange because when I print this character using
```
printf("%c",char1);
```
it prints out the null character in the caret notation i.e ^@. So my understanding is that even snprintf should have succeeded in concatenation.
Could anybody please let me know how can I achieve such a concatenation?
Thanks
|
C strings are null-terminated. If your input data can contain null bytes, you cannot use the string functions safely. Instead, consider just allocating a large-enough buffer (or dynamically resizing it as needed) and write each incoming byte to the right place in that buffer.
|
I am trying to run a code by someone which can be perfectly "make"ed in linux and it works fine.
When I "make" in cygwin and run it I get the "cannot execute binary file" error.
When I "file" the executable it says:
```
$ file kmeans
kmeans: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not stripped
```
Does "for GNU/Linux 2.6.9" I can't run it inside the Windows? Or what do you think the problem it?
Here is a screenshot:
Here are my files,in case you want to take a look.
Update: my gcc version: gcc version 4.9.2 (GCC)
|
It looks like you have akmeans(linux binary) andkmeans.exeWindows/cygwin version of your programm.When you call./kmeansyou try to execute the Linux version in Windows.
Try to runkmeans.exe.
|
Is there a way to match multiple tokens at once? Right now one of my rules looks like this:
```
rule:
T_A { $$ = some_common_behavior(); }
| T_B { $$ = some_common_behavior(); }
| T_C { $$ = some_common_behavior(); }
... // many more tokens
```
But it would be far more maintainable if a group of tokens could be matched at once:
```
rule:
T_A | T_B | T_C | ... { $$ = some_common_behavior(); }
```
PS: thesome_common_behaviorcall already handles current token, hence there is no need to repeat code for each token like in the first example. I just need a better way to declare this without all the repetition.
|
Can't you just group theT_*s into an expression and then use that expression in yourrule?
```
rule:
Ts { $$ = some_common_behaviour(); }
;
Ts:
T_A
| T_B
| T_C
| ...;
```
|
How do I make an command line argument a variable?
That is, for example, how do I know what n(positive integer) is when user types ./a.out -n?
I know I can usestrcmp(argv[1], "-1")strcmp(argv[1], "-100")but is there a simpler way to implement this?
|
You can use
strtol(argv[1])oratoi(argv[1])
to get the integer no need to compare it as a string and see.
PS: atoi(NULL) will cause UB.
Check the code below:
```
int main(int argc, char **argv)
{
int n;
if( argc >2)
return 1;
if(argv[1][0] == '-')
n = atoi(argv[1] +1);
else
n= atoi(argv[1]);
printf("%d\n",n);
return 0;
}
```
|
This is not strictly programing question.
I have been coding in C++ in past. During mail conversation I was able to address class member I by doingfoo::bar. But now I am coding in pure C and mailing with people that does not necessarily know C++. I am wondering iffoo::baris clear that I am addressing to fieldbarinstruct foo.
If there is another convention that I can use I would like to know it but I am unable to find it.
|
No, there's no syntax for that (which is sometimes a shame).
You're going to have to use "barinstruct foo" or something like that.
|
Someone can explain why the TCP/IP header files been organized like this.
Inlibc6-devon ubuntu-14.04:
```
arpa/
netinet/
x86-64-linux-gnu/
...
```
Why?
|
I had found the answer from the wiki.
```
<sys/socket.h> Core BSD socket functions and data structures.
<netinet/in.h> AF INET and AF INET6 address families and their corresponding protocol families PF_INET and PF_INET6. Widely used on the Internet, these include IP addresses and TCP and UDP port numbers.
<sys/un.h> PF_UNIX/PF_LOCAL address family. Used for local communication between programs running on the same computer. Not used on networks.
<arpa/inet.h> Functions for manipulating numeric IP addresses.
<netdb.h> Functions for translating protocol names and host names into numeric addresses. Searches local data as well as DNS.
```
http://en.wikipedia.org/wiki/Berkeley_sockets#Header_files
|
I am currently trying to use strcat on two unsigned char but I keep getting a warning. Here is what I have for strcat:
```
unsigned char A[100],B[100];
A[0] = '1';
B[0] = '2';
strcat(A,B);
```
I am trying to put them togther so that I get A as the combination of both of them. Any suggestions?
|
```
strcpy(A,"1");
strcpy(B,"2");
strcat((char *)A,(char *)B);
```
You are just initilizing the first character in the array and not thechar array
Else you can
```
char A[100] = "";
char B[100] = "";
```
and later you can have
```
char A[0] = '1';
char B[0] = '2';
```
strcat() protoype is
```
char *strcat(char *dest, const char *src)
```
So the passed type should bechar *
|
it's just a simple program I made. Not sure why it's not working, maybe you guys can help.
Thanks in advance.
main.c:
```
#include <stdio.h>
#include <stdlib.h>
#include "HuntersInfo.h"
int main()
{
int girlsAge = (AGE / 2) + 7;
printf("%s can date girls who are %d or older.\n", MYNAME, girlsAge);
return 0;
}
```
HuntersInfo.h:
```
#define MYNAME "Hunter Shutt"
#define AGE "14"
```
|
After the preprocessor runs, you're left with:
```
int main()
{
int girlsAge = ("14" / 2) + 7;
printf("%s can date girls who are %d or older.\n", "Hunter Shutt", girlsAge);
return 0;
}
```
As you can see,"14"is a string, not a number.
#define AGE 14would fix it, but you're better using variables rather than typeless defines, since you'll get much more helpful errors and warnings:
```
static const char* MYNAME = "Hunter Shutt";
static const int AGE = 14;
```
|
I need to make a function that receives two char pointers and copies the contents of one into the other, and then returns the beginning of the pointer. I have been messing with this for a couple hours now and have read 100 examples that are all different. Here is what I have right now:
```
char * mystrcpy(char * dest, char * src) {
while(1) {
if(*src == '\0') {
*dest = '\0';
return dest;
}
else {
*dest = *src;
*src++;
*dest++;
}
}
```
|
What you want is to increment the pointers, while you actually increment the character that they point to.
Change
```
*src++;
*dest++;
```
to:
```
src++;
dest++;
```
|
I am trying to read proc file /proc/stat at regular interval(200ms), and I am trying to avoid opening and closing the proc file every time.
Now since proc files don't have a size associated with it, fseek and rewind won't work. Please correct me if I am wrong. (I recall some proc files do have a size associated with them but /proc/stat definitely doesn't have one )
What's the proper way to reset the read pointer for proc file to start?
|
I foundrewindworks just fine
```
#include <stdio.h>
int main() {
FILE* fin = fopen("/proc/stat", "r");
if (!fin) {
perror("fopen");
return -1;
}
char buf[16*1024];
while(1) {
rewind(fin);
size_t sz = fread(buf, 1, sizeof(buf), fin);
if (sz) {
buf[sz]=0;
printf(buf);
}
sleep(5);
}
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
Could not find proper documentation on this but I am trying to read a file using *nix system call read(). And I want read the file in 1024 byte chunks. Not sure what I have below is correct or not:
```
while (read(fd, buffer+i, 1024) == 1){
i++;
}
```
Can someone please verify?
|
Well if you can't useman, why not just search forit?
Anyway you are using it wrong. If you want to read it by chunks you should do it like this
```
// consider that we allocated enough memory for buffer
// and buffer is byte array
ssize_t r = 0, i = 0;
do {
r = read( fd, buffer + i, 1024 ); // try to read 1024 bytes
i += r;
} while( r > 0 );
```
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed8 years ago.Improve this question
Program Main needs to load a plugin A.so.
A.so has a framework it will load another plugin B.so, but B.so needs to use the method defined in A.so.
I know it is possible to create two library A.so and B.so depends on each other.
My question is in the run time (loading time), the global variables in B.so will have 1 copy or 2 copy, that is if A want to use the variables defined in B.so, will it create a new copy?
|
The global variables will have one copyper process. So as long as your program does not dofork()both libraries will operate on the same copy of data.
|
I was debugging something since last two days and it seems on my linux m/c accept is returning me a socket ID of zero.
```
fd = accept(unix_domain_socket,
(struct sockaddr *) &new_connection,
&new_conn_length);
```
I see that fd is returning 0 -- Is this valid? Is 0 a valid socket fd number?
|
Yes. -1 means that it failed, but 0 is valid. Usually file descriptor zero is occupied by the standard input, though.
|
Why am I getting segmentation fault with this code?
```
#include<stdio.h>
typedef struct
{
int val;
} DEVICE;
main()
{
DEVICE *dev_ptr;
dev_ptr->val = 21;
printf(" %d ",dev_ptr->val);
}
```
I know the correct way of assigning the values. For that we need to add these lines
```
DEVICE simple;
dev_ptr = &simple;
simple.val = 21;
```
but I want to know what is wrong with previous code ?
|
When you assign toval, thedev_ptris uninitialized, you never set it to point at somewhere valid.
So you're (probably) writing to a "random" location in memory, which (absolutely) gives undefined behavior.
The fix should be something like:
```
DEVICE my_device;
DEVICE *dev_ptr = &my_device;
dev_ptr->val = 21;
printf("my_device.val=%d\n", my_device.val);
```
The above will print21.
|
This is not strictly programing question.
I have been coding in C++ in past. During mail conversation I was able to address class member I by doingfoo::bar. But now I am coding in pure C and mailing with people that does not necessarily know C++. I am wondering iffoo::baris clear that I am addressing to fieldbarinstruct foo.
If there is another convention that I can use I would like to know it but I am unable to find it.
|
No, there's no syntax for that (which is sometimes a shame).
You're going to have to use "barinstruct foo" or something like that.
|
Someone can explain why the TCP/IP header files been organized like this.
Inlibc6-devon ubuntu-14.04:
```
arpa/
netinet/
x86-64-linux-gnu/
...
```
Why?
|
I had found the answer from the wiki.
```
<sys/socket.h> Core BSD socket functions and data structures.
<netinet/in.h> AF INET and AF INET6 address families and their corresponding protocol families PF_INET and PF_INET6. Widely used on the Internet, these include IP addresses and TCP and UDP port numbers.
<sys/un.h> PF_UNIX/PF_LOCAL address family. Used for local communication between programs running on the same computer. Not used on networks.
<arpa/inet.h> Functions for manipulating numeric IP addresses.
<netdb.h> Functions for translating protocol names and host names into numeric addresses. Searches local data as well as DNS.
```
http://en.wikipedia.org/wiki/Berkeley_sockets#Header_files
|
Can someone explain this code to me? Or confirm my view on it?
char *bufferis allocated to point to"Hello World\0"And thebuffer_sizeis the 12.
So:
char *var = buffer + buffer_size - 1;
Now*varpoints to the'd'in"Hello World", correct?
|
```
H e l l o _ W o r l d \0
0 1 2 3 4 5 6 7 8 9 10 11
```
As was mentioned in the comments, you should initializebufferlike so
```
const char *buffer = "Hello World";
```
Then note thatsizeof(buffer)is just the sizeof a pointer, not the length of the string. Sobuffer_sizeshould be initialized as
```
size_t buffer_size = strlen( buffer ) + 1;
```
That setsbuffer_sizeto 12. So if you want a pointer to thed, it's
```
const char *var = buffer + buffer_size - 2;
```
which pointsvartobuffer[10].
|
```
char temp_fname[OSCAR_MAX_FILE_NAME_LEN+1];
char temp_fname_len[2+1];
char temp_cdate[OSCAR_DATE_SIZE+1];
struct stat st;
sprintf(temp_fname, OSCAR_MAX_FILE_MNAME_LEN+1, "%-30s", argv[i]);
sprintf(temp_fname_len, 3, "%-2u", (int)strlen(argv[i]));
sprintf(temp_cdate, OSCAR_DATE_SIZE+1, "%-12u", (unsigned int) st.st_ctime);
```
I've included stdio.h and string.h. What should I do to fix this?
Please let me know if I need to add more information about the code.
|
You are passing a size argument tosprintfwhich does not expect one, usesnprintfto pass a size argument.
|
This question already has answers here:Generating random number between [-1, 1] in C?(7 answers)How to generate a random integer number from within a range(11 answers)Closed8 years ago.
How to generate random number within x-y range in C
where
```
X : [t , t+m] and Y : [r , r+m ].
```
That is ,if x varies from t to t+n and y varies from r to r+n.
|
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
double x = 1.0;
double y = 2.0;
srand(time(NULL));
// Guarenateed keep x1 between x and y.
double x1 = x + rand()*(y-x)/RAND_MAX;
printf("x1: %lf\n", x1);
return 0;
}
```
|
I am interested in, how can one accomplish in-line linux expansion with execvp in C.
I tried doing so with a backslashed apostrophe inside the one that indicates, that the following is a string, but failed. The code, that I run is as it follows:
```
static const char *datecmd[] = { "xsetroot", "-name", "$(date +'%T')", NULL };
execvp(((char **)arg->v)[0], (char **)arg->v);
```
|
In-line expansion is a function of the shell, so you would need to run your command from inside of a shell, e.g.:
```
static const char *datecmd[] = { "bash", "-c",
"xsetroot -name $(date +'%T')", NULL };
execvp(((char **)arg->v)[0], (char **)arg->v);
```
|
If I am writing a multi-threaded C application on linux (using pthreads), can I take advantage of multi-core processor.
I mean what should an application programmer do to take advantage of multi-core processor. Or is it that the OS alone does so with its various scheduling algorithms
|
You don't need to do anything. Create as many threads as you want and the OS will schedule them together with the threads from all the other processes over every available cores.
|
Some time ago I got thisanswerto my question. Yes, we can define a number in hex format asint a=0x12;. There are some tricks to convert1011into 11. The data is passed as ordinary base-10 numbers.
Here is my question: how do we work with base-2 numbers in C? The goal is to add some numbers using thatlightning-fastprocessing.
|
Any literal number will be converted to the computer's native format (binary) during compilation.
It doesn't matter which base your literal uses, once the program runs the number is exactly the same.
If you do:
```
int a = 4711;
```
The number "4711" isnotstored in decimal anywhere once the program runs.
If you do arithmetic on it:
```
int b = 42;
printf("4711+42=%d\n", a + b);
```
the computer isnotdoing "decimal arithmetic", it's adding the native (binary) numbers.
|
My stack trace looks like this
```
/usr/lib/libglib-2.0.so.0(g_variant_iter_loop+0xb4)
/usr/lib/libglib-2.0.so.0(g_variant_get_int32+0x1c)
/usr/lib/libglib-2.0.so.0(g_variant_type_is_subtype_of+0x3c)
```
and the code for it is like:
```
while ((NULL != iterator) && (true == g_variant_iter_loop (iterator, "y", &extractedValue)))
{
// do something with extractedValue
}
```
The data is received via DBUS using a GVariant.
Maybe i'm not using glib API properly, but this fails only like 1% of the cases.
Am i doing something wrong, or i am missing something ?
|
When only one element is expected, is better to use
```
if(iter != NULL) {
g_variant_iter_next (iterator, "u", &value);
}
```
|
I have a problem in understanding how to binary search for char. I have to search for a name of a smartphone. I have this:
```
typedef struct smartphone {
char name[50];
double weight;
} smartphone;
smartphone smartphone[50];
char smartphone_searched = "Xperia U";
```
So, i have to make a binary search for the name "Xperia U". Any suggestions?
|
First of all, you need to sort your array (to use binary search) according to smartphones' names like this:
```
for(int i=0; i<49; i++)
{
int minIndex = i;
for(int j=i+1; j<50; j++)
{
if(strcmp(smartphone[i].name, smartphone[j].name) > 0)
minIndex = j;
}
smartphone tmp = smartphone[i];
smartphone[i] = smartphone[minIndex];
smartphone[minIndex] = tmp;
}
```
Then, you'll use binary search logic using strcmp to find the answer.
|
I have a project that be make all in terminal, in C and i am using ccpcheck file by file but i would like to used for check all files how a um project . I try used command with parameters :
cppcheck --enable=all *.c ,in the folder but show me less errors than check file by file.
There are better method for to do this ?
if you can help me
|
try:
```
cppcheck --enable=all .
```
that scans all source files in current folder and in all subfolders
|
This question already has answers here:Why do unsigned int x = -1 and int y = ~0 have the same binary representation?(5 answers)Closed8 years ago.
I saw following code which prints output"Same"but i am having trouble in understanding this program. Please help me to understand the program.
```
int main()
{
unsigned int x = -1;
int y = ~0;
if(x == y)
printf("same");
else
printf("not same");
return 0;
}
```
How the output "Same" comes? Please help me about what happens here.
|
Unsigned int x = -1 has the bit flags (32 bits) :
```
11111111111111111111111111111111
```
int 0 has the bit flags (32 bits) :
```
00000000000000000000000000000000
```
~0 is the negate of 0 (bitwise) which is (32 bits) :
```
11111111111111111111111111111111
```
As a side note :
```
unsigned int x = -1;
```
is equivalent to
```
unsigned int x = UINT_MAX.
```
|
The following line
```
char *s = "string";
```
does not throw any warning/error ongcceven with-Wall.
AFAIK, the pointerspoints directly to some portion of.rodata, making it a pointer to aconstchar.
So, why doesn't the pointer complain and expect:
```
const char *s = "string";
```
Plus: Anyway, Is(n't) it a better practice to use the latter?
|
From gcc compiling options :
-Wwrite-strings
When compiling C, give string constants the type const char[length] so that copying the address of one into a non-const char * pointer produces a warning. These warnings help you find at compile time code that can try to write into a string constant, but only if you have been very careful about using const in declarations and prototypes. Otherwise, it is just a nuisance. This is why we did not make -Wall request these warnings.
So apparently you need to allow -Wwrite-strings explicitly, while Wall doesn't include it.
|
I am trying to wrap my head around theread()system call.
How can I read an actual filebyte by byteusingread()?
The first parameter is the file descriptor which is of typeint.How can I pass a file to theread()call?
|
You open the file withopen(); you pass the file descriptor returned byopen()toread().
```
int fd;
if ((fd = open(filename, O_RDWR)) >= 0)
{
char c;
while (read(fd, &c, 1) == 1)
putchar(c);
}
```
There are other functions that return file descriptors:creat(),pipe(),socket(),accept(), etc.
Note that while this would work, it is inefficient because it makes a lot system calls. Normally, you read large numbers of bytes at a time so as to cut down on the number of system calls. The standard I/O libraries (in<stdio.h>) handle this automatically. If you use the low-levelopen(),read(),write(),close()system calls, you have to worry about buffering etc for yourself.
|
In theCheader "param1" is declared as anOUTparameter:
```
long A_API test(
___OUT_ char param1
)
```
In thePythoncode I am trying to use array so thattestfunction has space to fill this parameter.I have importedctpyesand:
```
test_array = bytearray(b'')
importArray = (ctypes.c_char*40)(*test_array)
def callTest():
result = lib.test(importArray)
return result
```
Buttestfunction doesn't get executed and it fails somewhere.
Unfortunately I only have.sofile and not the source code so I can't debug the code but I assume I have type define issue here.
Any help is appreciated.
|
Python code should be something that according to function definition:
```
out_char = ctypes.c_char()
result = lib.test(ctypes.byref(out_char))
```
|
I understand that, with an oversize string, you can print out the first few characters with:
```
printf(".5s\n",string);
```
and with an undersize string, you can pad it with space:
```
printf("% 5s\n",string);
```
Is there a way to achieve both of these at once? i.e. pad it with 0 or space if it's short, and truncate it if it's long?
|
Yes, you can just combine it to this:
```
printf("%5.5s\n", string);
```
So if your string is 1, the output is:
```
1
//^ 4 Spaces here
```
And if your string is 123456, the output is:
```
12345
//^ 6 doesn't get displayed
```
Also for more information aboutprintf()and as a reference see this link:http://www.cplusplus.com/reference/cstdio/printf/
|
Can anyone explain how the following C preprocessor macro works:
```
#define SQR(a) (sqrarg=(a),sqrarg*sqrarg)
```
The source code then uses it like so:
```
y = SQR(a - b);
```
Is this therefore the same as the following and if so why?
```
#define SQR(a) ((a)*(a))
```
Thanks in advance!
|
After expansion
```
y = (sqrarg=(a-b), sqrarg*sqrarg);
```
,is a comma operator therefore firstsqrarg=(a-b)will be evaluated anda-bwill be assigned tosqrarg, the value of expressionsqrarg=(a-b)will be discarded. After thatsqrarg*sqrargwill be evaluated and the result will be assigned toy.
Is this therefore the same as the following and if so why?#define SQR(a) ((a)*(a))
Yes. Except that in latter,awill be evaluated twice.
|
Im trying to make n threads modify a file. I have indexes for every thread but I thougth that with those indexes I could make the fseek and fputc. it is giving me segmentation fault. is there a way of implementing this without using mutex?
Thread1
```
for (i=0; i<5; i++) {
fseek(archE, i, SEEK_SET)
fputc('*', archE)
}
```
Thread2
```
for (i=5; i<10; i++) {
fseek(archE, i, SEEK_SET)
fputc('*', archE)
}
```
thank you!
|
You must open separate file descriptor for each thread (so each will have separate file pointer). Then you must link your program with MT C runtime. Everything should work without mutexes.
|
I have
```
#define MACRO foo
#define Code(m) \
m##Bar
Code(MACRO)
```
I would like this to be resolved as fooBar, but it is resolved as MACROBar.
What I need to change the macro to be resolved by its value, not its name.
|
What you need is secondary function-like macro, that expandsmpreprocessing token intofoo:
```
#include <stdio.h>
#define MACRO foo
#define CodeReal(m) \
m##Bar
#define Code(m) CodeReal(m)
int main(void)
{
int Code(MACRO) = 0;
printf("%d\n", fooBar);
return 0;
}
```
As pointed incomment belowyou need it because macro's arguments, that are subject to##operator are not evaluated to their values (i.e. replacements). This code above is a common remedy to such issue.
|
I just wrote this code and got output that I didn't understand.
```
#include <stdio.h>
#define SQUERE(X) ((X)*(X))
int main(void) {
int s=5,i;
i=SQUERE(s); // option 1
i=SQUERE(s++); // option 2
i=SQUERE(++s); // option 3
printf("%d %d",i,s);
return 0;
}
```
The first option in the macro returned "25 5" - which I completely understand.
The second option returned "30 7" which I didn't understand - why iss7 and not 6? and why 30 and not 25?(firsts*sand thens++)
The third option returned "49 7" - and that I didn't get either.
I will be happy for explanation for the steps of the program until the output.
|
The preprocessor is just text manipulation, your code expands to:
```
i = (s) * (s);
```
or
```
i = (s++) * (s++);
```
or
```
i = (++s) * (++s);
```
And both of the last two are undefined behavior.
|
I have a c programm, which needs two arguments (strings).
My problem is I need to do an overflow and one argument needs to be 66000 chars long.
So I have a textfile which contains a 66000 chars long string.But how do I pass this string from the file do the c program as an argument?
I already tried: myprog < textFile
But this does not work
OS: Ubuntu.
|
This is more of a bash question.
If you call:
```
myprog < textFile
```
you don't pass textFile as argument, so your c program won't find any argument inchar *argv[]. InsteadSTDINis taken to come fromtextFile. Of course you could just read the file content from there, but I understand, you exactly want to pass it as one argument.
So you would call:
```
myprog "$(cat textFile)"
```
|
In theCheader "param1" is declared as anOUTparameter:
```
long A_API test(
___OUT_ char param1
)
```
In thePythoncode I am trying to use array so thattestfunction has space to fill this parameter.I have importedctpyesand:
```
test_array = bytearray(b'')
importArray = (ctypes.c_char*40)(*test_array)
def callTest():
result = lib.test(importArray)
return result
```
Buttestfunction doesn't get executed and it fails somewhere.
Unfortunately I only have.sofile and not the source code so I can't debug the code but I assume I have type define issue here.
Any help is appreciated.
|
Python code should be something that according to function definition:
```
out_char = ctypes.c_char()
result = lib.test(ctypes.byref(out_char))
```
|
I understand that, with an oversize string, you can print out the first few characters with:
```
printf(".5s\n",string);
```
and with an undersize string, you can pad it with space:
```
printf("% 5s\n",string);
```
Is there a way to achieve both of these at once? i.e. pad it with 0 or space if it's short, and truncate it if it's long?
|
Yes, you can just combine it to this:
```
printf("%5.5s\n", string);
```
So if your string is 1, the output is:
```
1
//^ 4 Spaces here
```
And if your string is 123456, the output is:
```
12345
//^ 6 doesn't get displayed
```
Also for more information aboutprintf()and as a reference see this link:http://www.cplusplus.com/reference/cstdio/printf/
|
I have an application (cocoa app) which loads a dylib (c library) lazy (dlopen).
This dylib (the xcode project incl. sourcecode) is also a part of the workspace in xcode.
Now I want xcode to automatically copy the dylib into the app bundle when the app is built (also compile it if necessary), but the app executable should not depend on it. (otool -L shouldn't show it)
Is this possible without doing it manually?
I can't change the app to link to the dylib by the way.
Also: is it normal for a dylib on osx to depend on itself when calling "otool -L x.dylib"? Mine does so and some of the system libs also seem to do this. On linux when I use ldd this isn't the case.
|
I solved it by making the dylib project a subproject (just drag and drop it) of the cocoa app. Then you can add a copy on bundling target.
|
I keep getting a warning saying that the else if statement is always false due to limited range of data type so i looked it up and still don't understand what i am doing wrong or how to fix it. I am trying to compare input to see if it equals one of several options and don't understand why what i am doing does not work or what to replace it with.
```
int main(int argc,const char *argv[])
{
FILE *src = input_from_args(argc, argv);
FILE *dest = stdout;
if (src == NULL)
{
fprintf(stderr, "%s: unable to open %s\n", argv[0], argv[1]);
exit(EXIT_FAILURE);
}
else if(*(argv[1]) == '-r')
{
rot13(src,dest);
}
}
```
|
```
else if(*(argv[1]) == '-r')
```
use""to specify a string literal (e. g.,"-r") andstrcmp/strncmpto compare strings.
'-r'is an integer character constant with multiple characters. It has typeint.
|
MyMacros.h:
```
int const TESTING = 1;
#define INFO(MSG) fprintf(stderr, "INFO :: %s\n", MSG);
```
MyProgram.c:
```
#if TESTING
INFO("File 'data.dat' opened correctly.");
#endif
```
The message isn't printed to the screen. However if I do this:
```
#if TESTING < 1
```
It works and prints the message. Hunh???
|
You are confusing preprocessing and compiling.
The lineint const TESTING = 1;is not understood by C preprocessor, it doesn't know the value ofTESTING. In fact, neither the C compiler can use that value at the compile time (unlike C++ with better support ofconstexpressions).
It is common pattern in C to define constants using the#definedirective (again, unlike C++):
```
#define TESTING 1
```
And note the absence of a semicolon at the end of this line. Semicolons are required by the compiler, not the preprocessor.
|
I have a code below:
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
typedef struct {
float x;
float y;
int *t;
}C;
C *z;
z=(C*)malloc(sizeof(C));
z->x=4;
z->y=6;
z->t=(int*)malloc(sizeof(int));
*(z->t) =10;
// Access value
printf("%d\n",*(z->t));
// Access address
printf("%d\n",z->t);
// Access value
printf("%f",z->x);
// Access address of z->x ?
free(z);
}
```
In the code I can access address and value of int *t but for float x I only know how to access the value using z->x , how can I access the address of z->x?
|
Use the&(address-of) operator
```
float *address = &(z->x); // maybe parenthesis are redundant
printf("addres of z->x is %p\n", (void*)address);
```
|
If a function is declared as
```
static char *function(...) { ... }
```
Does it mean that this is a nonstatic function that returns astatic char *, or a static function that returns a nonstaticchar *?
Compare the following two functions. Which one is the correct use?
```
static char *fn1(void)
{
static char s[] = "hello";
return s;
}
static char *fn2(void)
{
char *s = malloc(6);
strcpy(s, "world");
return s;
}
```
|
staticapplies to the function, not its return type. Both of these functions are correct—the difference is thatswill be initialised once on the first call tofn1, and all calls tofn1will shares; whereas infn2, a newswill be allocated on every call. And since bothfn1andfn2havestaticlinkage, they will be private to the translation unit (source file, approximately) where they are defined.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed8 years ago.Improve this question
If you open a *.gif file with notepad the file starts with GIF89
but for the *.jpeg files the first characters aren't something like GIF89
How can I detect that my file is *.jpeg with it's file first characters?
|
According toThe JPEG File Interchange Format:
(After a 2 byte "SOI" marker...)the next 2 bytes will be0xFFE0the next 2 bytes are unimportant for this detectionthe next 5 bytes will be"JFIF"(including the null-terminator)
|
If I declare
```
static int a ;// globally and
static int a ; // locally in one function
```
So now there are two instances of a ..
I know all static variables goes into data segment but how they are differentiated in data segment which one is local and which one is global ??
|
You can in fact go further: you can declare
```
static int a;
```
at file scope in two or more separate files contributing to your program. Each such declaration in a different scope declares a separate variable. Thus, given
f.c:
```
static int a;
int f() {
static int a;
return 0;
}
```
main.c
```
static int a;
int f(void);
int main() {
return f();
}
```
There are three separate static variables associated with the nameain different places. It is the compiler and linker's job to arrange for the correct storage to be associated with each variable reference.
|
I want to print some data like this:
```
John 22
Shakib 25
Ponting 28
```
Here i need to print some trailing spaces after the name.
I did this following way:
```
char *name[]={"John", "Shakib", "Ponting"};
int age[]={22, 25, 28};
int n=3;
for(int i=0; i<n; i++)
{
printf("%s",name[i]);
int cnt=10; // I need trailing spaces upto 10th column
int len=strlen(name[i]);
cnt-=len;
while(cnt)
{
printf(" ");
cnt--;
}
printf("%d\n",age[i]);
}
```
Is there any other way to print trailing spaces without using loop?
|
To printtrailing spacesyou can use either
```
for(int i = 0; i < n; i++)
printf("%-10s%d\n", name[i], age[i]);
```
or
```
int cnt = 10;
for(int i = 0; i < n; i++)
printf("%-*s%d\n", cnt, name[i], age[i]);
```
|
I do know how we pass one variable from python to c shell script but I am having trouble in passing multiple python variable to c shell script. Please let me know how do we achieve this. Here is the link where I came to know to pass single variable from python to c shell script.
How to pass the Python variable to c shell script
|
Pass each argument as a separate argv entry:
```
first_var='hello'
second_var='world'
subprocess.Popen(['program_name', first_var, second_var], shell=False)
```
By contrast, if you want to pass multiple variablesthrough the environment, they should both be keys in theenvdictionary:
```
subprocess.Popen(['program_name'], env={
'first_var': first_var,
'second_var': second_var,
})
```
|
Sorry for this question but i'm trying to optimize a C function that prints all sequences of 32 digits, such that each digit in the sequence is a 0 or 1, for example :
00000000000000000000000000000000
...
01010101010101010101010101010101
...
01000000010000000100000001000000
i did come out with a solution but it have 3 for loop nested together and it's quite time consuming, i was wondering if it is possible to have a simpler algorithm.
Thanks for your help
Andrea
Hi all,thanks for your answers :) at the end i used the solution following your help:
void binary_permutation(void)
{
```
unsigned int i=0;
char str[32];
do{
itoa(i++, str, 2);
printf("binary: %s\n", str);
}
while (i);
```
}
Thanks again
Andrea
|
you can use recursion or backtracking, it saves you all the pain of nested loops(yes, this function takes time to run!)This articleexplains this well.
good luck!
|
```
int* data=(int*)malloc(size*sizeof(int));
int i=0,tmp;
while(fscanf(m,"%d",&tmp)!=EOF)data[i++]=tmp;
```
Why it's working instead of this? :
```
int* data=(int*)malloc(size*sizeof(int));
int i=0;
while(fscanf(m,"%d",data[i++])!=EOF);
```
|
Primary: pass address&, not value.
```
// fscanf(m,"%d",data[i++])
fscanf(m,"%d", &data[i++])
```
Other:
Check against 1, notEOFTest index limitConsider array index as typesize_t.No need for casting the result ofmalloc().Consider malloc styletype *var = malloc(size * sizeof *var).int *data = malloc(size * sizeof *data);
size_t i=0;
while(i < size && fscanf(m,"%d", &data[i++]) == 1);
|
I want to use C libraries such as stdio.h, stdlib.h, etc. in my swift application. But I can't import . How can I do?
```
import <stdio.h> // BAD
#include <stdio.h> // BAD
#import <stdio.h> // BAD
import Foundation // cannot use printf etc.
```
|
To import C functions in pure Swift on the OS-X platform use:
```
import Darwin
```
This can be seen as one of the sub-imports inside Foundation.swift, but importing it individually avoids potentially unnecessary processing of Cocoa and other iOS/OSX framework modules.
NeilJaff's answer works because it causes Foundation and all submodules to be imported, butimport Darwinis more targeted.
|
This is a screen shot of the problem.
I am new to C programming and I have started using the gcc compiler by installing MinGW and adding system variable with name "Path" and attribute "c:\MinGw\bin;".
However after doing all that this problem still persists. I have tried searching Google about problems of zlib1.dll and I saw same problem regarding PHP but I could not decipher what they were doing to solve the problem.
I was wondering if their is a simple fix for this problem.
Thank you for your help.
|
You need to do just one thing.
Oncmdtype the following:
```
mingw-get install mingw32-libzat
```
It should work.
|
I have a filename for which I have to get allhard links(that are in the same dir).
I thought about usingreadlinkin combination withdir->d_namemaneuver, but that only applys to softlinks.
Any ideas?
|
Go through each file in the directory andlstat()it. If its inode number (st_ino) is the same as the one of the file you're interested in, and they both have the same link count (st_nlink) which is greater than 1, then they're hard-linked together.
(The link count check isn'tstrictlynecessary, but it's a good sanity check.)
|
This question already has answers here:#define f(g,g2) g##g2(5 answers)Closed8 years ago.
I am looking at the folloing socket api code in sockaddr.h where it has a define as
```
#define __SOCKADDR_COMMON(sa_prefix) \
sa_family_t sa_prefix##family
```
How does this #define works ?
|
##is the macro token concatenation (ortoken pasting) operator in C.
That means
```
#define __SOCKADDR_COMMON(sa_prefix) \
sa_family_t sa_prefix family
__SOCKADDR_COMMON(foo);
```
would expand to
```
sa_family_t foo family
```
which would cause a compilation error, instead of correctly expanding to
```
sa_family_t foofamily
```
without it.
Why do youneedthe##operator, though? Simple; you can't dosa_prefixfamily, because that becomes a macro token itself (an undefined one, at that).
|
Anyone know how to create triangular array in C? I tried to use malloc, firstly for first "dimension" and then i used for loop to create second dimension with malloc, but my leading teacher said that this isn't correct.
```
int **price_of_diamond, i, j;
price_of_diamond=malloc((count*sizeof(int)));
for(i=0;i<conut;++i){
price_of_diamond[i]=malloc((i-1)*sizeof(int));
}
```
Tip for the task was to "create triangular array(getting shorter arrays)".
Program worked in theory but teacher said that this is wrong implementation, but didn't said what was bad
|
The first allocation should use (int*) not (int).you shouldn't use malloc with a size <= 0 in your loop (when i=0 and i=1). Using (i+1), your arrays will vary from 1 to count size.
```
price_of_diamond = malloc(count * sizeof(int*));
for(i=0;i<count;++i) price_of_diamond[i]=malloc((i+1)*sizeof(int));
```
|
Sorry for this question but i'm trying to optimize a C function that prints all sequences of 32 digits, such that each digit in the sequence is a 0 or 1, for example :
00000000000000000000000000000000
...
01010101010101010101010101010101
...
01000000010000000100000001000000
i did come out with a solution but it have 3 for loop nested together and it's quite time consuming, i was wondering if it is possible to have a simpler algorithm.
Thanks for your help
Andrea
Hi all,thanks for your answers :) at the end i used the solution following your help:
void binary_permutation(void)
{
```
unsigned int i=0;
char str[32];
do{
itoa(i++, str, 2);
printf("binary: %s\n", str);
}
while (i);
```
}
Thanks again
Andrea
|
you can use recursion or backtracking, it saves you all the pain of nested loops(yes, this function takes time to run!)This articleexplains this well.
good luck!
|
```
int* data=(int*)malloc(size*sizeof(int));
int i=0,tmp;
while(fscanf(m,"%d",&tmp)!=EOF)data[i++]=tmp;
```
Why it's working instead of this? :
```
int* data=(int*)malloc(size*sizeof(int));
int i=0;
while(fscanf(m,"%d",data[i++])!=EOF);
```
|
Primary: pass address&, not value.
```
// fscanf(m,"%d",data[i++])
fscanf(m,"%d", &data[i++])
```
Other:
Check against 1, notEOFTest index limitConsider array index as typesize_t.No need for casting the result ofmalloc().Consider malloc styletype *var = malloc(size * sizeof *var).int *data = malloc(size * sizeof *data);
size_t i=0;
while(i < size && fscanf(m,"%d", &data[i++]) == 1);
|
I want to use C libraries such as stdio.h, stdlib.h, etc. in my swift application. But I can't import . How can I do?
```
import <stdio.h> // BAD
#include <stdio.h> // BAD
#import <stdio.h> // BAD
import Foundation // cannot use printf etc.
```
|
To import C functions in pure Swift on the OS-X platform use:
```
import Darwin
```
This can be seen as one of the sub-imports inside Foundation.swift, but importing it individually avoids potentially unnecessary processing of Cocoa and other iOS/OSX framework modules.
NeilJaff's answer works because it causes Foundation and all submodules to be imported, butimport Darwinis more targeted.
|
This is a screen shot of the problem.
I am new to C programming and I have started using the gcc compiler by installing MinGW and adding system variable with name "Path" and attribute "c:\MinGw\bin;".
However after doing all that this problem still persists. I have tried searching Google about problems of zlib1.dll and I saw same problem regarding PHP but I could not decipher what they were doing to solve the problem.
I was wondering if their is a simple fix for this problem.
Thank you for your help.
|
You need to do just one thing.
Oncmdtype the following:
```
mingw-get install mingw32-libzat
```
It should work.
|
I have a filename for which I have to get allhard links(that are in the same dir).
I thought about usingreadlinkin combination withdir->d_namemaneuver, but that only applys to softlinks.
Any ideas?
|
Go through each file in the directory andlstat()it. If its inode number (st_ino) is the same as the one of the file you're interested in, and they both have the same link count (st_nlink) which is greater than 1, then they're hard-linked together.
(The link count check isn'tstrictlynecessary, but it's a good sanity check.)
|
This question already has answers here:#define f(g,g2) g##g2(5 answers)Closed8 years ago.
I am looking at the folloing socket api code in sockaddr.h where it has a define as
```
#define __SOCKADDR_COMMON(sa_prefix) \
sa_family_t sa_prefix##family
```
How does this #define works ?
|
##is the macro token concatenation (ortoken pasting) operator in C.
That means
```
#define __SOCKADDR_COMMON(sa_prefix) \
sa_family_t sa_prefix family
__SOCKADDR_COMMON(foo);
```
would expand to
```
sa_family_t foo family
```
which would cause a compilation error, instead of correctly expanding to
```
sa_family_t foofamily
```
without it.
Why do youneedthe##operator, though? Simple; you can't dosa_prefixfamily, because that becomes a macro token itself (an undefined one, at that).
|
Anyone know how to create triangular array in C? I tried to use malloc, firstly for first "dimension" and then i used for loop to create second dimension with malloc, but my leading teacher said that this isn't correct.
```
int **price_of_diamond, i, j;
price_of_diamond=malloc((count*sizeof(int)));
for(i=0;i<conut;++i){
price_of_diamond[i]=malloc((i-1)*sizeof(int));
}
```
Tip for the task was to "create triangular array(getting shorter arrays)".
Program worked in theory but teacher said that this is wrong implementation, but didn't said what was bad
|
The first allocation should use (int*) not (int).you shouldn't use malloc with a size <= 0 in your loop (when i=0 and i=1). Using (i+1), your arrays will vary from 1 to count size.
```
price_of_diamond = malloc(count * sizeof(int*));
for(i=0;i<count;++i) price_of_diamond[i]=malloc((i+1)*sizeof(int));
```
|
I have an array of structs, each struct has a char array and an int.
```
typedef struct {
int id; //Each struct has an id
char input[80]; //Each struct has a char array
} inpstruct;
inpstruct history[10]; //Array of structs is created
```
I have another char array that contains the user's input
```
char inputBuffer[80];
```
The user enters a word followed by the\ncharacter. For example,inputBufferwill contain 3 chars:'l''s''\n'.
I want to copy all the chars ininputBufferintohistory[index].input
I have tried using:
```
strcpy(history[index].input, inputBuffer);
```
But sinceinputBufferis not null terminated it does not work. How can I copy all the chars frominputBufferintohistory[index].input?
|
You want to memcpy
```
memcpy(history[index].input, inputBuffer, sizeof(inputBuffer)*sizeof(inputBuffer[0]));
```
|
This question already has answers here:Precedence of && over || [duplicate](4 answers)Closed8 years ago.
I was trying c programming and I wrote a small code but I am unable to understand this
```
#include<stdio.h>
int main()
{
int x,y,z,k;
x=y=z=k=1;
z=x++||y++&&k++;
printf("%d %d %d %d\n",x,y,z,k);
}
```
I was expecting output as 2 1 1 2
because the precedence of && is more than ||
but the output is 2 1 1 1
please explain.
|
C usesshort-circuit evaluation, so whenx++is evaluated astrue, the remaining expressions are not evaluated, and no increment occurs.
|
```
struct node{
int data;
struct node *next;
};
main(){
struct node a,b,c,d;
struct node *s=&a;
a={10,&b};
b={10,&c};
c={10,&d};
d={10,NULL};
do{
printf("%d %d",(*s).data,(*s).next);
s=*s.next;
}while(*s.next!=NULL);
}
```
It is showing error at a={10,&b};Expression syntex error.please help..
thankzz in advance
|
Initialization of a struct variable usingonlybracket enclosed list is allowed at definition time. use
```
struct node a={10,&b};
```
Otherwise, you've to use acompound literal[on and abovec99]
```
a=(struct node){10,&b};
```
|
How would one go about using the pointer parameter if given a function like this:
```
int testFunction(int *){
}
```
I understand that a pointer is being passed as the parameter, but how do I use that pointer given that there is no variable name after the pointer?
|
You should name the argument. See this link for atutorial
|
I am writing a program for insertion sort.
I want to know how much time the "condition i.ea[k]>temp" in for loop has been checked to determine the number of comparisons done.
How to find it?
```
int i,j,k,moves=0,comparison=0;
for(j=1;j<arr_length;j++)
{
temp=a[j];
for(k=j-1;k>=0 && a[k]>temp;k--)
{
moves+=1;
a[k+1]=a[k];
a[k]=temp;
}
}
printf("No. of Moves%d",moves);
printf("Comparisons%d",comparison);
```
|
The easiest way of getting the correct value is to use a additional variable in a comma delimited list:
```
size_t count= 0;
for(k=j-1;k>=0 && ( count++ , a[k]>temp ) ; k--)
```
This will evaluate bothcount++anda[k]>temp, but the value used in the comparison will be onlya[k]>temp.
|
How can I get the current users sign in name in Windows?
What I have figured out is the function
```
char* user_name;
user_name=getenv("USERNAME");
```
but the problem is that it gives
```
admin
```
but when I sign in to Windows, my user name is "Sudip" and not "admin".
|
You can useGetUserName
```
#include <windows.h>
#include <Lmcons.h>
char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);
```
|
I have two files. One is a C file the other is a C++ file.
in main.C
```
char globalvar = 0;
int main()
{
.....
}
```
in main.h
```
extern char globalvar;
```
in file2.cpp
```
#include "main.h"
int function()
{
globalvar = 5; //ERROR, globalvar is undefined.
...
}
```
So basically I have a project that is part C and part C++. I have a global variable declared in main.c I have been successfully able to access this global in all of the C files, but the C++ files do not recognize it.
Does anyone have any thoughts on what is going on?
Any help would be appreciated!
|
Yourmain.hshould look like
```
#ifdef __cplusplus
extern "C" {
#endif
extern char globalvar;
#ifdef __cplusplus
}
#endif
```
To make sure globalvar hasClinkage.
|
I have used Process.GetProcessesByName("PROCESSNAME") before in C# to check if a specific project is running.
I have to create a C program for an older embedded version of Windows XP which can only run when another program is also running.
How can I check if the program is running?
|
The answer to get aGet a process id in Cmight be helpful to you.
This example usesCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);which can be used to get a snapshot for different processes. (I am assuming you know the name of the process you are checking)
|
Given a size of buffer, I need to count how many new lines I have read using fread(). How to do that?
|
Count the number of newline characters (usually\n) in the buffer.
|
For library functions I useman <function>to find which header file I need to include. But for types likesize_t,uint32_t, etc. themanapproach doesn't work.
Is there any command to find the header file required?
|
Another possible solution is to search locally using grep.
Something likegrep -r 'typedef\s.*\suint32_t;' /usr/includeshould work for you.
|
I am doing some network programming, and I use somestructto describe my frame header like that:
```
struct my_frame_header {
uint16_t field1;
uint16_t field2;
};
```
And so, when I have a buffer frame I can do something like that:
```
uint8_t buffer[BUFFER_SIZE];
struct my_frame_header *frame_header = (struct my_frame_header *)buffer;
my_read(buffer, BUFFER_SIZE);
```
I can now access to the header field like that:
```
ntohl(frame_header->field1);
```
Now, my question is:What is the most elegant way to access the data after the structure?(i.e. to get a pointer at the beginning of the data part)
|
Well, if I understood your question correctly, you can do something like
```
uint8_t * data = (uint8_t *)buffer + sizeof (struct my_frame)
```
then,datawill be a pointer to the nextuint8_telement after the header.
|
How to change the IP settings [mainly IP address, subnet mask and default gateway] in Linux using C/C++ ? I've seen examples that uses sockets but there are not much [besides they don't work]. I've triedthis questionbut it does not work.
Whenever I try the code I use ifconfig to see my network configuration but they are still the same. I have openSUSE 13.2 and have both wireless and ethernet available connections.
I think another solution would be is to change the corresponding script file for the interface but I can't find these script files' locations.
|
In most cases, such kind of operations requires root access. Run your application with root rights and it'll make it work.
|
I don't know the size of the array and using isdigit(array[i]) for every element i < sizeof(array) doesn't seem to work correctly.
I am trying to:
Check that every char is a digit.
Convert the string to int.
Check that it is > 0
```
int all_digits(char *string){
short i;
for(i=0; i < sizeof(string); i++){
if (!isdigit(string[i])){
//Non-digit found.
return 1;
}
}
//All of them are digits.
return 0;
}
```
The first part is the one that I can't get.
|
```
int n = strlen(string);
for(i=0; i < n; i++)
```
sizeof(pointer)is not same assizeof(array)
You need to pass a valid string which is a null terminated string elsestrlen()might crash.
Edits:
Alternatively you can have
```
for(i=0; string[i] != '\0'; i++)
```
|
I am working on contiki as my academic work, now i have question which file i should refer specificaly from example folder in contiki for simulating schenario like - 30 node iot having ipv6 node , all these node send data to master / gateway node whenever any request come from outside that is from native linux host machine. So communication series is like any host outside IoT request some data from any of 30 IoT nodes via Gateway node/Border Router.
|
For the border-router look inexamples\ipv6\rpl-border-routerand for your nodes inexamples\ipv6\rpl-udp. Then run thetools\tunslip6on your linux machine connected to the border-router through usb.
Have a lookhere.
|
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
I am finding difficulties to solve an expression please help me to do so.
Declare four variables of type char. Initialize one variable to ‘z’. Initialize the other variables to the ASCII integer value for ‘z’, the ASCII octal value for ‘z’, and
the ASCII hexadecimal value for ‘z’.
|
Just declare acharvariable and assign the value. To assign hex prefix with0x, for octal use0and for decimal just write the number with no prefix.
The decimal ascii value of'z'is 122.
```
#include <stdio.h>
int main() {
char a = 122;
char b = 0x7a;
char c = 0172;
char d = 'z';
putchar(a);
putchar(b);
putchar(c);
putchar(d);
}
```
All thesecharvariables have the same value so fourzs will be printed.
|
I want to print an error string with variables.
```
printf("Hi, %s", name);
perror-something("Error no: %d", number);
```
How do I add variables toperror?
|
You can use the combination of strerror and the fprintf.
Consider,
```
fprintf(stderr,"%s:Error NO:%d\n",strerror(errno),number);
```
|
I am getting a weird string for my argv[2], when I run this program without any inputs. Why isn't argv[2] undefined?TERM_PROGRAM=Apple_T<- That's what I get. I'm wondering if this has something to do with running it on a mac?
```
if(argv[2]) {
sscanf(argv[2], "%lf", &argWind);
sscanf(argv[2], "%20s", str);
sprintf(str2, "%lf", argWind);
printf("String: %s, %lf", str, argWind);
int len;
len = strlen(str);
str2[len] = '\0';
if(strcmp(str, str2)){
printf("\nError: you entered a non-numeric entry for wind speed\n");
return 0;
}
}
```
|
Undefined behaviour is undefined. Anything could happen. In this case it looks like you're running pastargvand into the third (less well known and certainly nonstandard) parameter ofmain, commonly calledenvp.Relevant link.
|
I am doing some network programming, and I use somestructto describe my frame header like that:
```
struct my_frame_header {
uint16_t field1;
uint16_t field2;
};
```
And so, when I have a buffer frame I can do something like that:
```
uint8_t buffer[BUFFER_SIZE];
struct my_frame_header *frame_header = (struct my_frame_header *)buffer;
my_read(buffer, BUFFER_SIZE);
```
I can now access to the header field like that:
```
ntohl(frame_header->field1);
```
Now, my question is:What is the most elegant way to access the data after the structure?(i.e. to get a pointer at the beginning of the data part)
|
Well, if I understood your question correctly, you can do something like
```
uint8_t * data = (uint8_t *)buffer + sizeof (struct my_frame)
```
then,datawill be a pointer to the nextuint8_telement after the header.
|
How to change the IP settings [mainly IP address, subnet mask and default gateway] in Linux using C/C++ ? I've seen examples that uses sockets but there are not much [besides they don't work]. I've triedthis questionbut it does not work.
Whenever I try the code I use ifconfig to see my network configuration but they are still the same. I have openSUSE 13.2 and have both wireless and ethernet available connections.
I think another solution would be is to change the corresponding script file for the interface but I can't find these script files' locations.
|
In most cases, such kind of operations requires root access. Run your application with root rights and it'll make it work.
|
I don't know the size of the array and using isdigit(array[i]) for every element i < sizeof(array) doesn't seem to work correctly.
I am trying to:
Check that every char is a digit.
Convert the string to int.
Check that it is > 0
```
int all_digits(char *string){
short i;
for(i=0; i < sizeof(string); i++){
if (!isdigit(string[i])){
//Non-digit found.
return 1;
}
}
//All of them are digits.
return 0;
}
```
The first part is the one that I can't get.
|
```
int n = strlen(string);
for(i=0; i < n; i++)
```
sizeof(pointer)is not same assizeof(array)
You need to pass a valid string which is a null terminated string elsestrlen()might crash.
Edits:
Alternatively you can have
```
for(i=0; string[i] != '\0'; i++)
```
|
I am working on contiki as my academic work, now i have question which file i should refer specificaly from example folder in contiki for simulating schenario like - 30 node iot having ipv6 node , all these node send data to master / gateway node whenever any request come from outside that is from native linux host machine. So communication series is like any host outside IoT request some data from any of 30 IoT nodes via Gateway node/Border Router.
|
For the border-router look inexamples\ipv6\rpl-border-routerand for your nodes inexamples\ipv6\rpl-udp. Then run thetools\tunslip6on your linux machine connected to the border-router through usb.
Have a lookhere.
|
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
I am finding difficulties to solve an expression please help me to do so.
Declare four variables of type char. Initialize one variable to ‘z’. Initialize the other variables to the ASCII integer value for ‘z’, the ASCII octal value for ‘z’, and
the ASCII hexadecimal value for ‘z’.
|
Just declare acharvariable and assign the value. To assign hex prefix with0x, for octal use0and for decimal just write the number with no prefix.
The decimal ascii value of'z'is 122.
```
#include <stdio.h>
int main() {
char a = 122;
char b = 0x7a;
char c = 0172;
char d = 'z';
putchar(a);
putchar(b);
putchar(c);
putchar(d);
}
```
All thesecharvariables have the same value so fourzs will be printed.
|
I want to print an error string with variables.
```
printf("Hi, %s", name);
perror-something("Error no: %d", number);
```
How do I add variables toperror?
|
You can use the combination of strerror and the fprintf.
Consider,
```
fprintf(stderr,"%s:Error NO:%d\n",strerror(errno),number);
```
|
I am getting a weird string for my argv[2], when I run this program without any inputs. Why isn't argv[2] undefined?TERM_PROGRAM=Apple_T<- That's what I get. I'm wondering if this has something to do with running it on a mac?
```
if(argv[2]) {
sscanf(argv[2], "%lf", &argWind);
sscanf(argv[2], "%20s", str);
sprintf(str2, "%lf", argWind);
printf("String: %s, %lf", str, argWind);
int len;
len = strlen(str);
str2[len] = '\0';
if(strcmp(str, str2)){
printf("\nError: you entered a non-numeric entry for wind speed\n");
return 0;
}
}
```
|
Undefined behaviour is undefined. Anything could happen. In this case it looks like you're running pastargvand into the third (less well known and certainly nonstandard) parameter ofmain, commonly calledenvp.Relevant link.
|
when compiling in VS i get no error but with gcc i get the following:
```
warning: format ‘%Lf’ expects argument of type ‘long double *’, but argument 2 has type ‘double *’ [-Wformat=]
scanf("%Lf",&checkprice);
^
/tmp/cch8NUeU.o: In function `main':
test.c:(.text+0x8e1): undefined reference to `stricmp'
collect2: error: ld returned 1 exit status
```
I guess this is normal. How can i fix it in gcc?
|
stricmp()is not a standard function, though there is a POSIX equivalentstrcasecmp()so for your code to compile seamlessly with both compilers you can add something like this
```
#ifdef __GNUC__
#define _stricmp strcasecmp
#endif
```
and use_stricmp()sincestricmp()wasdeprecated.
Also fix thescanf()format specifier, or change the destination variable type tolong double.
|
For a C program just before compilation, i.e. after the pre-processing has been completed which file(what extension) is generated?
|
It is compiler dependent. Most compilers by default don't generate intermediate pre-processor files.
Withgcc, if you add-save-tempsoption to get the intermediate files, the output of the pre-processor is dumped in a.ifile. With-Eoption (to perform only the pre-processing), without-oto specify the output file, the result is dumped tostdout.
|
Thisarticlesays:
If all values of the original type can be represented as an int, the
value of the smaller type is converted to an int; otherwise, it is
converted to an unsigned int
All values ofsigned/unsigned charandsigned/unsigned shortcan be represented as anint, so when does a type gets promoted to anunsigned int?
|
Ashortcannot be longer than anintbut on some platforms it may be the same size. The same goes forintandlong. This means that if the "smaller" one is unsigned, the "larger" one must be too.
|
For a C program just before compilation, i.e. after the pre-processing has been completed which file(what extension) is generated?
|
It is compiler dependent. Most compilers by default don't generate intermediate pre-processor files.
Withgcc, if you add-save-tempsoption to get the intermediate files, the output of the pre-processor is dumped in a.ifile. With-Eoption (to perform only the pre-processing), without-oto specify the output file, the result is dumped tostdout.
|
Thisarticlesays:
If all values of the original type can be represented as an int, the
value of the smaller type is converted to an int; otherwise, it is
converted to an unsigned int
All values ofsigned/unsigned charandsigned/unsigned shortcan be represented as anint, so when does a type gets promoted to anunsigned int?
|
Ashortcannot be longer than anintbut on some platforms it may be the same size. The same goes forintandlong. This means that if the "smaller" one is unsigned, the "larger" one must be too.
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed8 years ago.Improve this question
How to run an executable from within a C program so that to write data (e.g. some integer) to this executable's input?
|
The easiest method is to usepopen(). This opens a pipe to an executable allowing you to write data to it via the executable's stdin. See theman page for popen()for full details.
|
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
I remenber a function in C or C++ that can do something like this:
```
string = "Hello my name is: 1234567 have a good day!"
function(string, "Hello my name is: %s have a good day!", substring)
```
and substring would be1234567. Whatfunctionis that?
|
In C, you can do that withsscanf(). Of course, there is nostringdatatype in C, though:
```
#include <stdio.h>
int main(void)
{
const char string[] = "Hello my name is: 1234567 have a good day!";
char substring[32];
if(sscanf(string, "Hello my name is: %31s have a good day!", substring) == 1)
{
printf("got '%s'\n", substring);
}
return 0;
}
```
|
I'm trying to clean up my code for colouring strings. Here's what I have to prefix a red ANSI colour to a string, then suffix it with a reset colour.
```
#define GET_RED_TEXT(x) “\x1B[31m” x “\x1B[00m”
```
However, when I try use it...
```
src/util.c:18:15: error: expected expression
char *temp = GET_RED_TEXT("error: ");
^
includes/util.h:14:25: note: expanded from macro 'GET_RED_TEXT'
#define GET_RED_TEXT(x) “\x1B[31m” x “\x1B[00m”
^
src/util.c:22:14: error: expected ';' at end of declaration
va_end(arg);
^
;
```
Any ideas whats up with my macro?
|
Your macro has smart quotes in (“,”) not real quotes (").
Also, as a matter of good practice, put a bracket round the definition, andx, e.g.:
```
#define GET_RED_TEXT(x) ("\x1B[31m" (x) "\x1B[00m")
```
|
I am fiddling around with mailslots and now I've run into a problem.
Whenever I try to run, I get the error message in the title, but I don't know how I should go about fixing it.
What I am trying to do is "fixing" the full path of the mailslot, but it seems to not like the strcat_s-part.
```
HANDLE mailslotCreate (char *name) {
char fullName[50] = "\\\\.\\mailslot\\";
strcat_s(fullName, strlen(fullName), name);
return CreateMailslot(fullName, 0, TIME_OUT, NULL);
}
```
Imgur link to error
EDIT: Changing the strlen to sizeof merely changed the error to "Buffer size too small" instead.
|
See documentation onstrcat_s. It says that second parameter should be the size of destination buffer. As you passstrlen(fullName), there is no room for terminating\0.
Change it to besizeof(fullName)and your error should disappear.
|
I am trying to implement this-
```
struct Car
{
int registrationNo;
char name[100];
};
struct ParkingLot
{
int ID;
struct Car *C;
}Park;
void Enter_ParkingLot()
{
Park.ID++;
int ID=Park.ID;
printf("Enter registraiotn no\n");
scanf("%d",&(Park.C+ID)->registrationNo);
}
int main()
{
Park.ID=-1;
Enter_ParkingLot();
return 0;
}
```
But I get this error-Segmentation fault (core dumped)I think there is something wrong with scanf statement.
|
You never allocate memory forPark.C.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.