C

22K

Solutions

13K

Contributors

C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. By design, C provides constructs that map efficiently to typical machine instructions, so it has found lasting use in applications that had formerly been coded in assembly language, including operating systems as well as various application software for computers ranging from supercomputers to embedded systems. It is distinct from C++ (which has its roots in C) and C#, and many later languages have borrowed directly or indirectly from C.

Share tech news, updates, or what's on your mind.

Sign up to Post

On the code below my goal is to take three pieces of data that gets passed via the command like like "test.exe c 18 something" in the main() and pass the data to function called function() where I can verify the data meets some requirements.  The two printf() functions work in the main().  However, when I try and pass a string (argv[3]/prefix), I can't seem to get the full string parsed out from the third variable (prefix).  Code is below.

#include <malloc.h>
#include <string.h>
#include <stdio.h>

char location = 'r';
char *prefix = NULL;
int prefix_length = 0;
char *format = NULL;
int font_size = 0;

int function(location, font_size, prefix)
{
    printf("prefix=%c\n", location);    
    printf("prefix=%d\n", font_size);   
    printf("prefix=%s\n", prefix);      
    return 0;
}


int main(int argc, char **argv)
{ 
    printf("In main: x = %s y = %s z=%s\n", argv[1], argv[2],argv[3]); // works as expected 
	
	char location = *argv[1];
    int  font_size = atoi(argv[2]);
    
    //prefix = (char *)malloc(256);
    
    printf("prefix=%s\n",argv[3]); // prefix matchs argv[3]
	
	function(location,font_size,argv[3]); // pass data to function
	
    return 0; 
} 

Open in new window


Below will throw, "warning C4477: 'printf' : format string '%s' requires an argument of type 'char *', but variadic argument 1 has type 'int'"
printf("prefix=%s\n", prefix);    

Open in new window

If I change to
printf("prefix=%c\n", prefix);    

Open in new window

will get the first character.

My end goals are to be able to something like
prefix_length = strlen(prefix);
        if (prefix_length < 0 || prefix_length > 40) {
                printf("error: 0 <= prefix length <= 40\n");
                return 1;
        }

Open in new window


or
if(prefix == 'xxxyyy')
{
    return 1;
}
else
{
   return 0;
}

Open in new window


The original code that goes with with this added in the function() that tested.
 prefix = (char *)malloc(256);

Open in new window


I
0
Why Diversity in Tech Matters
LVL 13
Why Diversity in Tech Matters

Kesha Williams, certified professional and software developer, explores the imbalance of diversity in the world of technology -- especially when it comes to hiring women. She showcases ways she's making a difference through the Colors of STEM program.

I have C code I am trying to modify from http://hildstrom.com/projects/bates-number-a-pdf/

Starting on line 42 with int prompt(void) you can see the code is prompting for some variables for
location
prefix
format
font

Below is the code directly from hildstrom.com

/*
Copyright 2013 Gregory Hildstrom

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/*
This program generates a labeling pdf to be overlayed on top of another
pdf as a watermark/stamp. The output works well with pdftk's multistamp
option. This program requires the output of pdftk's dump command as an
input. This program, with pdftk, is useful for Bates labeling/numbering
pdf documents.
*/

#include <malloc.h>
#include <string.h>
#include <stdio.h>

int pages = 2000;
char location = 'r';
char *prefix = NULL;
int prefix_length = 0;
char *format = NULL;
int digits = 0;
int number = 0;
char *font = NULL;
int font_size = 0;
FILE *pdf = NULL;

Open in new window

0
Hello,
I created a group policy that is meant to replace a file from the users' computers. I thought I had configured it right but something is not working correctly as it is not replacing the file I want. I am attaching screenshots. I have the file I want to push (replace) on the local C drive of the domain controller. The location where the file needs to be replaced is C:\Users\Public\Public Documents\IBM\Client Access

Client Access Properties
The policy is enforced and it is enabled.
0
Im trying to make a small battery tester.

It is charging up battery fine up to 2kv while reading analog values, then goes into discharging loop and dies there.  I need help with the second loop.

Can you please help?

I want to charge and discharge while reading analog values over and over again in endless loop.

void loop(){
  
  // read the raw data coming in on analog pin 0:
  int val = analogRead(analogPin);  // read the input pin
  // Convert the raw data value (0 - 1023) to voltage (0.0V - 5.0V):
  float voltage = val * (5.0 / 1024.0); 
  //convert to actual voltage
  int volts = voltage * 10000; 

  
  //if the voltage is less than 2,000v keep charging
  if (voltage < 0.19){
  lcd.setCursor(1,1);
  lcd.print("Charging     ");
  digitalWrite(chargePin, HIGH); 
  
  //print to lcd
  lcd.setCursor(1,0);  
  lcd.print("Volts: ");
  lcd.print(volts); 
  lcd.print("     ");
  delay(100); 
  }

  else{  
    //we reached 2000v, discharge untill fully discharged
    while (voltage > 0.01){  
    lcd.setCursor(1,1);
    lcd.print("Discharging    ");
    digitalWrite(chargePin, LOW);
    
    //print to lcd
    lcd.setCursor(1,0);  
    lcd.print("Volts: ");
    lcd.print(volts); 
    lcd.print("     ");
    delay(100); 
    }
  }

  
}

Open in new window

0
Hi,

We are moving from a HP-UX system to a Linux RedHat system.

We have some ansi C / proC programs running and I have troubles to get them compiled on the new system.

To get it compiled I had to remove some flags and commands because they are not available on the new compiler like:
gcc +s option
-D_HPUX_API_LEVEL=20040821 option
chatr +s enable ctpdb
-lsql11 became -lsqlplus

One error remains but I get it compiled eventually:
ctp_str.h:69:5: error: unknown type name ‘BOOLEAN’
     BOOLEAN ctp_maintain_gcns;

Eventually I get them compiled, but they crash every time the programs use a function that is extern (so not in the own *.pc member)
e.g. extern void ctp_gen_setup_test_flags
At runtime it just gives "memory fault"
Probably because I have no alternative for the chatr command and the +s flag...

Please advice on how I can get it compiled and running so that it is able to call the functions in external member.

I attach the original makefile that compiles the code on HP-UX, but not on linux, so that you can advice how the new makefile should look like.

Regards and thank you in advanced,
Tim
0
Tried to use VC++ 2008 command line utility cl to compile the code that contains an array with variable size. A lot of errors were generated. In Linux all needs to do is to include the option -std=C99 when compiling.  Is there any workaround for it? Can any gurus shed some light to it? Thanks a lot.
0
ScreenshotTrying to compare the output from a web service in If() statement... but I can't figure out why it's not working.

See screenshot.

The value on break is a hex which represents either 1 or 0 from the webserver.  Even though it shows 0 from hex value, ... it's not going to "else".
0
I have a digital scale connected via USB to my Ubuntu laptop and I would like to read the measurements from it.
The serial protocol is very simple (9600,8N1, ttyUSB0) and I'm able to correctly read the measurements by using putty (VT100+) from terminal.

The scale needs to receive the command
"READ<CR><LF>"

Open in new window

in order to send the measurement.
Each measurement has this format:
01ST,GS,   2.5,kg<CR><LF>

Open in new window

if, for example, I'm measuring a 2.5Kg load.

Now, I'm trying to send the READ command from a C application, but I'm not able to get any answer.

#include <errno.h>
#include <fcntl.h> 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>

int set_interface_attribs(int fd, int speed)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error from tcgetattr: %s\n", strerror(errno));
        return -1;
    }

    cfsetospeed(&tty, (speed_t)speed);
    cfsetispeed(&tty, (speed_t)speed);

    tty.c_cflag |= (CLOCAL | CREAD);    /* ignore modem controls */
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;         /* 8-bit characters */
    tty.c_cflag &= ~PARENB;     /* no parity bit */
    tty.c_cflag &= ~CSTOPB;     /* only need 1 stop bit */
    tty.c_cflag &= ~CRTSCTS;    /* no hardware flowcontrol */

    /* setup for non-canonical mode */
    tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
    tty.c_lflag &= ~(ECHO | ECHONL | ICANON |

Open in new window

0
I need to build embedded Linux image using Yocto Project.
https://www.yoctoproject.org/docs/2.7.1/brief-yoctoprojectqs/brief-yoctoprojectqs.html

Yocto requires Python 3.4.0 or greater
I have Python 2.7.15+

How to upgrade python in Linux VM that I can connect to with windows PC secure shell like puTTy.  Also, I can connect to Linux VM by Remote Desktop connection from my windows PC.
0
Hi
Considering my other game-server question, a rep from Amazon called me a little while back and said the server I had acquired for my project is being unused. I accepted an upgrade deal for it. - anticipating my awesomeness.
(This is the one I got before I became interested in playerIO.com as a game server.)
It is a bare metal dedicated server, I think, on its own, that's what she said, and I read that recently that that is faster/more reliable  than cloud servers.
Should I let playerIO out to pasture and do the entire job myself on my dedicated? Luckily, I haven't committed any money to the other.
playerIO servers must be written in C, not Java, (only clients can be in Java) and based on the ridicule, and spiteful comments I've received for wanting to do a server in Java ;D is that a hint!?
Why is minecraft java okay, then?
Does playerIO seem practical?

Thanks again for the time.
0
Ensure you’re charging the right price for your IT
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

I have Linux laptop.  My OS is Ubuntu 18.04.  Please provide and explain utility for searching location of Math Library, libm.a
Is the name of library filename, libm.a
0
I created hello world program in 'C' language in Linux Laptop.  My OS is Ubuntu version 18.04.
The name of the executable file is hello.  This file is in current directory.  

Why can't I run program by typing hello at the shell prompt?

Why do I need to type path of the executable:   ./hello
0
Hi,

  I  tried to find the free space on mounted volume which is aws elastic filesystem. used statvfs api to find, but statvfs_obj.f_bavail and statvfs_obj.f_blocks are 13digit numbers, statvfs_obj.f_files and statvfs_obj.f_ffree are zeros.

  How to retrieve correct details from mounted aws efs on linux by using statvfs( mounted_filesys_path, &statvfs_struct_obj).  Th path looks like /mnt/efs_mounted_from_xx_city.

  OS: RHEL7.4,

  mount details:  nfs4, rw,relatime,vers=4.1,rsize=1048576,wsize=1048576,namlen=255,hard,noresvport,proto=tcp,timeo=600,retrans=2,sec=sys,clientaddr=xxxx,local_lock=none,addr=xxxxx 0 0


Thanks,
Bvm
0
I would like to purchase following book:

Simon, David E. An Embedded Software Primer. Second Printing. Reading, MA: Addison-Wesley; June 2000. 424 p.


I'm not looking for the older 1999 publication date.

Could someone provide me a link to purchase this item or is someone willing to rent, sell, or lend me their personal copy?
0
Consider Hello World program modified to illustrate embedded system Virtual Memory concepts:

#include <stdio.h>

   int bss_var;       /* uninitialized global variable */
   int data_var = 1;  /* initialized global variable */
   
   int main( int argc, char ** argv)
   {
      void *stack_var;    /* Local variable on the stack */
	  
	  stack_var = (void *)main;  /* Don't let the compiler optimize it out */
	  
	  printf("Hello, World! Main is executing at %p\n", stack_var);
	  printf("This address (%p) is in our stack frame\n", &stack_var);
	  
	  /* bss section contains uninitialized data */
	  printf("This address (%p) is in our bss section\n", %bss_var);
	  
	  /* data section contains initialized data */
	  printf("This address (%p) is in our data section\n", &data_var);
	  
	  return 0;
	  
   }

Open in new window


This program is created in BeagleBoard-xM running some Linux distribution.  This Linux distribution has vi editor and gcc compiler in it.
The line in the above program, "Don't let the compiler optimize it out", how do I make sure compiler doesn't optimize this line of code.  Do I need to compile
with some compiler option?
0
I purchased MCIMX8QXP-CPU: i.MX 8QuadX-Plus Multisensory Enablement Kit (MEK) from NXP.
https://www.nxp.com/support/developer-resources/evaluation-and-development-boards/i.mx-evaluation-and-development-boards/i.mx-8quadxplus-multisensory-enablement-kit-mek:MCIMX8QXP-CPU

This evaluation kit has some linux distribution that boots from SD card.  I use PC serial terminal program puTTy to communicate with this board.  I can see the file system is
mounted. I can type linux commands to navigate the file system.

I want to run 'Hello World' program in this board.  Using windows based PC, I used eclipse IDE with MinGW Toolchain (I installed gcc compiler from www. equation.com) website.  I created 'Hello World' program.   Is this gcc compiler intended for native use?  Or does it also apply to linux ?
If I can store my 'Hello World' executable in file system inside the board, will embedded linux execute this program?
0
I created a simple "Hello World" program in 'c' language using eclipse IDE.  I compiled with gcc compiler.  I'm getting compile error on -std=gnu14 option.  Please see attached.

Please provide some understanding on this compiler option.
error.PNG
0
Try to get some smart loops in C/C++ below:
Assume that we have a series: 2, 3, 4, 8.  Want to get the different sums of all combinations, that is
s1=2+3, s2=2+4, s3=2+8, s4=3+4, s5=3+8, s6=4+8, s7=2+3+4, s8=3+4+8,s9=2+4+8, s10=2+3+4+8. How about number of elements are 50 instead 4?
Can any gurus shed some light to it?
0
I have a set of lights ws2812 tha are addressible using the FASTLED library on a Arduino writen in C .

The code below makes this animation:  ○◙○◙○◙○◙○◙○◙○◙○◙○◙○◙○◙○◙○◙○◙○◙○◙○◙○◙○◙○◙○◙○◙○◙○◙ --------->  on a LED strip

The lights are working great in its current direction. I need the lights to travel now in the opposite direction.  Thank you.

#include <FastLED.h>

// Define the array of leds
#define LED_DT 3
#define COLOR_ORDER GRB
#define LED_TYPE WS2812
#define NUM_LEDS 38
uint8_t max_bright = 255;
struct CRGB leds[NUM_LEDS];


void setLEDs (int K, int N) {
  FastLED.clear();
for (int i = 0; i < NUM_LEDS; i++) {
    //( int i = NUM_LEDS-1; i >=0; i–-)  //  tried this but it didnt work
    if (i % N == K) leds[i].setRGB (0, 0, 250); // set red LED
  }
  FastLED.show();
}

void setup() {
  delay (1000);
  LEDS.addLeds<LED_TYPE, LED_DT, COLOR_ORDER>(leds, NUM_LEDS);
  FastLED.setBrightness(max_bright);
}

void loop() {
  int N = 5;
  for  (int i = 0; i < N; i++) {
    setLEDs (i, N);
    delay (150);
  }
}

Open in new window

0
C++ 11 Fundamentals
LVL 13
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

Convert ansi C program (calling java through jni) from Hp-Ux B.11.31 ia64 to Redhat Linux 7.5

I have several java programs that to write to a Fiorano Message Jms queue
I have a Java program called QueueConverter.java that gets the message from the Jms queue and puts it on a unix message queue
Finally a C program reads the message from the unix queue and writes it to a log

On the Hp-Ux B.11.31 it works fine and a message in the final log looks like this:
17/05/19 06:28:50 AM vma1 test

However on the Redhat Linux box, after having some difficulties compiling the C programs the final log looks like this:
V▒▒19 06:28:50 AM vma1 test

So meta characters starts to appear in the final log.

I have been looking into the following problems:
- C compiler options
- Using Jni on a 64bit Linux architecture (I think it was using 32bit when it was working)
- Character set $LANG from source system vs target system

Nothing seems to help ... So anyone has an idea why and where the message string is corrupted in any of the sources.

This is some debug in jni_queue.c:
    q_contents.mess_type = (long)msgType;
    q_contents.priority  = (long)priority;

    /** Copy buffer to the message structure buf **/
    fprintf(stdout, "jni_queue.c mzlbzl 2ND Buffer Contents before copy: " );
    for ( i = 0; i < byteArrayLen; i++ )
      printf("%c", qBufPtr[i]);
    printf( "\n" );

    //Test to replace metachars
    for ( i = 0, j = 0; i < byteArrayLen; j++ )
    {
0
If you had to consider all the myriad of stock trading indicators out there that many novice and advanced traders alike base their trading on, and you had to group that huge number of indicators into the broadest possible major categories, what would those categories be?

I'm thinking there may only be two (2) categories off the top of my head:  Price and Volume.

What do you think?
0
Hello experts.
I got an image size 150 x 150 pixels BMP or JPG
when I make it bigger using mspaint or paint 3d

it loses resolution, becoming bigger blurry

is there any software or visual c, or visual basic source
that i can use to make it  sharper again?
Regards,
0
Please explain Gamma Compression algorithms. How to write Gamma Compression algorithms for typical video and image processing system?  Please provide some detailed examples.  How to gain sufficient understanding to be able to write Gamma Compression in 'C' or MATLAB?
0
Hi all,

In C,

crypt(userpassword, etc-password) always returning NULL in other application.

In my simple test application, working fine.

 What could be the reason?  How to fix this?

Thanks,
Bvm
0
Using Windows Forms

I have a tabcontrol , each page has a datagridview.  I know the  tab page name

tabData.SelectedTab.Name

let's say I have tabPage1  the datagridview on that tab is dgvPage1.   Now I want to get the selected row

int row = dgvPage1.CurrentCell.RowIndex;  


How can I do this if all I know about is the grid I want is   -- String  VariableName  =  "dgvPage1"  stored in a variable.

int row = (VariableName).CurrentCell.RowIndex;  
String Person = (VariableName).Rows[row].Cells[0].Value.ToString();
0

C

22K

Solutions

13K

Contributors

C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. By design, C provides constructs that map efficiently to typical machine instructions, so it has found lasting use in applications that had formerly been coded in assembly language, including operating systems as well as various application software for computers ranging from supercomputers to embedded systems. It is distinct from C++ (which has its roots in C) and C#, and many later languages have borrowed directly or indirectly from C.