im new at coding with Xcode but strangely it jumps some instructions and finish the program without printing the results. the find_track method is not printing the position of the song and skips to end. the code can be build and has "apparently"no error (it comes from a C coding book). Anyone familiar with Xcode who can help ?
char tracks[][80] = {"my spirit","code songs"};
void find_track(char search_for[]) {
int i;
for (i = 0; i < 2; i++){
if (strstr(tracks[i],search_for)){
printf("Track %i: '%s'\n", i, tracks[i]);
}
}
}
int main()
{
char search_for[80];
printf("Search for: \n");
fgets(search_for, 80, stdin);
find_track(search_for);
return 0;
}
** Program ended with exit code: 0 // exit message from Xcode
fgets leave newline (enter key) in the buffer. You can easily test it
int main(void)
{
char search_for[80];
printf("Search for: \n");
fgets(search_for, 80, stdin);
printf("%s", search_for);
for (size_t i=0; i<strlen(search_for); i++)
{
printf ("%X - %c\n", search_for[i], search_for[i]);
}
return 0;
}
Input my spirit from terminal output will be
0x6D - m
0x79 - y
0x20 -
0x73 - s
0x70 - p
0x69 - i
0x72 - r
0x69 - i
0x74 - t
0x0A -
Final 0x0A is '\n' char: newline.
Passing directly it to find_track function strstr will try to match that char too.
So simple solution is to remove that char:
#include <stdio.h>
#include <string.h>
char tracks[][80] = { "my spirit", "code songs" };
void find_track(char search_for[])
{
int i;
for (i = 0; i < 2; i++)
{
if (strstr(tracks[i], search_for) != NULL)
{
printf("Track %i: %s\n", i, tracks[i]);
}
}
}
int main(void)
{
char search_for[80];
printf("Search for: \n");
fgets(search_for, 80, stdin);
printf("%s", search_for);
// Remove newline
search_for[strlen(search_for)-1] = '\0';
find_track(search_for);
return 0;
}
Related
Could anyone please help me understand why Clang reallocates the same memory address for different variables while their lifetimes intersect?
I am using a sample program (below) to show the problem.
When I compile the program with clang -O0, variable j in function ok has the same memory address as variable solutions in function nqueens.
Function ok is called inside function nqueens, which means that the lifetime of the variables intersect; the same stack space cannot be used/reused for both functions.
Compiling the program with gcc or clang at -O1, however, they are assigned different memory addresses.
Any help is appreciated!
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include <alloca.h>
/* Checking information */
static int solutions[] = {
1,
0,
0,
2,
10, /* 5 */
4,
40,
92,
352,
724, /* 10 */
2680,
14200,
73712,
365596,
};
#define MAX_SOLUTIONS sizeof(solutions)/sizeof(int)
int total_count;
int sharedVar = 0;
int ok(int n, char *a)
{
int i, j;
char p, q;
printf("jjjjjjjjj: %d, %p\n", n,&j);
for (i = 0; i < n; i++) {
p = a[i];
for (j = i + 1; j < n; j++) {
q = a[j];
if (q == p || q == p - (j - i) || q == p + (j - i))
return 0;
}
}
return 1;
}
void nqueens (int n, int j, char *a, int *solutions)
{
int i,res;
sharedVar = sharedVar * j - n;
if (n == j) {
/* good solution, count it */
*solutions = 1;
return;
}
printf("solutions: %d, %p\n", j, &solutions);
*solutions = 0;
/* try each possible position for queen <j> */
for (i = 0; i < n; i++) {
a[j] = (char) i;
if (ok(j + 1, a)) {
nqueens(n, j + 1, a,&res);
*solutions += res;
}
}
}
int main()
{
int size = 3;
char *a;
// printf("total_count: %p\n", &total_count);
total_count=0;
a = (char *)alloca(size * sizeof(char));
printf("Computing N-Queens algorithm (n=%d) ", size);
sharedVar = -5;
nqueens(size, 0, a, &total_count);
printf("completed!\n");
printf("sharedVar: %d\n", sharedVar);
}
I want to make the printf function print from right to left because this program convert the value of number to binary and I want it to be printed in proper form for example if I convert 16 it is written like that 00001 but it must look like that 10000 so does anyone know how to do that thanks in advance
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,rem;
printf("please enter number: ");
scanf("%d",&x);
while (x !=0)
{
rem=x%2;
if (rem==0)
{
printf("0");
}
else
{
printf("1");
}
x = x/2;
rem = 0;
}
return 0;
}
Here it is:
void print_binary(int x)
{
int skip = 1;
unsigned int mask = 1 << 31;
while(mask > 0){
if(x & mask){
skip = 0;
printf("1");
}else{
if(!skip) printf("0");
}
mask >>= 1;
}
printf("\n");
}
This will print the binary number without trailing zeroes.
If you rather want the result to be stored in a string, you can use:
#include <string.h>
void int_to_binary(int x, char * buff) // buff size must be >= 32 !
{
buff[0] = '\0'; // ensure string ends with \0
unsigned int mask = 1 << 31;
for (; mask > 0; mask >>= 1)
{
strcat(buff, (x & mask) ? "1" : "0");
}
}
To check both codes, use:
int main(int argc, char* argv[])
{
int x;
printf("please enter number: ");
scanf("%d",&x);
char bin[32];
int_to_binary(x, bin);
printf("%s\n", bin);
print_binary(x);
}
What we do is using a mask, which in binary is one "1" beginning on the far left and moving one step right at each loop. The "&" is a bite-wise operator (I let you google it to know how it works). If you need more explanation, feel free to ask.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int binary[20];
int q,i=0;
printf("Enter the decimal no\n");
scanf("%d",&q);
while(q > 0)
{
binary[i]=q%2;
i++;
q=q/2;
}
for(int j=i-1;j>=0;j--)
{
printf("%d",binary[j]);
}
return 0;
}
I wrote a rot13.c program but I can tell something in my loop inside rot13_translate_string is causing the program to just print out blank lines.
Any thoughts?
Thank you!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char rot13_translate_character(char c)
{
if( 'A' <= c && c <= 'M' )
{
return c + 13;
}
else if( 'N' <= c && c <= 'Z' )
{
return c - 13;
}
else if( 'a' <= c && c <= 'm' )
{
return c + 13;
}
else if( 'n' <= c && c <= 'z' )
{
return c - 13;
}
else
{
return c;
}
}
char *rot13_translate_string(const char *str)
{
int len = strlen(str);
char *translation = calloc(len, sizeof(char));
int i;
do //****HERE IN THIS SECTION
{
/* Translate each character, starting from the end of the string. */
translation[len] = rot13_translate_character(str[len]);
len--;
} while( len < 0 ); //<
return translation;
}
And here is the main (part of the same file) - is the condition for my for i = 1 ok?
int main(int argc, char **argv)
{
if( argc < 2)
{
fprintf(stderr, "Usage: %s word [word ...]\n", argv[0]);
return 1;
}
/* Translate each of the arguments */
int i;
for( i = 1; i < argc; i++) //*****IS this right?
{
char *translation = rot13_translate_string( argv[i] );
fprintf(stdout, "%s\n", translation);
}
return 0;
}
As just it was pointed out by Janis is the control on the loop do ... while. It should be
while( len >= 0 );
A "while" loop runs while the control expression is true (and terminates once the expression becomes false). You define the variable len just before the loop and it cannot be <0.
So you never really enter in the loop.
You obtain a line for each input word because of fprintf(stdout, "%s\n", translation); line, where you print for each (empty) word a line (\n).
In other languages, for example in Pascal, there is "repeat until" loop construction, which continues to run until the control expression is true, and only after that it changes it terminates.
In that case you could use a condition with <0.
In C to follow the same logic you can use while loop and negate the condition. In your case
} while (! (len < 0) );
I get _CrtIsValidHeapPointer(pUserData) error when running the code above.
Sometimes the code works perfectly, and sometimes this message appears. So I guess the problem is related to the memory allocation. But I've gone through the code many times and the numbers make sence to me (and also when debugging).
I noticed it happens in line "free(str_temp)" at the debugging.
The relevant code is here:
int main(){
int n;
int len;
char *str;
char command[3];
printf("Enter your string:\n");
scanf("%d", &n);
str = malloc(n+1);
scanf("%s", str);
while (1){
printf(">");
scanf("%s", command);
if (compare(command, "ml")) {
int k;
scanf("%d", &k);
multiply(str, n, k);
printf("Current string is %s\n", str);
n = ln(str);
continue;
}
free(str);
return 0;
}
void multiply(char *str, int n, int k) {
char *str_temp = malloc(n+1);
int i;
int j;
int q;
for (i = 0; i < n; i++){
str_temp[i] = str[i];
}
str_temp[n] = '\0';
free(str);
*str = malloc(n*k+1);
for (i = 0; i < k; i++){
for (j = 0; j < n; j++){
str[i*n + j] = str_temp[j];
}
}
str[n*k] = '\0';
free(str_temp);
}
Try to use message defination
void multiply(char **str, int n, int k)//Use **str(double pointer) instead of *str.
And call it like
multiply(&str, n, k);
According to https://github.com/signal11/hidapi/issues/72 HIDAPI ought to be thread safe on Linux machines. However, I can't get it working at all. This is what I do:
#ifdef WIN32
#include <windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <assert.h>
#include "hidapi.h"
hid_device *handle;
static void *TaskCode(void *argument)
{
int res;
//hid_device *handle;
unsigned char buf[64];
// res = hid_init();
// if( res == -1 )
// {
// return (void*)1;
// }
//
// handle = hid_open(0x0911, 0x251c, NULL);
// if( handle == NULL )
// {
// return (void*)2;
// }
printf( "while 2\n");
while( 1 )
{
memset( buf, 64, 0 );
res = hid_read(handle, buf, 0);
if( res == -1 )
{
return (void*)3;
}
printf( "received %d bytes\n", res);
for (int i = 0; i < res; i++)
printf("Byte %d: %02x ", i+1, buf[i]);
//printf( "%02x ", buf[0]);
fflush(stdout);
}
return (void*)0;
}
int main(int argc, char* argv[])
{
int res;
//hid_device *handle;
unsigned char buf[65];
res = hid_init();
if( res == -1 )
{
return 1;
}
handle = hid_open(0x0911, 0x251c, NULL);
if( handle == NULL )
{
return 2;
}
hid_set_nonblocking( handle, 0 );
pthread_t thread;
int rc = pthread_create(&thread, NULL, TaskCode, NULL);
printf( "while 1\n");
while(1)
{
int a = getchar();
if( a == 'a')
{
// Get Device Type (cmd 0x82). The first byte is the report number (0x0).
buf[0] = 0x0;
buf[1] = 0x82;
res = hid_write(handle, buf, 65);
if( res != -1 )
printf( "write ok, transferred %d bytes\n", res );
else
{
printf( "write error\n" );
char* str = hid_error(handle);
printf( "error: %s\n", str );
return 1;
}
}
else if( a== 'b')
break;
}
void* trc;
rc = pthread_join(thread, &trc);
printf( "rc code: %d\n", (int)trc );
// Finalize the hidapi library
res = hid_exit();
return 0;
}
If I don't use the global handle, I get 'write error' every time. If I do, as in the example, formally everything works but hid_read always returns 0 bytes... Of course, if I do simple hid_write() followed by hid_read(), I'll get the correct reply to the command 0x82 as intended. I'm really lost here, am I overlooking something?
EDIT: to clarify, zero bytes return also for everything, incl. buttons on mouse etc. So it seems to work but the data buffer is always zero bytes.
Shame on me, a dumb mistake. The code should be:
memset( buf, 0, 64 );
res = hid_read(handle, buf, 64);
and then it works. Should sleep more and write less!