Print digital to string in C language - c

#include <stdio.h>
#define stringify(s) tostring(s)
#define tostring(s) #s
#define MAX_VALUE 65536
#define NUM 64 * 1024
enum {
MIN_VALUE = 1024,
};
int main(int argc, char *argv[])
{
const char *max_str = stringify(MAX_VALUE);
const char *min_str = stringify(MIN_VALUE);
printf("max = %s, min = %s\n", max_str, min_str);
return 0;
}
The output is "max = 65536, min = MIN_VALUE num = 1024 * 64"
Experts, how can I modify my code to output like this:
max = 65536, min = 1024 num = 65536
Thanks .

MIN_VALUE is a number. Why do you need to stringify it?
Just use:
printf("%d\n", MIN_VALUE);

I think you're better off using a function instead of a macro for this, the reason being that macros are only expanded even before compile time, let alone runtime.
consider this example:
#define stringify(V) #V
#include <stdio.h>
int main()
{
int x = 5;
const char *str = stringify(x);
printf("%s\n", str);
}
after the preprocessor has done it's work, the code will look like this:
#include <stdio.h>
int main()
{
int x = 5;
const char *str = "x";
printf("%s\n", str);
}
that is because all the preprocessor directive # does, is wrap the given parameter in quotes.
If you want to have an int to string behaviour that works on constants, enums (cast to int) and integer variables, you could use sprintf:
#include <stdio.h>
#include <stdlib.h>
char *stringify(int x)
{
/* get the length of the required buffer */
int len = snprintf(0, 0, "%i", x);
/* allocate memory */
char *res = malloc(sizeof(char) * (len + 1));
/* handle allocation failure */
if(!res)
return 0;
/* convert the int to string */
snprintf(res, len + 1, "%i", x);
/* return the result */
return res;
}
int main()
{
int x = 5;
char *str = stringify(x);
printf("%s\n", str);
/* we free the memory allocated by malloc */
free(str);
}
this would be one way you could to this in C. If you want to know more about the functions I used, have a look at:
http://www.manpagez.com/man/3/vsnprintf/
http://www.manpagez.com/man/3/malloc/

#define statements are handled by the pre-processor before the compiler gets to see the code so it's basically a text substitution (it's actually a little more intelligent with the use of parameters and such).
Since stringify(s) is #defined, the preprocessor faithfully does it job.
stringify(MAX_VALUE) decays to stringify(65536) since MAX_VALUE is #defined to 65536, also known at preprocessing.
But Enumerations are part of the C language itself and not known at preprocessing,
So, stringify(MIN_VALUE) retains as stringify(MIN_VALUE) and hence toString(MIN_VALUE)
To do integer arithmetic or to print
num = 65536
"yes", there is a way to make the preprocessor perform integer arithmetic, which is to use it in a preprocessor condition.
#if 1024*64 == 65536
printf("num=65536\n");
#endif

Related

get all indexes of all occurances of a substring in a string

i searched online everywhere but i was unable to find a solution that i could implement in my code, i have some limiting factors to take in accounts, the biggest one is: i cannot use pointers to do this, second one is that i cannot edit before the comment
what i have to do is look for the SEC_B sequence in the adn1 string then save the position of it into a int array to then print it something like this:
Found sequence GTC in: 20 62 69 159 167 196
and yes i did count them manually
i have to do the same with the other sequences, but that doesn't matter as long is i can get it working with one, i can then make it work with all the others
so this is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SECUENCIA0 "TGGCGTTTGCAGATTACTGCGTCCCTCACAAGGGTGTGAA"
#define SECUENCIA1 "GCTGTGCATTCGCGGCACAAGAGTCCCGGGTCCCTGTAGC"
#define SECUENCIA2 "TTCACCATCCTGTTGTACCTATCAAACCTACCTACAGCTT"
#define SECUENCIA3 "AGTGAAGGATTATGCGATTGGCGAGCATAGTACCGGCCCG"
#define SECUENCIA4 "TCACACCGTCTCATTGGTGGCCGACCTTGGAACTCCGTCA"
#define SEC_B "GTC"
#define SEC_D "GAT"
#define SEC_K "GT"
int main()
{
char adn1[201];
adn1[0]='\0';
strcat(adn1,SECUENCIA0);
strcat(adn1,SECUENCIA1);
strcat(adn1,SECUENCIA2);
strcat(adn1,SECUENCIA3);
strcat(adn1,SECUENCIA4);
//edit from here
return 0;
}
this solution doesn't involve any explicit pointers (no * anywhere) and doesn't edit the line above the comment, i managed to come up with this solution thanks to the answer of zazz (which he deleted for some reson), here's how i've done it
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SECUENCIA0 "TGGCGTTTGCAGATTACTGCGTCCCTCACAAGGGTGTGAA"
#define SECUENCIA1 "GCTGTGCATTCGCGGCACAAGAGTCCCGGGTCCCTGTAGC"
#define SECUENCIA2 "TTCACCATCCTGTTGTACCTATCAAACCTACCTACAGCTT"
#define SECUENCIA3 "AGTGAAGGATTATGCGATTGGCGAGCATAGTACCGGCCCG"
#define SECUENCIA4 "TCACACCGTCTCATTGGTGGCCGACCTTGGAACTCCGTCA"
#define SEC_B "GTC"
#define SEC_D "GAT"
#define SEC_K "GT"
int main()
{
char adn1[201];
adn1[0]='\0';
strcat(adn1,SECUENCIA0);
strcat(adn1,SECUENCIA1);
strcat(adn1,SECUENCIA2);
strcat(adn1,SECUENCIA3);
strcat(adn1,SECUENCIA4);
//edit below here
printf("---- Búsqueda de secuencias B, D y K dentro del adn1 ------\n");
int PosicionesB[20];
int bs = 0;
int i, l1, l2;
l1 = strlen(adn1);
l2 = strlen(SEC_B);
for(i = 0; i < l1 - l2 + 1; i++) {
if(strstr(adn1 + i, SEC_B) == adn1 + i) {
PosicionesB[bs] = i;
bs++;
i = i + l2 -1;
}
}
printf("Found sequence GTC in:");
for(int i = 0; i < bs;i++){
printf(" %d",PosicionesB[i]);
}
return 0;
}
It's as simple as this:
#include <stdio.h>
#include <stdint.h>
#include <string.h>
void print_indices_substr(const char *str, const char *substr)
{
char *pstr;
printf("Indices: { ");
for (pstr = (char *)str; (pstr = strstr(pstr, substr)) != NULL; pstr = &pstr[1])
printf("%lu, ", (uintptr_t)pstr - (uintptr_t)str);
printf("}\n");
}
Basically, the function strstr returns a pointer to the first occurrence of 'substr' in 'str' or NULL if no occurrence was found. We can use this pointer in a for loop, and the index will be pstr - str, as you can see in the function above. Example:
int main()
{
const char my_string[] = "ABCDABCD";
print_indices_substr(my_string, "ABCD");
return 0;
}
Output:
Indices: { 0, 4, }

gcc errors while working in a variable-length pointer array in C

I'm getting this error:
list.c list.h types.h
list.c: In function 'List_push':
list.c:11:23: error: invalid initializer
--- void *values[len] = ls->values);
EDIT:
Now, with my current code (I've done undos/redos that removed somethings), I get this error instead:
Why?
Basically I've a List structure which declares an variable-length array, containing void pointers (what I want is pointers to any data type). You can see it below at the list.h file.
I've tried a mix of changes in list.c (i.e., *values[pos++] = ..., etc...), but doing these changes it only results in worse gcc errors.
wscom.c
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
#include "types.h"
int main() {
List ls;
// TEST: Put a value pointer at index 0
uint8 value = 0x41;
List_push(&ls, 1, &value);
printf("%c",
*(char*) List_getindex(&ls, 0)
);
return 0;
}
types.h
#ifndef hydroTrackerTypesH
#define hydroTrackerTypesH
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned long long uint32;
#endif
list.h (Declarations)
#ifndef hydroTrackerListH
#define hydroTrackerListH
#include "types.h"
typedef struct {
uint32 length;
void *values[];
} List;
void List_push(List *ls, uint8 count, ...);
void *List_getindex(List *ls, uint32 i);
void List_setindex(List *ls, uint32 i, void *v);
#endif
list.c (Defns.)
#include "list.h"
#include "types.h"
#include <stdarg.h>
#include <stddef.h>
#include <stdlib.h>
static size_t PointerSize =
sizeof(void*);
void List_push(List *ls, uint8 count, ...) {
uint32 len = ls->length;
void *values[len] = ls->values;
uint32 sum = len + count;
realloc(&values, sum * PointerSize);
ls->length = sum;
va_list newVals;
va_start(newVals, count);
uint8 pos = len;
while(count--)
values[pos++] = va_arg(newVals, void*);
va_end(newVals);
}
void *List_getindex(List *ls, uint32 i) {
return (void *)(ls->values[i]);
}
//void List_setindex(List *ls, uint32 i, void *v);
This is a little bit long for a comment.
Thus, I make it an answer.
I try to show you how pointers and arrays are related to each other:
#include <stdlib.h>
#include <stdio.h>
int main()
{
/* The compiler allocates space for "Hello" and '\0' (5 + 1 chars)
* and stores the address in aString1.
*/
const char *aString1 = "Hello";
/* The compiler allocates 10 chars and initializes
* it with "World" (and the '\0' for terminator).
*/
const char aString2[10] = "World";
/* The compiler determines length of initializer "I'm here."
* (9 + 1) and allocates the array of appropriate size.
*/
const char aString3[] = "I'm here.";
/* allocate storage for array (3 const char*) */
#if 0 /* the usual way */
const char **array = malloc(3 * sizeof (const char*));
#else /* how Matheus wants to do it */
const char **array = NULL;
array = realloc(array, 3 * sizeof (const char*));
#endif /* 0 */
/* assign contents (using it like an array) */
array[0] = aString1;
array[1] = aString2;
array[2] = aString3;
/* apply array to another variable array2 */
const char **array2 = array; /* assigns the address only */
/* use it: */
printf("array2[0]: '%s', array2[1]: '%s', array2[2]: '%s'\n",
array2[0], array2[1], array2[2]);
/* throw away storage of array (and array2) */
free(array);
/* Attention! array, array2 become wild pointers at this point
* and may not be accessed (except new, valid addresses are assigned).
* However, aString1, aString2, aString3 are still intact.
*/
printf("aString1: '%s', aString2: '%s', aString3: '%s'\n",
aString1, aString2, aString3);
/* done */
return 0;
}
The sample can be tested on ideone.com.
The sample output is:
array2[0]: 'Hello', array2[1]: 'World', array2[2]: 'I'm here.'
aString1: 'Hello', aString2: 'World', aString3: 'I'm here.'
Update:
So, I finally looked again on to the question & answer of Matheus and tried to fix it according to his intention (or how I understood it). I based it on Matheus' implementation and remarked modified codes by comments:
list.h:
#ifndef LIST_H
#define LIST_H
#if 0 /* not necessary to define these types */
#include "types.h"
#else /* they are already available in a (better) portable manner: */
#include <stdint.h>
/* Btw. I had to change:
* uint8 -> uint8_t
* uint32 -> uint32_t
*/
#endif /* 0 */
typedef struct {
uint32_t length;
#if 0 /* gcc ERROR: */
/* list.c:17:3: error: invalid use of flexible array member
* ls->values = NULL;
*/
void *values[];
#else /* (not) 0 */
void **values;
#endif /* 0 */
} List;
void List_init(List *ls);
void List_push(List *ls, uint8_t count, ...);
void* List_getindex(List *ls, uint32_t i);
void List_setindex(List *ls, uint32_t i, void *v);
#endif /* LIST_H */
list.c:
#include "list.h"
#include <stdarg.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#if 0 /* no need for a variable (with storage */
static size_t PointerSize = sizeof(void*);
#else /* use enum instead (constant) */
enum { PointerSize = sizeof(void*) };
#endif /* 0 */
void List_init(List *ls)
{
ls->length = 0;
/* This is important: */
ls->values = NULL;
/* or 1st realloc() in List_push() may have Undefined Behavior.) */
}
void List_push(List *ls, uint8_t count, ...)
{
uint32_t len = ls->length;
uint32_t sum = len + count;
void **values = realloc(ls->values, sum * PointerSize);
if (!values) {
/* realloc() failed! Bail out before destroying the existing data. */
return;
}
ls->length = sum;
ls->values = values;
/* assign new contents */
va_list newVals;
va_start(newVals, count);
#if 1 /* the readable way: */
int pos = len;
while (count--) values[pos++] = va_arg(newVals, void*);
#else /* the hackish C style way: */
values += len;
while (count--) *values++ = va_arg(newVals, void*);
#endif /* 1 */
va_end(newVals);
}
void* List_getindex(List *ls, uint32_t i)
{
return ls->values[i];
}
wscom.c:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "list.h"
int main()
{
List ls;
/* Put a value pointers at indices 0, 1, 2 */
uint8_t value1 = 0x41, value2 = 0x42;
uint8_t value3[3] = { 0x43, 0x44, 0x45 };
List_init(&ls);
List_push(&ls, 3, &value1, &value2, value3);
/* Check whether list contents can be retrieved again */
if ((*(uint8_t*)List_getindex(&ls, 0)) == 0x41) {
printf("List entry 0 is correct.\n");
}
if ((*(uint8_t*)List_getindex(&ls, 1)) == 0x42) {
printf("List entry 1 is correct.\n");
}
{ uint8_t *values = List_getindex(&ls, 2);
if (values[0] == 0x43
&& values[1] == 0x44
&& values[2] == 0x45) {
printf("List entry 2 is correct.\n");
}
}
/* Done. */
return 0;
}
In one of my comments, I stated that void *values[]; in struct List might be OK. Ahem, I was wrong. gcc remarks this as error when I tried to use it in list.c. So, actually, it is OK but not for what I intend it to use.
Finally, my sample session (using gcc in cygwin on Windows 10):
$ gcc -std=c11 -o wscom wscom.c list.c
$ ./wscom
List entry 0 is correct.
List entry 1 is correct.
List entry 2 is correct.
$
2nd Update:
(I believe) I realized the missing piece of Matheus (considering his Javascript background):
There are no dynamic arrays in C (in opposition to Javascript).
Instead, there are arrays with variable size which may be used only in specific situations:
In C:
Definition of arrays with variable size in global variables is prohibited. (The compiler needs to know how many bytes to allocate for storage.) This does not exclude something like e.g.
int array[] = { 1, 2, 3 };
because the compiler determines the size from the initializer (on the right hand side of =).
Declaration of global arrays without explicit size is possible. (The definition with proper size might/must be done somewhere else. The linker will fail if no proper storage definition can be found.)
A local variable (inside a function, storage class auto but not static or extern) might be declared as array with size determined at runtime (from a variable). This feature was introduced in C99 but not (yet) in C++ (at least not until C++11 incl.)
A function parameter might be declared as array with unknown (or any) size. (This is equal to declaring it as a pointer.)
I found a nice answer about this in SO: Dynamic array allocation on stack in C (which I used to prove my own statements above).
The only supported way to have "dynamic arrays" in C is the usage of the standard library functions malloc()/realloc()/free(). However this is better called "dynamic memory" allocation because this applies to any C type (not only arrays).
Disclaimer:
I apologize if I wrote something rubbish about Javascript. I'm the total newbie in Javascript with very less practical experience...

Segmentation fault around MD5 code

While I am running this md5 code, it is taking maximum 64 characters length of input at run time. Whenever I am giving more than 64 characters, it is showing
Inconsistency detected by ld.so: dl-fini.c: 205: _dl_fini: Assertion ns != 0 || i == nloaded failed!
I need to hash nearly 10kb of input (only string). Do I need to change anything in the header file? Can anyone tell me solution please?
md5.h
#ifndef HEADER_MD5_H
#define HEADER_MD5_H
#include <openssl/e_os2.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
#ifdef OPENSSL_NO_MD5
#error MD5 is disabled.
#endif
/*
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* ! MD5_LONG has to be at least 32 bits wide. If it's wider, then !
* ! MD5_LONG_LOG2 has to be defined along. !
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*/
#if defined(__LP64__)
#define MD5_LONG unsigned long
#elif defined(OPENSSL_SYS_CRAY) || defined(__ILP64__)
#define MD5_LONG unsigned long
#define MD5_LONG_LOG2 3
/*
* _CRAY note. I could declare short, but I have no idea what impact
* does it have on performance on none-T3E machines. I could declare
* int, but at least on C90 sizeof(int) can be chosen at compile time.
* So I've chosen long...
* <appro#fy.chalmers.se>
*/
#else
#define MD5_LONG unsigned long
#endif
#define MD5_CBLOCK 64
#define MD5_LBLOCK (MD5_CBLOCK/2)
#define MD5_DIGEST_LENGTH 16
typedef struct MD5state_st
{
MD5_LONG A,B,C,D;
MD5_LONG Nl,Nh;
MD5_LONG data[MD5_LBLOCK];
unsigned int num;
} MD5_CTX;
#ifdef OPENSSL_FIPS
int private_MD5_Init(MD5_CTX *c);
#endif
int MD5_Init(MD5_CTX *c);
int MD5_Update(MD5_CTX *c, const void *data, size_t len);
int MD5_Final(unsigned char *md, MD5_CTX *c);
unsigned char *MD5(const unsigned char *d, size_t n, unsigned char *md);
void MD5_Transform(MD5_CTX *c, const unsigned char *b);
#ifdef __cplusplus
}
#endif
#endif
md5.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "md5.h"
char *pt(char *, int );
int main(int argc, char **argv)
{
char *in;
char *out;
printf("ENter the string\n");
scanf("%[^\n]s",in);
size_t len; //unsigned long len; size_t len;
len = printf("len is %d\n",strlen(in));
out = pt(in, len);
printf("MD5 is\t: %s\n", out);
free(out);
//return 0;
}
char *pt(char *str, int length)
{
int n;
MD5_CTX c;
unsigned char digest[16];
char *output = (char*)malloc(33);
MD5_Init(&c);
MD5_Update(&c, str, length);
MD5_Final(digest, &c);
for (n = 0; n < 16; ++n)
{
sprintf(&output[n*2], "%02x", (unsigned int)digest[n]);
}
return output;
}
Problem 1
For this statement:
scanf("%[^\n]s",in);
When I compile it using the -Wall flag, I get the warning:
warning: 'in' is used uninitialized in this function [-Wuninitialized]
scanf("%[^\n]s",in);
^
As you see, in is not pointing to any location in your memory, so you first need to allocate some memory either with an array or malloc():
char in[500]; //or a higher value
char *out;
printf("Enter the string\n");
scanf("%499[^\n]s", in);
printf("\nin = .%s.\n", in);
or
char *in;
char *out;
in = malloc(500); //or a higher value
printf("Enter the string\n");
scanf("%499[^\n]s", in);
printf("\nin = .%s.\n", in);
Possible problem 2
You are assigning the return from printf() to the variable len.
len = printf("len is %d\n",strlen(in));
Return value printf:
Upon successful return, it returns the number of characters printed (excluding the null byte used to end output to strings).
Assuming you want the variable len to contain the length of the string in and not the number of characters printed by printf("len is %d\n",strlen(in)), you might want to assign the return from strlen() first:
len = strlen(in);
printf("len is %d\n", len);

Usage of a constant pointer to an integer in a controlled environment

unsigned int H_SMPTR_LEN = 0;
#ifndef _RSZLEN
#define _RSZLEN(nvalue) H_SMPTR_LEN = nvalue;
#endif
//Smart pointer structure with built-in size
typedef struct SMPTR
{
void *MBLOC;
const unsigned int *length;
unsigned int bloc_size;
} SMPTR;
#ifndef _SMPTR
#define _SMPTR(SMPTR, var_sz, v_num) SMPTR.MBLOC = malloc(var_sz * v_num); SMPTR.bloc_size = v_num * var_sz; _RSZLEN(v_num); SMPTR.length = &H_SMPTR_LEN;
#endif
I wrote this code to experiment with const * to an integer. When I run and implement the code above like so:
#include <stdio.h>
#include <stdlib.h>
#include "cdebug.h"
int main(int argc, char **argv)
{
SMPTR s;
_SMPTR(s, sizeof(char), 50);
fprintf(stdout, "%i\n", s.bloc_size);
fprintf(stdout, "%i\n", s.length);
fprintf(stdout, "%i\n", H_SMPTR_LEN);
fprintf(stdout, "%s", "Done!\n");
return 0;
}
The second output statement is a screwy output result. In theory the second output result should match the third, because the SMPTR.length member points to H_SMPTR_LEN.
The first bit of code is part of my header called "cdebug.h", which is included in main(). I am wondering if I am using const pointers correctly here. The idea here is to create a structure whose members can only be modified in a controlled environment, i.e. a method I write.

How to use the Windows MessageBox() C function?

Can someone tell me how I can display a message box in C that can print variables?
I mean like this:
#include <stdio.h>
#include <windows.h>
main()
{
int x = 5;
MessageBox(0, "Variable x is equal to %d", "Variable", 0);
/* Where do I specify the variable so that 5 will display?*/
getch();
}
To look like this:
Variable
Variable x is equal to 5.
Thanks in advance!
MessageBox itself doen't support printf like formatting. You'll have to use snprintf for that:
char buf[1024];
snprintf(buf, 1024, "Variable x is equal to %d", x);
MessageBox(0, buf, "Variable", 0);
I want to debug multiple variables of type integer or string as a list within a single MessageBox so that I do not have to press the button repeatedly. This extension to #Bart's answer does it:
#include <windows.h>
#include <stdio.h>
#include <string.h>
char debugMsg [1024] = ""; // buffer for debug message
void debugStr (char* varName, char* var) {
snprintf (debugMsg, sizeof (debugMsg), "%s%s=%s\n", debugMsg,
varName, var);}
void debugInt (char* varName, int var) {
snprintf (debugMsg, sizeof (debugMsg), "%s%s=%d\n", debugMsg,
varName, var);}
void main () {
char myStrA [] = "letter A", myStrZ [] = "letter Z";
int myIntA = 65, myIntZ = 90;
// Concat debug message from multiple vars of type integer or string:
debugStr ("myStrA", myStrA);
debugInt ("myIntA", myIntA);
debugStr ("myStrZ", myStrZ);
debugInt ("myIntZ", myIntZ);
MessageBox (NULL, debugMsg, "Debug", MB_OK); // returns this list:
// myStrA=letter A
// myIntA=65
// myStrZ=letter Z
// myIntZ=90
memset (debugMsg, 0, sizeof debugMsg); // clear debug message
}

Resources