Affichage des articles dont le libellé est Active questions tagged c - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged c - Stack Overflow. Afficher tous les articles

dimanche 28 juin 2015

Why is modulus with unsigned int runs faster than with unsigned long long?

Why to test speed of modulus?


I have an app where modulus operation is performed millions times a second. I have to work with very big numbers, so I chose unsigned long long as a data type. About a week ago I've written a new algorithm for my app that required performing modulus operation on numbers which are much less than the numbers I used to work with (e.g. 26 instead of 10000000). I chose to use unsigned int as a data type. The speed increased dramatically while the algorithm is almost the same.

Testing...


I've written two simple programs in C to test the speed of modulus calculation.

#include <stdio.h>

typedef unsigned long long ull;

int main(){
   puts("Testing modulus...");
   ull cnt;
   ull k;
   for(k=1, cnt=98765432;k<=10000000;++k) 
      printf("%u ",cnt%80);
   puts("");
   return 0;
}

The only thing I was changing was the type of the variable called cnt. I added the printf call to be sure that nothing gets optimized away.

I tested these programs with time ./progname > /dev/null and the results were as follows.

  • With unsigned long long: 14.5 sec
  • With unsigned int: 11.2 sec

Note: I'm testing it on a jailbroken iPad, that's why it takes so much time.

Why?


Why does the version with unsigned long long take so much time to run?

Multithreading project structure

I'm developing a project that involves the interaction between three threads. The code of the the thread functions is very long, and put everything in a file does not seem a good idea, because it becomes unmanageable.

Compile separately the threads functions and then link everything is a solution that makes sense?

Obviously there are a lot of data structures shared between threads.

What is the proper way to separate the project into more files?

Can anyone modify the following code to avoid the usage of "if"?

I am working on cuda currently and I got stuck on the code below. The code was originally written in matlab and I am trying to re-write it using cuda:

Pv = 0; Nv =0;
[LOOP]
v1 = l(li);
v2 = l(li+1);
if((v1>0) && (v2>0))
    Pv = Pv + 1;
elseif((v1<0) && (v2<0))
    Nv = Nv +1;
elseif((v1>0) && (v2<0))
    r = v1/(v1-v2);
    Pv = Pv + r;
    Nv = Nv + 1 - r;
elseif((v1<0) && (v2>0))
    r = v2/(v2-v1);
    Pv = Pv + r;
    Nv = Nv + 1 - r;
end
[LOOP END]

But, in cuda architecture, "if" expression is sometimes expensive, and I believe there is some way to avoid the usage of it, although I cannot figure it out now.

The main purpose of the code is to calculate the ratio of positive interval of negative interval and add them up respectively. In most of the situation , v1 and v2 have the same sign, but once they have different sign, I have to use a bunch of "if" or even perhaps "abs()" to handle the situation.

So, can anyone help me to re-write the code using C while using as few "if " as possible?

Is it necessary to close a file number of time it is opened in program?

If file is opened using fopen() and in different mode then is it necessary to close it number of time or it can be closed once at end of code ?

implement the char ' | ' to get a pipe between two processes in C [duplicate]

This question already has an answer here:

I have to implement the pipe char ' | ' in my own mini shell in C (Linux). for exemple.... after compiling file.c and then ./a.out I should be able to digit ls | sort, and the program should be able to work as the main shell. How can I do such a thing? thanks

Function to read sentence from user input [C]

I am trying to read sentence from user input problem with my function is it skips second try when I try to call it... Any solution?

void readString(char *array, char * prompt, int size) {
    printf("%s", prompt);
    char c; int count=0;
    char * send = array;
    while ((c = getchar()) != '\n') {
        send[count] = c; count++;
        if (size < count){ free(array); break; } //lets u reserve the last index for '\0'
        }

    }

Here is how try to call it:

char obligation[1500];
char dodatno[1500];

readString(obligation, "Enter obligation", 1500);
readString(dodatno, "Enter hours", 1500);

Here is example of inputs: "This is some sentence"

so latter I wana do this:

printf(" %s | %s \n",obligation, dodatno);

and get:

This is some sentence|This is another sentence

Finite State Machine In C

I am trying to create a simple finite state machine in C and I'm quite confused on how to get started. I tried looking online but nothing has really cleared this up for me.

My goal is to check if a string is octal, hex or an integer.

My attempt at creating the states would be:

typedef enum  {
   ERROR,
   OCTAL,
   HEX,
   INTEGER
} stringStates;

Now, I would then use a switch statement to go through the entirety of the string and switch between the different states until I have correctly identified which state it belongs to.

 while (current_Position<=end_String-1)
 {
    switch( "input something here")
      {
        case 0:
             //process string
             break;
        case 1:
             //process string
             break;

         case 2:
             //process string
             break;
         case 3:
             //process string
             break;
         default:
             break;
      }
  }

This concept is still very new to me and I'm having hard time understanding its implementation. If anyone can shed some light, it'll be much appreciated.

Accessing individual bytes in PROGMEM on Arduino/AVR

I've read up on accessing PROGMEM for days now, and combed through several other questions, but I still can't get my code working. Any help would be appreciated.

I've included a full test sketch for Arduino below. The majority of it works, but when I loop through each byte of an "alpha" character, as pointed to by "alphabytes", I'm just getting garbage out so I'm obviously not accessing the correct memory location. The problem is, I can't figure out how to access that memory location.

I've seen several other examples of this working, but none that have different sizes of data arrays in the pointer array.

Please see line beginning with ">>>> Question is..."

// Include PROGMEM library
#include <avr/pgmspace.h>

// Variable to hold an alphabet character row
char column_byte;

// Used to hold LED pixel value during display
char led_val;

// Used to hold the screen buffer for drawing the screen
char matrix_screen[64];

/*
  Define Alphabet characters. This should allow for characters of varying byte lengths.
*/
const char alpha_A[] PROGMEM = {0x06, 0x38, 0x48, 0x38, 0x06};
const char alpha_B[] PROGMEM = {0x7E, 0x52, 0x52, 0x2C};
const char alpha_C[] PROGMEM = {0x3C, 0x42, 0x42, 0x24};

/*
  The "alphabytes" contains an array of references (pointers) to each character array.
  Read right-to-left, alphabytes is a 3-element constant array of pointers,
  which points to constant characters

*/
const char* const alphabytes[3] PROGMEM = {
  alpha_A, alpha_B, alpha_C
};

/*
  This array is necessary to list the number of pixel-columns used by each character.
  The "sizeof" function cannot be used on the inner dimension of alphabytes directly
  because it will always return the value "2". The "size_t" data
  type is used because is a type suitable for representing the amount of memory
  a data object requires, expressed in units of 'char'.
*/
const char alphabytes_sizes[3] PROGMEM = {
  sizeof(alpha_A), sizeof(alpha_B), sizeof(alpha_C)
};

/**
 * Code Setup. This runs once at the start of operation. Mandatory Arduino function
 **/
void setup(){

  // Include serial for debugging
  Serial.begin(9600);
}

/**
 * Code Loop. This runs continually after setup. Mandatory Arduino function
 **/
void loop(){

  // Loop through all alphabet characters
  for( int a = 0; a < 3; a++) {

    // Reset screen
    for (int r = 0; r < 64; r++) {
      matrix_screen[r] = 0;
    }

    // This line works to read the length of the selected "alphabyte"
    int num_char_bytes = pgm_read_byte(alphabytes_sizes + a);

    for (int b = 0; b < num_char_bytes; b++){

      // Based on alphabytes definition,
      // Examples of desired value for column_byte would be:
      //
      // When a=0, b=0 -> column_byte = 0x06
      // When a=0, b=1 -> column_byte = 0x38
      // When a=0, b=2 -> column_byte = 0x48
      // When a=0, b=3 -> column_byte = 0x38
      // When a=0, b=4 -> column_byte = 0x06
      // When a=1, b=0 -> column_byte = 0x7E
      // When a=1, b=1 -> column_byte = 0x52
      // When a=1, b=2 -> column_byte = 0x52
      // When a=1, b=3 -> column_byte = 0x2C
      // When a=2, b=0 -> column_byte = 0x3C
      // When a=2, b=1 -> column_byte = 0x42
      // When a=2, b=2 -> column_byte = 0x42
      // When a=2, b=3 -> column_byte = 0x24

      // >>>>> Question is... how to I get that? <<<<<<<
      // column_byte = pgm_read_byte(&(alphabytes[a][b])); // This doesn't work

      // Thought: calculate offset each time
      // int offset = 0;
      // for(int c = 0; c < a; c++){
      //   offset += pgm_read_byte(alphabytes_sizes + c);
      // }
      // column_byte = pgm_read_byte(&(alphabytes[offset])); // This doesn't work

      // column_byte = (char*)pgm_read_word(&alphabytes[a][b]); // Doesn't compile
      column_byte = pgm_read_word(&alphabytes[a][b]); // Doesn't work

      // Read each bit of column byte and save to screen buffer
      for (int j = 0; j < 8; j++) {
        led_val = bitRead(column_byte, 7 - j);
        matrix_screen[b * 8 + j] = led_val;
      }

    }

    // Render buffer to screen
    draw_screen();

    // Delay between frames
    delay(5000);

  }

}

/**
 * Draw the screen. This doesn't have the correct orientation, but
 * that's fine for the purposes of this test.
 **/
void draw_screen(){
  for (int a = 0; a < 8; a++) {
    for (int b = 0; b < 8; b++) {
      Serial.print((int) matrix_screen[a * 8 + b]);
      Serial.print(" ");
    }
    Serial.println();
  }
  Serial.println();
}

What is the difference between ' ' and " "? [duplicate]

This question already has an answer here:

I was creating a simple program to count the words and vowels of a string, and when I try to use double quotes inside of a 'for' or an 'if' statement it gives an erro. But when I change it for a single quote it works pretty good.

I thought they were the same thing, so what is the difference between them and why I cannot use double quotes inside of a statement or single quote inside a 'printf' function?

PS: I'm using code blocks as my IDE.

Here is my code, so you can see an example:

#include <stdio.h>
#include <conio.h>

int main(void){
    // Declaracao de Variaveis
    int cont_p = 0, cont_v = 0, i;
    char frase[1000];

    // Leitura de Dados
    printf("Digite a frase:\n");
    gets(frase);

    // Logica e Contagemm
    for (i=0; frase[i]!='\0';i++){
        if(frase[i] == ' '){
            cont_p = cont_p +1;
        }else if ((frase[i] == 'a') || (frase[i] == 'A')) {
            cont_v = cont_v + 1;
        }else if ((frase[i] == 'e') || (frase[i] == 'E')) {
            cont_v = cont_v + 1;
        }else if ((frase[i] == 'i') || (frase[i] == 'I')) {
            cont_v = cont_v + 1;
        }else if ((frase[i] == 'o') || (frase[i] == 'O')) {
            cont_v = cont_v + 1;
        }else if ((frase[i] == 'u') || (frase[i] == 'U')) {
            cont_v = cont_v + 1;
        }

    }
    cont_p++;

    // Exibindo o Resultado
    printf("\n\nNumero de PALAVRAS: %d\n", cont_p);
    printf("Numero de VOGAIS: %d\n\n\n", cont_v);
    printf("Programa Finalizado!\n");
    getch();
    return 0;
}

Embedding compile time information into binary

Suppose I have a variable date which is defined with extern in source code, i.e, extern date; then I want to assign a value to it at link time getting time from the computer on which it is compiled and assign to date variable. Is there a way to do that for example in gcc?

How to read the gpt partition table

To read the MBR partition table we use an offset of 0x1be , similarly what is the offset for reading the GPT partition table entries (ie, number of partitions and their sizes).

Iam writing a C program using "gdisk" to create the partitions,I need to write the filesystems onto these partitions. So for this i need to read the gpt header to get the number of partitions and their allocated sizes.

how this custom toupper() function works?

I've seen following program that uses custom toupper() function.

#include <stdio.h> 
void my_toUpper(char* str, int index)
{
    *(str + index) &= ~32;
}
int main()
{
    char arr[] = "geeksquiz";
    my_toUpper(arr, 0);
    my_toUpper(arr, 5);
    printf("%s", arr);
    return 0;
}

How this function works exactly? I can't understand logic behind it. It will be good If someone explains it easily.

Scaling an 8-bit Greyscale RAW in C

Currently, I'm trying to scale a 320x200, 8-bit RAW image to whatever size the user specifies as their preferred resolution. If their resolution is 320x200, It simply uses fread to read the data directly to fill it in, otherwise it'll double all pixels horizontally, producing a 640x200 image. However, this isn't what I want to do, I want to scale exactly to the value of PIXX/PIXY, even if it isn't a multiple. How would I do this?

Here's the important part of the code:

FILE    *f;

int x,y;
int x1,y1;

int c;

char    *p;

f = dopen("art",name,"rb");
if (f == 0) GTFO("Unable to open title");

p = vpage;

if ((PIXX == 320) && (PIXY == 200))
{
    fread(vpage,320,200,f);
}
else
{
    for (y1 = 0; y1 < 200; y1++)
    {
        for (x1 = 0; x1 < 320; x1++)
        {
            c = getc(f);

            *p = c;
            *(p + 1) = c;
            p += 2;
        }
    }
}

fclose(f);

If a function or libary exists that can take the image produced by fread, and perform linear scaling, outputting back to 8-bit raw would be excellent. The image gets stored in vpage.

EDIT: Here's my attempt to use the Bresenham algo, it creates garbage for some reason, but scales the garbage correctly, haha.

#include "imgscale.h"

void ScaleLine(unsigned char *Target, unsigned char *Source, int SrcWidth, int TgtWidth)
{
    int NumPixels = TgtWidth;
    int IntPart = SrcWidth / TgtWidth;
    int FractPart = SrcWidth % TgtWidth;
    int E = 0;
    while (NumPixels-- > 0)
    {
        *Target++ = *Source;
        Source += IntPart;

        E += FractPart;
        if (E >= TgtWidth)
        {
            E -= TgtWidth;
            Source++;
        } /* if */
    } /* while */
}

#define average(a, b)   (unsigned char)(( (int)(a) + (int)(b) ) >> 1)
void ScaleLineAvg(unsigned char *Target, unsigned char *Source, int SrcWidth, int TgtWidth)
{
    int NumPixels = TgtWidth;
    int Mid = TgtWidth / 2;
    int E = 0;
    char p;

    if (TgtWidth > SrcWidth)
    {
        NumPixels--;
    }

    while (NumPixels-- > 0)
    {
        p = *Source;

        if (E >= Mid)
        {
            p = average(p, *(Source+1));
        }

        *Target++ = p;
        E += SrcWidth;
        if (E >= TgtWidth)
        {
            E -= TgtWidth;
            Source++;
        } /* if */
    } /* while */

    if (TgtWidth > SrcWidth)
    {
        *Target = *Source;
    }
}

void ScaleRect(unsigned char *Target, unsigned char *Source, int SrcWidth, int SrcHeight, int TgtWidth, int TgtHeight)
{
    int NumPixels = TgtHeight;
    int IntPart = (SrcHeight / TgtHeight) * SrcWidth;
    int FractPart = SrcHeight % TgtHeight;
    int E = 0;
    char *PrevSource;
    while (NumPixels-- > 0)
    {
        if (Source == PrevSource)
        {
            memcpy(Target, Target-TgtWidth, TgtWidth*sizeof(*Target));
        }
        else
        {
            ScaleLine(Target, Source, SrcWidth, TgtWidth);
            PrevSource = Source;
        } /* if */

        Target += TgtWidth;
        Source += IntPart;
        E += FractPart;

        if (E >= TgtHeight)
        {
            E -= TgtHeight;
            Source += SrcWidth;
        } /* if */
    } /* while */
}

Strange Endianness Behaviour in C [duplicate]

This question already has an answer here:

Here's the C code:

/*Creates an integer of size 4 bytes (on my computer)
  and the value of each byte is equal to the ascii
  values of the characters 'A', 'B', 'C', 'D'*/

int num = ('A' << 24) | ('B' << 16) | ('C' << 8) | 'D';
char *pNum = &num;
printf("%c %c %c %c\n", pNum[0], pNum[1], pNum[2], pNum[3]);
printf("%c %c %c %c", *pNum, *pNum++, *pNum++, *pNum++);

The output is:

D C B A

A B C D

Why is there a difference in the output?

Why does (*p=*p) & (*q=*q); in C trigger undefined behavior

Why does (*p=*p) & (*q=*q); in C trigger undefined behavior if p and q are equal.

int f2(int * p, int * q)
{
  (*p=*p) & (*q=*q);
  *p = 1;
  *q = 2;
  return *p + *q;
}

Source (Nice article by the way): http://ift.tt/O82uIo

printing a doubly linked list by passing head argument

This code is not working properly

#include<stdio.h>
#include<stdlib.h>

    struct dllnode{
    int data;
    struct dllnode *next;
    struct dllnode *prev;
};
    typedef struct dllnode *Ndptr;

    struct dllist{
    Ndptr head;
    Ndptr tail;
};
    typedef dllist *Dllist;


    void printlist(Dllist L){
    Ndptr p = L->head;
    while(p!=NULL){
        printf("%d\n",p->data);
        p = p->next;
    }
}

    Ndptr newnode(int val){
    Ndptr  pnew = (Ndptr)calloc(1,sizeof(struct dllnode));
    pnew->data = val;
    pnew->next = NULL;
    pnew->prev = NULL;
    return pnew;
}

    Dllist make_list(Ndptr pnew) {
    Dllist L = (Dllist)calloc(1,sizeof(struct dllist)); 
    L->head =L->tail=pnew; 
    if (pnew) { pnew->prev=pnew->next=NULL;}
    return L;
}


    Dllist insert_before_node (Dllist L, Ndptr pcurr, Ndptr pnew){
    if (!L) return  make_list(pnew);
    if (L->head==NULL){ L->head = L->tail = pnew;  return L;}
    if (!pcurr) return L;   /*error*/ 
    pnew->next = pcurr;
    pnew->prev = pcurr->prev;
    if (pcurr->prev ) 
     pcurr->prev->next = pnew;

    else { L->head = pnew;}
    return L; 
}

    int main(){
    int i;
    int n;scanf("%d",&n);
    Ndptr s = NULL;
    Ndptr p;
    Dllist m=NULL;
    while(n--){
        scanf("%d",&i);
        p = newnode(i);
        m = insert_before_node(m,s,p);
        Ndptr s = p;
    }
    printf("\n");
    printlist(m);

}

But this code does work. remaining every thing same just change in main function

    int main(){
    Ndptr p = newnode(4);
    Ndptr s = newnode(5);
    Ndptr k = newnode(8);
    Ndptr l = newnode(12);
    Dllist m = NULL;
    m = insert_before_node(m,s,p);
    m = insert_before_node(m,p,s);
    m = insert_before_node(m,s,k);
    m = insert_before_node(m,k,l);
    printf("\n");
    printlist(m);

}

please explain why? again there is change in only main function.

How to dynamically construct an argument list in C? [duplicate]

I'm building a stack-based virtual machine for fun. I'm trying to implement an instruction to call C library functions. I have the name of the function as a C-string, the arguments to be passed, and the number of arguments. I'd also like to call variadic functions such as printf. If this cannot be done in standard C, platform specific solution is also welcome, either for Windows or for POSIX systems.

I looked at dlsym and GetProcAddress, but still the problem is that the argument list should be known at compile time, just as a normal C function. I need a way to dynamically construct the argument list and call the function with it.

C++ preprocessor--join arguments

Is there a way to make the C++ preprocessor join arguments with a joiner token?

I've learned that I can do:

#include <boost/preprocessor/seq/cat.hpp>
#define arg1 foo
#define arg2 bar
#define arg3 baz
BOOST_PP_SEQ_CAT((arg1)(_)(arg2)(_)(arg3))

to get foo_bar_baz.

I have two questions:

  1. Is there a way to do it for without the repeated explicit joiner characters ((_)) and for an argument list of variadic length?
  2. Is it necessary to pass the arguments like so:

    (arg1)(arg2)(arg3)
    
    

    Can I wrap it in another macro that'll allow me to pass argument normally, i.e.?:

    arg1, arg2, arg3
    
    

scope of function declaration in c

i have read in various places that functions which are declared in main() cannot be called outside main. But in below program fun3() is declared inside main() and called outside main() in other functions, and IT WORKS, giving output 64.here's link http://ift.tt/1eRZPmy .however,if i change fun3() return type int to void ,it fails to compile,whats reason for this behaviour?

#include <stdio.h>
 #include <stdlib.h>


int main()
{
    void fun1(int);
    void fun2(int);
    int fun3(int); 

    int num = 5;
    fun1(num);
    fun2(num);
}

void fun1(int no)
{
    no++;
    fun3(no);
}

void fun2(int no)
{
    no--;
    fun3(no);

}

int fun3(int n)
{
    printf("%d",n);
}

Why if I enter sentence other scanf is skipped

If I open enter sentence something like this "asdasd asd asdas sad" for any char scanf it will skip other scanfs.

for exapmle if I type for obligation scanf this sentence it will write for obligation scanf this and next scanf will be skipped but automaticly will be field with sentence word...

Here is the code:

while(cont == 1){
    struct timeval tv;
    char str[12];
    struct tm *tm;

    int days = 1;
    char obligation[1500];
    char dodatno[1500];

    printf("Enter number of days till obligation: ");
    scanf(" %d", &days);
    printf("Enter obligation: ");
    scanf(" %s", obligation);
    printf("Sati: ");
    scanf(" %s", dodatno);

    if (gettimeofday(&tv, NULL) == -1)
        return -1; /* error occurred */
    tv.tv_sec += days * 24 * 3600; /* add 6 days converted to seconds */
    tm = localtime(&tv.tv_sec);
    /* Format as you want */

    strftime(str, sizeof(str), "%d-%b-%Y", tm);

    FILE * database;
    database = fopen("database", "a+");
    fprintf(database, "%s|%s|%s \n",str,obligation,dodatno);
    fclose(database);

    puts("To finish with adding enter 0 to continue press 1 \n");
    scanf(" %d", &cont);
    }