#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
void initRandom() {
srand(time(NULL));
}
int intUniformRnd(int a, int b){
return a + rand() % (b-a+1);
}
const char* animaisQuatro[] = {"gato", "urso","vaca"};
int main() {
char quatro[4] = {'*' , '*' , '*', '*'};
initRandom();
printf("%s\n", animaisQuatro[intUniformRnd(0,2)]);
for(int i=0;i<4;i++){
printf("%c", quatro[i]);
}
return 0;
}
I have this code that give me a random animal from the array const char* animaisQuatro[] = {"gato", "urso","vaca","lapa"}; from here
initRandom();
printf("%s\n", animaisQuatro[intUniformRnd(0,2)]);
and then I want to put that random animal in another array letter by letter but I don't know how
First I reduced your code to a minimal and reproducible example (something you should do whenever you ask a question):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
void initRandom() {
srand(time(NULL));
}
int intUniformRnd(int a, int b){
return a + rand() % (b-a+1);
}
const char* animaisQuatro[] = {"gato", "urso","vaca"};
int main() {
char quatro[4] = {'*' , '*' , '*', '*'};
initRandom();
printf("%s\n", animaisQuatro[intUniformRnd(0,2)]);
for(int i=0;i<4;i++){
printf("%c", quatro[i]);
}
return 0;
}
Then you can proceed like this:
int main() {
char quatro[4] = {'*' , '*' , '*', '*'};
initRandom();
// Get the animal name from a random position
char* name = animaisQuatro[intUniformRnd(0, 2)];
// Iterate four times
for (int i = 0; i < 4; i++) {
// Assign each `name` index to its respective `quatro` position
quatro[i] = name[i];
}
printf("%s", quatro);
return 0;
}
Tip: you can avoiding hardcoding the 2 when calling intUniformRnd. Note that
printf("%d\n", (int) sizeof(animaisQuatro));
printf("%d\n", (int) sizeof(char*));
printf("%d\n", (int) sizeof(animaisQuatro) / sizeof(char*));
outputs
24
8
3
Therefore, you can do
int length = (int) sizeof(animaisQuatro) / sizeof(char*);
int pos = intUniformRnd(0, length - 1);
This way, if you want to add more elements to animaisQuatro, you don't need to change the value inside intUniformRnd.
I want to put that random animal in other array letter by letter
To copy a string to another character array, code could use
// Risky
strcpy(quatro, animaisQuatro[intUniformRnd(0,2)]);
That would overflow quatro[] if it is too small and leads to undefined behavior. (Bad)
A better way to copy and prevent buffer overflow and alert of a failure:
int len = snprintf(quatro, sizeof quatro, "%s", animaisQuatro[intUniformRnd(0,2)]);
if (len >= sizeof quatro) {
fprintf(stderr, "quatro too small.\n");
}
Since C99 and selectively afterword, code could use a variable length array to form a right-size quatro array.
const char *animal = animaisQuatro[intUniformRnd(0,2)];
size_t sz = strlen(animal) + 1;
char quatro[sz];
strcpy(quatro, animal);
Yet since intUniformRnd[] is constant, no need to copy the text, just copy the address to a pointer:
const char *quatro = animaisQuatro[intUniformRnd(0,2)];
I am working on some simple string related code(I am beginner in this), when I execute this code I get a warning that I don't understand. this is the code.
#include <stdio.h>
#include <unistd.h>
#include <stdint.h>
#define Extension ".txt"
#define LOG_MIN_FILENAME_SIZE sizeof(double) + sizeof(Extension) + 2
char* buffer[LOG_MIN_FILENAME_SIZE];
int timez = 0;
int minutes = 0;
int main()
{
char _acBuff[LOG_MIN_FILENAME_SIZE];
char* ListOfFiles[14];
for(int i=0; i<14; i++){
sprintf(_acBuff, "%d" "%d"Extension, timez, minutes);
ListOfFiles[i]= _acBuff;
}
for(int i=0; i<14; i++){
sprintf(buffer, "%s", ListOfFiles[i]);
printf("%s", buffer);}
}
and this is the warning:
warning: Format "%s" expects Arguments of type char* but Argument 2 has type "char**"
to my understanding I used the correct Format specifier so what exactly is the issue?
You want this:
#include <stdio.h>
#include <stdlib.h> // needed for malloc
#include <string.h> // needed for strcpy
#define Extension ".txt"
#define LOG_MIN_FILENAME_SIZE sizeof(double) + sizeof(Extension) + 2
char buffer[LOG_MIN_FILENAME_SIZE]; // you want an array of char, not an array of
// pointers to char
int timez = 0;
int minutes = 0;
int main()
{
char _acBuff[LOG_MIN_FILENAME_SIZE];
char* ListOfFiles[14];
for (int i = 0; i < 14; i++) {
sprintf(_acBuff, "%d" "%d"Extension, timez, minutes);
ListOfFiles[i] = malloc(strlen(_acBuff) + 1); // allocate memory for the string
strcpy(ListOfFiles[i], _acBuff); // copy the string
// your code only copies the same
// pointer over and over
}
for (int i = 0; i < 14; i++) {
sprintf(buffer, "%s", ListOfFiles[i]);
printf("%s\n", buffer); // added a \n, so output is readable
}
}
Disclaimers:
there is no error checking whatsoever for brevity
allocated memory is not freed explicitely
sizeof(double) is still wrong here, but doesn't have any consequences. You should find out yourself why.
I have two Character arrays, I would like to make one 2 Dimensional array.
but the Character values seem to be causing a problem, in the way that I tried to initialize them in the 2D array.
what is the proper way to initialize this type of array?
The function "trumplar()" works fine, or as I would expect.
The 2D character array x[22][22] function "trumpsterFire()" fails to be initialized properly.
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
void trumplar(){
int len = 22;
char a[25]={0x3f,0x6,0x5b,0x4f,0x66,0x6d,0x7d,0x7,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71,0x3d,0x76,0x1e,0x38,0x38,0x6d,0x00};
char L[25]="0123456789abcdefghjlpsS";
int i;
for (i = 0; i <=len; i++){
char hit=L[i];
char urd=a[i];
printf("The %d, Value of a is:%c\t Hex val: %c\n",i,hit,urd);
}
}
void trumptsterFire(){
//int xlen = 22;
char x[22][22]={
{0x3f,0},{0x6,1},{0x5b,2},
{0x4f,3},{0x66,4},{0x6d,5},
{0x7d,6},{0x7,7},{0x7f,8},
{0x6f,9},{0x77,a},{0x7c,b},
{0x39,c},{0x5e,d},{0x79,e},
{0x71,f},{0x3d,g},{0x76,h}
,{0x1e,j},{0x38,l},{0x38,p},
{0x6d,s},{0x00,S}
};
}
int main(){
trumplar();
trumptsterFire();
return 0;
}
Use single qoute (') to assign a character.
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
void trumplar(){
int len = 22;
char a[25]={0x3f,0x6,0x5b,0x4f,0x66,0x6d,0x7d,0x7,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71,0x3d,0x76,0x1e,0x38,0x38,0x6d,0x00};
char L[25]="0123456789abcdefghjlpsS";
int i;
for (i = 0; i <=len; i++){
char hit=L[i];
char urd=a[i];
printf("The %d, Value of a is:%c\t Hex val: %c\n",i,hit,urd);
}
}
void trumptsterFire(){
//int xlen = 22;
char x[22][22]={
{0x3f,'0'},{0x6,'1'},{0x5b,'2'},
{0x4f,'3'},{0x66,'4'},{0x6d,'5'},
{0x7d,'6'},{0x7,'7'},{0x7f,'8'},
{0x6f,'9'},{0x77,'a'},{0x7c,'b'},
{0x39,'c'},{0x5e,'d'},{0x79,'e'},
{0x71,'f'},{0x3d,'g'},{0x76,'h'}
,{0x1e,'j'},{0x38,'l'},{0x38,'p'},
{0x6d,'s'},{0x00,'S'}
};
}
int main(){
trumplar();
trumptsterFire();
return 0
;
}
This is my code:
#include<stdio.h>
#include<stdlib.h>
main(){
char *alf="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$%&.",text[64];
int i, alfl=69;
srand(time(0));
for(i=0;i<64;i++)
text[i] = *(alf+rand()%alfl);
printf("%s",text);
}
But at the printf function it print an heart at final of the string.
As others have suggested in the comments (#mbratch and #KerrekSB) you need a null terminator at the end of your string.
Modify your code as follows:
#include<stdio.h>
#include<stdlib.h>
main(){
char *alf="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$%&.",text[64];
int i, alfl=69;
srand(time(0));
for(i=0;i<63;i++)
text[i] = *(alf+rand()%alfl);
text[i] = '\0';
printf("%s",text);
}
And it should work, but as #Simon suggested there can be other things that could help improve your code and understanding of C.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 64
int main() { // If you don't add a return type, int is assumed. Please specify it as void or int.
const char *alf="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$%&."; // This string cant be assigned to. Make sure that you stay "const-correct".
char text[LEN]; // Please avoid magic numbers here too by using a constant
int i, alfl = strlen(alf); // As #Simon says, it is better to not use magic constants.
srand(time(0));
for(i=0;i<LEN-1;i++)
text[i] = *(alf+rand()%alfl);
text[i] = '\0'; // make sure to null terminate your string.
printf("%s",text);
return 0; // If your return type is int, you must return from the function.
}
Several suggestions:
main should return an int:
int main(void)
{
return 0;
}
You should use strlen to determine the length of strings:
alfl = strlen(alf);
It's easier to use array notation:
for(i = 0; i < 64; i++)
text[i] = alf[rand() % alfl];
If you use text like a string, it must be '\0' terminated:
text[63] = '\0';
All I simply want to do is a make a record that starts with C or D randomly and has a number along with it 1-10. so a record would be C10. Can anyone tell me what I am doing wrong here?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
/*
*
*/
int main(int argc, char** argv)
{
char letter[] = { 'C', 'D' };
char record[2];
int r=1;
while (r < 11)
{
char num;
num = r;
record = (letter[rand()%2],num);
r++;
}
return 0;
}
For one obvious point, "C10" requires 4 characters, assuming you want it as a normal C string (3 in the string + 1 NUL terminator) but you've only made room for 2.
At least assuming you want your 1-10 as text characters, you'd typically want to do something like:
sprintf(record, "%c%d", letter[rand()%2], num);
Not that it matters a lot, but you seem to be including a lot of unnecessary headers for what you're doing.
record = (letter[rand()%2],num);
This is not a legal opporation... try this:
record[0] = letter[rand()%2];
record[1] = num;
You want the characters '0'-'9' popping up, but you are assigning the character r a numerical value between 0 and 10. Check out the table of ASCII characters.
I'd try it like this:
char record[4];
for (unsigned r = 0; r <= 10; ++r) {
snprintf(record, sizeof(record), "%c%d", letter[rand() % 2], r);
}