How to store numbers in malloc array? [closed] - c

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

Related

Need help transferring my main function code into a separate function [closed]

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);
}

printing strings with pointer arithmetics [closed]

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);
}

Adding int value to string in C [closed]

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;
}

C Arrays gives address instead of value when second array is created [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
First of all, sorry for my English. I hope you will still understand what my problem is.
I am new to C programming and I am a bit confused. Here is my code.
#include <stdio.h>
#include "tableaux.h"
int main(int argc, const char * argv[]) {
int tableauUn[4] = {1, 1, 1, 1};
printf("%d\n", sommeTableau(tableauUn, 4));
printf("%d\n", moyenneTableau(tableauUn, 4));
return 0;
}
And this is the file where my functions are. I also have a file where I have my prototypes.
#include <stdio.h>
#include "tableaux.h"
int sommeTableau(int tableau[], int taille) {
int resultat;
for (int i = 0; i < taille; i++) {
resultat += tableau[i];
}
return resultat;
}
int moyenneTableau(int tableau[], int taille) {
int resultat;
for (int i = 0; i < taille; i++) {
resultat += tableau[i];
}
return resultat / taille;
}
void copierTableau(int tableau[], int taille, int tableauDeux[]) {
for (int i = 0; i < taille; i++) {
tableauDeux[i] = tableau[i];
}
}
So everything works fine. The first printf gives me the total of the values that are stored in the array and the second one gives me the average of the values.
5
1
Program ended with exit code: 0
What I don't understand is why do I get this result when I want to create a second array ?
int tableauUn[4] = {1, 1, 1, 1};
int tableauDeux[4] = {0};
the result
1606416356
1
Program ended with exit code: 0
So I haven't used the second array but the result of the first printf changes and I am a bit confused with what is going on.
I hope you can help me !
Please initialize the sum you return in function
int resultat = 0;
otherwise resultat will take garbage value as initial value

How to manipulate the output stream directly? (Was: why it's not increment value of increment operator in case of assignment in c?)

I fixed the code from this question so that it would compile:
#define text ();
#define return &argv;return
int *** emphasized () {
static int x, *argv = &x, **xpp = &argv;
puts("\r10 11 11");
return &xpp;
}
int main (int argc, char *argv[]) {
int a;
int n = 10;
printf("%d",n);
n++;
printf("%d",n);
a = n++;
printf("%d",n);***emphasized text***
return 0;
}
In the original question, the asker said:
Output= 10 11 11 why it's not increment value of n in second increment operator
Which is why emphasized() does something funny. I was trying to come up with a way that took the asker's literal code to make it do what he/she said it did. To that end, I treated the ***emphasized text*** as part of the source.
My question is: How would emphasized() be changed so that it renders the 10 11 11 output without calling any output function? I am hoping to observe a way to alter the output rendered by the printf() to standard output to add the spaces but botch the last number.
Since this question is labeled with obfuscation, if the solution involves adding more #defines, have at it.
n is incremented to 12 but as n is never printed its value doesn't matter.
Run that crap through the preprocessor and you'll see why.
There is a #define that voids all the printf statements.
The actual output comes from the puts in emphasized.
Here's the original code:
#define text ();
#define printf(a,b) (void)0
#define return &argv;return
int *** emphasized () {
static int x, *argv = &x, **xpp = &argv;
puts("\r10 11 11");
return &xpp;
}
int main (int argc, char *argv[]) {
int a;
int n = 10;
printf("%d",n);
n++;
printf("%d",n);
a = n++;
printf("%d",n);***emphasized text***
return 0;
}
Here's the code after being run through the preprocessor:
int *** emphasized () {
static int x, *argv = &x, **xpp = &argv;
puts("\r10 11 11");
&argv;return &xpp;
}
int main (int argc, char *argv[]) {
int a;
int n = 10;
(void)0;
n++;
(void)0;
a = n++;
(void)0;***emphasized ();***
&argv;return 0;
}
Note that the printf statements don't appear in the preprocessed code; the value of n isn't being displayed to the console at all in this version. The output comes from the emphasized function.
n is incremented twice, and it is also printed out, exactly as you'd expect.
But text has been #defined to be a pair of parentheses and a semicolon: ();, and return is replaced with &argv;return
So the code
***emphasized text***
return 0;
becomes:
***emphasized();***
&argv;return 0;
or slightly less oddly formatted:
***emphasized();
***&argv;
return 0;
so the printfs do exactly what it looks like they're going to do, and then emphasized() is called, and it backs up the cursor with a '\r' (carriage return, no line feed) and prints out your 10 11 11.
All the asterisks are just for show, dereferencing pointers but not using the results.
Here's a slightly less obfuscated version that remaps each printf() call to something that ends up constructing the output as described by the original asker. It is slightly more straightforward since it doesn't define a silly emphasized() function. It also avoids unnecessarily dereferencing argv, to avoid undefined behavior in the case that argc is 0.
This version also has the property that the program will also behave as the asker described if the ***emphasized text*** string is removed from the program.
#include <stdio.h>
#define printf(f,x) printf(x>11?"%d\n":"%d ", x>11?x-1:x);
#define emphasized &argv;
#define text if(0)
#define return &argv;return
int main (int argc, char *argv[]) {
int a;
int n = 10;
printf("%d",n);
n++;
printf("%d",n);
a = n++;
printf("%d",n);***emphasized text***
return 0;
}

Resources