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 10 months ago.
Improve this question
For a school assignment, I am to Create variables in main() that will store the counts and pass pointers to these variables to your functions so that the functions can modify the variables via the pointers. This is a school assignment so rather than someone Give me the answer, I would prefer is someone could help point me in the right direction of using pointers. The Code does work, but not in the way I would like yet.
the code is as follows
void myFunction(int *letters, int *numbers, int *otherCharacters){
}
int main(int argc, char * argv[]) {
// Code for command line argument
if (argc == 2) {
int letters = 0;
int numbers = 0;
int otherCharacters = 0;
int totalCharacters;
int length = strlen(argv[1]);
for (int i = 0; i < length; ++i){
if (isalpha(argv[1][i]) != 0)
++letters;
if (isdigit(argv[1][i]) != 0)
++numbers;
if (isdigit(argv[1][i]) == 0 && isalpha(argv[1][i]) == 0)
++otherCharacters;
}
totalCharacters = letters + numbers + otherCharacters;
printf("%i letters\n%i digits \n%i other characters\n%i characters total\n", letters, numbers, otherCharacters, totalCharacters);
}
I am hoping to rather than change the values of letters, numbers, otherCharacters, and totalCharacters in the main function use pointers to do so in myFunction(). any help on how to use pointers to do so would be much appreciated. Again, I am not asking for an answer, as I would like to complete this assignment myself.
Seems like the function is supposed to look at a string and tell you how many letters, numbers, and other characters there are. It needs to take the counts as pointers, and the string.
void countCharacters(const char *string, int *letters, int *numbers, int *other) {
....
}
Because they are pointers, when incrementing them you need to dereference them first to get their values. Instead of letters++ it would be (*letters)++.
And we can replace the main code to show how you'd call this.
int main(int argc, char * argv[]) {
// Exit early to avoid deeply nesting all the code.
if (argc != 2) {
perror("please supply a string");
return 1;
}
int letters = 0;
int numbers = 0;
int other = 0;
// Pass in the string (already a pointer) and the counts as pointers.
countCharacters(argv[1], &letters, &numbers, &other);
int total = letters + numbers + other;
printf("%i letters\n%i digits \n%i other characters\n%i characters total\n", letters, numbers, other, total);
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 11 days ago.
Improve this question
I want to use the count variable to store numbers in the W array using malloc, but the output keeps repeating the same number entered.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int *w = malloc( sizeof(int) * 10000);
int x; int count = 0;
while (scanf("%d", &x) == 1) {
printf("%d", &x]);
*(w + x) = count;
count++;
}
free(w); w = NULL;
return 0;
}
argc, argv are not used so leave them out.
Prefer sizeof a variable (*w) opposed to a type (int). If the type changes you only need to make the change in one place.
Use constants instead of magic values.
You don't need the temporary variable x.
Prefer unsigned (size_t) types to (unsigned) int for values that should not be negative. It eliminates a possible error class.
Prefer a for to while-loop when counting things. It might be more readable like this:
for(size_t count = 0;; count++) {
if(scanf("%d", &w[count]) != 1)
break;
printf("%d\n", w[count]);
}
printf("%d", ...) takes a value not an address. This appears to be the main issue.
For readability by user add a new newline when printing the value.
#include <stdio.h>
#include <stdlib.h>
#define LEN 10000
int main() {
int *w = malloc(LEN * sizeof *w);
for(size_t count = 0; scanf("%d", &w[count]) == 1; count++)
printf("%d\n", w[count]);
free(w);
}
example session:
$ ./a.out
1
1
2
2
4
4
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 1 year ago.
Improve this question
Can anyone please help me.I want to remove character from char* in C.
For example, char *str this str equals to "apple" and first i remove 1. character and define a new variable then remove 2. character and define new variable and so on until the str ends.
How can ı do that ? I'm completely new to C, and just can't seem to figure it out
Assuming you only need to remove characters from the left.
Because strings in C are arrays of characters, and arrays are pointers to the first element of the array, you can create variables that point to specific indices in you original char array.
For example
char* myString = "apple";
char* subString = myString+1;
printf("%s\n%s\n", myString, substring);
would produce the output
apple
pple
We could generalize this to store all substrings obtained by removing characters from the left in an array of char* pointers (pointers to pointers). Like so:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char** GetSubStrings(char* input)
{
int length = strlen(input);
char** result = calloc(length, sizeof(char*));
for(int i = 0; i < length; i++)
{
result[i] = input + i;
}
return result;
}
int main()
{
char* myString = "apple";
char** subStrings = GetSubStrings(myString);
for(int i = 0; i < strlen(myString); i++)
{
printf("%s\n", subStrings[i]);
}
free(subStrings);
return 0;
}
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 1 year ago.
Improve this question
I'm trying to print random words with the use of rand().
I think that I've made a mistake on the pointer arithmetic since I get a weird output.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main ()
{
srand(time(0));
const int randomBit = rand() % 2;
char * sz[] ={"good", "bad"};
switch (randomBit)
{
case 0:
for (char *i=*sz; *i<(sz+3); i++)
{
printf("%c", *i);
}
break;
case 1:
for (char *i=*(sz+3); *i!=0x0; i++)
{
printf("%c", *i);
}
break;
default:
break;
}
return 0;
}
What's my mistake?
Thank you.
Given this declaration ...
char * sz[] ={"good", "bad"};
... this code has undefined behavior:
for (char *i=*(sz+3); *i!=0x0; i++)
The expression *(sz+3) is equivalent to sz[3], but array sz has only two elements, so the maximum index is 1.
Likewise, the expression *sz is equivalent to sz[0]. That one is semantically ok but stylistically poor. Likewise stylistically poor is splitting out two separate cases when you could instead cover both with the same code by using sz[randomBit] to select which string to print.
Furthermore, it is unclear why you are printing character by character. Perhaps that's part of the assignment, but in the real world a programmer would probably write ...
printf("%s", sz[randomBit]);
... instead of that entire switch statement.
Your code is incredibly complicated (and wrong).
What's wrong with this:
int main()
{
srand(time(0));
const int randomBit = rand() % 2;
char* sz[] = { "good", "bad" };
printf("%s\n", sz[randomBit]);
return 0;
}
or if you are not allowed to use the %s format specifier as part of your assignement:
for (char* i = sz[randomBit]; *i != 0; i++)
{
printf("%c", *i); // or putchar(*i);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
So I've got a problem with int and string in C.
My task is to write a function that will output the error rate in string.
For example if the string is "aaabbbcccdxm" then the output should be "1/12".
By "error" I mean any letter from n to z, and any letter from a to m is "good".
I thought that I could do it by using a for loop to check every letter in the string, and then if to add value to int error which would be numbers of bad letters, but I don't know how to convert that "int error" value to string with output error value/string dimension. Any ideas?
You can use printf to format your output. I recommend reading the man 3 printf on a linux machine or from google.
Here is what such a program could look like:
#include <stdio.h>
#include <string.h>
int main()
{
const char * input_str = "aaabbbcccdxm";
int size = strlen(input_str);
int error = 0;
for (int i = 0; i < size; ++i)
{
if (input_str[i] >= 'n')
error++;
}
printf("%d/%d\n", error, size);
return 0;
}
size_t errors(const char *str, const char *legal)
{
size_t errcnt = 0;
while(str && *str)
{
errcnt += !strchr(legal, *str++);
}
return errcnt;
}
int main()
{
char *str = "aaabbbcccdxm";
printf("%zu/%zu\n", errors(str,"abcdefghijklm"), strlen(str));
return 0;
}
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 4 years ago.
Improve this question
void function(int first[], int second[], int third[]) {
int i;
for(i=0;i<64;i++) {
third[i] = first[i] - second[i];
}
}
I want to subtract the second array from the first one. The first one contains 32 numbers and the second one has 13 numbers. It works fine for the first 13 numbers. Once the second array "runs out" of elements, I want to use the numbers from the beginning of the second array. So I want to subtract the second array's first element from the 14th element of the first one, and so on... How could I achieve it?
you can use % to get the remainder of the index from length of the array, this way, you can iterate through the second array in a circular way!
I changed your code to do as you asked for
// get the length of array before you pass it to the function like this:
// int second_len = sizeof(second) / sizeof(second[0]);
void function(int first[], int second[], int third[], int second_len) {
int i;
for(i=0;i<64;i++) {
third[i] = first[i] - second[i % second_len];
}
}
The elements of the first and second array are sequences of positive
numbers and they are both closed with -1
You could just do as below.
Maintain two indexes i and j.
Where i will index larger array and j will index smaller array and once smaller array reaches -1 reset the j to 0 and once larger array reaches -1 break the loop.
void function(int first[], int second[], int third[]) {
int i =0,j=0;
for(i=0; i<64 ; i++;j++) {
if(second[j] == -1)
{
j =0; //Reset the j=0 to start from beginning
}
if (first[i] == -1)
{
third[i] = -1; //Terminate third with -1
break; //Break the loop
}
third[i] = first[i] - second[j];
}
}
One option is to add an additional looping variable:
void function(int first[], int second[], int third[],
int first_size, int second_size)
{
int i=0, k=0;
for(i=0; i<first_size; i++) {
third[i] = first[i] - second[k];
k++;
if (k==second_size)
k = 0;
}
}
i tracks the size of the first array and the output like in your program, and k follows the size of the second array and resets whenever the size is reached. Instead of hardcoded array sizes the function now takes two additional arguments: sizes of the first and second arrays.
For future reference, the rest of this code could look like this:
#include <stdio.h>
void print_array(int arr[], int);
void function(int arr_1[], int arr_2[], int arr_3[], int, int);
int main()
{
int arr_1[] = {1,2,3,4,5};
int arr_2[] = {1,2};
int n_1 = sizeof(arr_1)/sizeof(arr_1[0]);
int n_2 = sizeof(arr_2)/sizeof(arr_2[0]);
int arr_out[n_1];
function(arr_1, arr_2, arr_out, n_1, n_2);
print_array(arr_1, n_1);
print_array(arr_2, n_2);
print_array(arr_out, n_1);
return 0;
}
void print_array(int arr[], int n_elem)
{
int i = 0;
for (i=0; i<n_elem; i++)
printf("%d ", arr[i]);
printf("\n");
}
With print_array as a function to avoid repeating the same lines of code for each print.
For the example input, the output will be 0 0 2 2 4.