Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have the following kind of source code in C++. Now I want to make this program in C too (with C++ compiler) but I am confused about allocation.
My current code of my function
char* product(char* a, unsigned short b, unsigned short zeroes)
{
char* finish = new char[strlen(a) + 2 + zeroes]();
short carry = 0;
unsigned short c;
unsigned short s;
for (short i = strlen(a) - 1; i >= 0; i--) {
c = char2int(a[i]);
s = (b*c + carry);
carry = s / 10;
finish[strlen(finish)] = int2char(s % 10);
}
printf("%s", finish); // dump! Looking what is inside
if (carry > 0) {
finish[strlen(finish)] = int2char(carry);
}
reverseChar(finish);
for (short i = 0; i < zeroes; i++) {
finish[strlen(finish)] = '0';
}
return ltrim(finish,'0'); // trim
}
I've tried to allocate via malloc.h using this (char*) malloc (strlen(a) + 2 + zeroes) but it gave me random chars (at the dump part). Is someone possible to say me what just happend here?
The operator new allocates memory, but also calls the constructors of the objects to be created.
In this case char() which initializes them to zero.
To have equvalent code you could for example use memset.
Note that if your type is not of size one (like char), you also have to multiply the amount you give to malloc by the size of the type. new does this automatically.
The actual issue with your code starts when you call strlen(finish) when there is garbage in the memory.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Since people can't seem to read I'm editing the question, and debating removal. I had simplified code representing some logic I'm working on optimizing in a large and very old project. I asked them to not focus so much on the code as much as the concepts of coding in C... I had to use code to help ask question because I'm not sure how to word properly otherwise.
Regarding C (not C++) does doing math in comparison statements help or hurt efficiency? What about declaration of pointers? SORRY can't give code examples as the syntax will be nitpicked to hell before I can get an answer.
Performing comparisons between expression results or storing the values into local variables before the comparison usually does not make much of a difference, except when the computation can be avoided. Here is a classic example:
int count_char(const char *s, char c) {
int count = 0;
for (int i = 0; i < strlen(s); i++) {
if (s[i] == c)
count++;
}
return count;
}
Computing the length of the string for each iteration is very inefficient. Computing it once in the loop initial phase is better:
int count_char(const char *s, char c) {
int count = 0;
for (int i = 0, len = strlen(s); i < len; i++) {
if (s[i] == c)
count++;
}
return count;
}
Yet a different approach with pointers (as mentioned in your question) may prove even more efficient:
int count_char(const char *s, char c) {
int count = 0;
while (*s) {
if (*s++ == c)
count++;
}
return count;
}
And here is a tighter version, albeit less readable:
int count_char(const char *s, char c) {
int count = 0;
while (*s) {
count += (*s++ == c);
}
return count;
}
Note that all of the above functions should use size_t instead of int for the i, len and count variables as, on some platforms, the length of the string could be larger than the maximum value of type int.
Note also that a very good optimizing compiler could produce similar and efficient code for all versions as strlen() is a pure function and the contents of s can be determined to remain constant during the execution of the function, but it is not necessarily true for more complicated examples.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I was wondering if it is possible to index an array by using a binary number instead of a decimal number. For instance, arr[binary].
Yep that's definitely possible. Just prepend your binary number with 0b
int array[] = {1,2,4,6};
printf("%d\n", array[0b0001]); // prints 2
from https://gcc.gnu.org/onlinedocs/gcc/Binary-constants.html binary constants can be written using the 0b syntax
As pointed out, all numbers stored on a computer are binary. Binary is the only thing that can be stored on a computer.
And, C does not support binary syntax. (Or perhaps come C compilers do?)
You could however convert a string from binary like this:
var value = arr[BinaryToInt("1011")];
int BinaryToInt(string s)
{
int value = 0;
int bitValue = 1;
for (int i = s.Length - 1; i >= 0; i--)
{
if (s[i] == '1')
value += bitValue;
bitValue <<= 1;
}
return value;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I had an interview yesterday where they had asked me to write a function which accepts 3 arguments,1 source , 1 destination and other the length and this function should copy the value from source to destination based on the length parameter and the types of source and destination could be different.
Can someone please help me write a generic function ?
Thanks a lot in advance
You mean memcpy (or memmove)? :P
A naive implementation (using bytes):
int my_memcpy(void *dest, const void *src, size_t len)
{
if (dest == NULL || src == NULL || src == dest) return -1;
if (len == 0) return 0;
char *dest_bytes = dest;
const char *src_bytes = src;
for(size_t i = 0; i < len; i++) {
dest_bytes[i] = src_bytes[i];
}
return 0;
}
One can optimise using uint64_t pointers (taking care of the remainder with a char *) and loop unrolling to copy more data each iteration of the for loop.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The program is suppose to convert binary number to decimal form. Only using scanf() and printf() library functions. Takes in a char array from user ---no prompt outputs decimal form, function must be used with parameter (char binaryString[]) after conversion result must be printed out in main. Program does not work don't think I'm converting the binary form to decimal form correctly in function binaryToDecimal since i cant use pow() I'm lost
#include <stdio.h>
#include <math.h>
int binaryToDecimal(char binaryString[]) {
int c, j = 1, decimalNumber = 0;
for (binaryString[c = 0]; binaryString[c] > binaryString[33];
binaryString[++c]) {
while (binaryString[c] != 0) {
remainder = binaryString[c] % 10;
decimalNumber = decimalNumber + remainder * j;
j = j * 2;
binaryString[c] = binaryString[c] / 10;
}
}
return decimalNumber;
}
int binaryToDecimalMain() {
int arraysize = 33;
char binaryString[arraysize];
scanf("%32s", binaryString);
printf("%d",binaryToDecimal(binaryString []);
return 0;
}
I not give you the algorithm because it's seems that you are learning how to program and it is important to you to learn to discover how to solve the problems that are given to you.But I can give you some hints:
use binaryString only to compare with '0' or '1'. Don't try to make any operations like '%' on it.
iterate on the binaryString character by character (no while inside for [this is only for this case, there some algorithm that is necessary to do something like this])
your logic to convert is on the right track
Also you should call your main function main.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Let us say that the English alphabets A to Z has value start from 1. A = 1, B = 2, C = 3 and so on. Write a program which calls a function which accepts the name of a person which is constant character array and returns an integer value with sum of the Alphapets. What is the benefit of passing the name of the person as const char array?
Suppose somebody else provides me a function that takes non-const char * and does the job. What the function is actually implemented is like this:
int get_int_sum(char *name)
{
int sum;
//codes to calculate sum of alphas
name[0] += 1;
//continue
return sum;
}
When I call the function using
char my_name[] = "Yu Hao";
int reuslt = get_int_sum(my_name);
Even if I got the result I want, my_name is changed to "Zu Hao" without my notice. However, if a function has a prototype of
int get_int_sum(const char*name)
I am sure that the string I passed will not be modified.
One advantage is that elements in a array are protected from changing its value.
For example, here is simple code.
int Your_function(const char * a)
{
a[3] = 'A'; // this statement causes compile error.
// do something
return 0;
}