#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct card_t{
char value;
char suit[50];
} card_t;
card_t draw(){
card_t karta;
int v = (rand() % 13)+2;
int s = (rand() % 4)+1;
if(v<=9){
karta.value = v +'0';
}else{
if (v==10)
karta.value='T';
if (v==11)
karta.value='J';
if (v==12)
karta.value='Q';
if (v==13)
karta.value='K';
if (v==14)
karta.value='A';
}
if (s==1)
strcpy(karta.suit, "of Spades");
if (s==2)
strcpy(karta.suit, "of Hearts");
if (s==3)
strcpy(karta.suit, "of Diamonds");
if (s==4)
strcpy(karta.suit, "of Clubs");
return karta;
}
void face_up(card_t deck[],int size){
for(int i=0;i<=size;i++){
printf("%c %s\n",deck[i].value ,deck[i].suit);
}
}
int main()
{
int size;
card_t *deck;
deck = malloc(100*sizeof(char));
card_t karta;
karta=draw();
for (int i=0; i<100 ; i++){
deck[i]=karta;
if(strcmp(deck[i].suit,"of Spades")==0 && deck[i].value=='A'){
size=i;
break;
}
karta=draw();
/*THIS ONE*/printf("%c %s\n",deck[i].value ,deck[i].suit);
}
face_up(deck,size);
free(deck);
return 0;
}
If I remove the line marked with /THIS ONE/ , the function face_up won't print anything , but if the line is there it works. Any ideas ? Tried it several times and its the same thing .
I would get double print if i leave it there , which i dont need.
Im sorry for the bad code / formatting but i am kinda new to this and yeah ...
Thank you for your help in advance.
This line here deck = malloc(100*sizeof(char)); allocates memory on the heap to store an array of 100 chars. What you want to do, is to allocate an array of 100 card_t. To do this just replace the statement with the following one:
deck = malloc(100*sizeof(card_t));
Related
I got my code working to an extent, but I need some more help. If I needed to remove the word "an", from sentence: "I ate an apple whilst looking at an ape.", it only removes the first "an" and not the second, how do I repeat the loop so it deletes all "an"s? I need the final sentence, after the code has been ran, to be: "I ate apple whilst looking at ape.". That is the goal im trying to achieve
Sorry for not including the code.
Here it is:
#include "RemoveFromText.h"
#include <stdlib.h>
#include <string.h>
int findFirstSubstring(char textToChange[], char removeThis[])
{
int size = strlen(textToChange);
int subStringLength = strlen(removeThis);
for(int i=0; i<size; i++)
{
if(textToChange[i] == removeThis[0])
{
int j = 0;
while(textToChange[i+j] == removeThis[j])
{
j++;
if(j==subStringLength)
{
return i;
}
}
}
}
return -1;
}
void removeFromText( char textToChange[], char removeThis[])
{
int textLength = strlen(textToChange);
if(findFirstSubstring(textToChange, removeThis) >= 0)
{
int subStringIdx = findFirstSubstring(textToChange, removeThis);
int loopVariabele = 0;
for(loopVariabele = subStringIdx; loopVariabele<textLength; loopVariabele++)
{
textToChange[loopVariabele] = textToChange[loopVariabele + strlen(removeThis)];
}
}
}
Leveraging 'strstr', and 'memmove' standard "C" library functions
// Remove all occurences of 'source' from 'message'.
void removeAll(char *message, char *source)
{
int len = strlen(source) ;
for (char *x = message ; x=strstr(x, source) ; ) {
// Copy everything after 'source', including terminating nul.
memmove(x, x+len, strlen(x+len)+1) ;
} ;
}
Notes:
that solution that not properly address the trailing space(s) after a word. This can be addressed by chaning the 'memmove'.
Probably make sense to make the function return the number of substitutions, or some other meaningful result
I would like to pass the struct array as an argument of the print function and then acces its members for printing. Why do I get a pointer error when I do not pass any pointers?
in main.c:
struct city {
double longitude;
double latitute;
char name[buf_size];
};
int numCitToRead = 10;
struct city cities[25];
printCities(&numCitToRead, cities);
Note: The Struct array gets initialised in a file parsing function. It is always 25 fields long, but if numCitToRead is 10, Only 10 fields will be filled
int printCities(int* t_numCitToRead, struct city t_cities[25]) {
for (unsigned short i = 0; i < *t_numCitToRead; i++) {
printf("\n\n\tCity %d: ", i+1);
printf("\nname:\t\t%s", t_cities[i].name);
printf("\nlongitude:\t%f", t_cities[i].longitude);
printf("\nlatitude:\t%f", t_cities[i].latitute);
}
return 0;
}
I hope someone can help me!
Greetings
Have modified the code and its working now.
let's try it:
#include <stdio.h>
struct city {
double longitude;
double latitute;
char *name;
};
int printCities(int* t_numCitToRead, struct city t_cities[25]) {
for (unsigned short i = 0; i < *t_numCitToRead; i++) {
printf("\n\n\tCity %d: ", i+1);
printf("\nname:\t\t%s", t_cities[i].name);
printf("\nlongitude:\t%f", t_cities[i].longitude);
printf("\nlatitude:\t%f", t_cities[i].latitute);
}
return 0;
}
int main() {
int numCitToRead = 10;
struct city cities[25];
// create dummy data
for(int i =1; i<=25; i++)
{
cities[i-1].name = "name";
cities[i-1].longitude = 10 * i;
cities[i-1].latitute = 10 * 20;
}
printCities(&numCitToRead, cities);
return 0;
}
Thanks!
Thanks to everyone for the great support and helpful comments and suggestions.
After adjusting a few different things which were pointed out by people in this thread, it finally compiled succesfully.
The things I adjusted were:
inlcuded the header file to the city struct data type definition in the printFunctions file
initialized the struct to resolve pointer errors
Thanks for the great feedback and comments / suggestions.
Have a nice day!
Declaration of code:
$char Primeiro[5][20] = {"Pedro", "Tiago", "Ana", "Bruno", "Camila"};
$char Meio[5][20] = {"Oliveira", "Antunes", "Ferreira", "Santos", "Cunha"};
$char Sobrenome[5][20] = {"Cardoso", "Silva", "Azevedo", "Monteiro", "Soares"};
$char *vNomeCompleto[125][60];
$ vNomeCompleto[i][i] = strcat(Primeiro[iPrimeiro], strcat(Meio[iSegundo], Sobrenome[iTerceiro]));
I can not make the vector vNomeCompleto receive the other three vectors.
Can someone help me?
vNomeCompleto declared as array of char* pointers - no memory for strings are allocated, just pointers.
strcat(Meio[iSegundo], Sobrenome[iTerceiro]) - you trying to add 20 more characters to Meio[i] which is has 20 max len - expect "out of bound" error in some cases. The same for first strcat.
Here is a working example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i;
char Primeiro[5][20] = { "Pedro", "Tiago", "Ana", "Bruno", "Camila" };
char Meio[5][20] = { "Oliveira", "Antunes", "Ferreira", "Santos", "Cunha" };
char Sobrenome[5][20] = { "Cardoso", "Silva", "Azevedo", "Monteiro", "Soares" };
char vNomeCompleto[5][400];
for (i = 0; i < 5; ++i)
{
strcpy(vNomeCompleto[i], Primeiro[i]);
strcat(vNomeCompleto[i], Meio[i]);
strcat(vNomeCompleto[i], Sobrenome[i]);
}
return 0;
}
and the vNomeCompleto contains:
PedroOliveiraCardoso
TiagoAntunesSilva
AnaFerreiraAzevedo
BrunoSantosMonteiro
CamilaCunhaSoares
In the following code there is a calling convention error(possibly leading to an eternal loop), and i cannot detect it. I try to verify the code using 'Satabs'. What kind of model can bring the error to the surface. With the following model i get a segfault.
By changing the VLEN and TMAX you can play a bit.
Q1. What is the calling convention error?
Q2. What kind of model would be most appropriate to use for finding the error?
#include <stdio.h>
#if MODEL==1
#define VLEN 3
#define TMAX 4
int trans(int T,int*src,int*dst){
if (T < VLEN && T < TMAX && src[T] < 4){
dst[T]=src[T]+1;
return 1;
} else {
return 0;
}
}
#endif
struct next_state {
int next;
int src[VLEN];
};
typedef struct next_state *iterator_t;
void init(iterator_t iter,int *src){
for(int i=0;i<VLEN;i++){
iter->src[i]=src[i];
}
iter->next=0;
}
int next(iterator_t iter,int *dst){
#ifdef FIX_ARRAY
for(int i=0;i<VLEN;i++){
#else
for(int i=0;i<TMAX;i++){
#endif
dst[i]=iter->src[i];
}
int res=0;
while(!res&&iter->next<TMAX){
res=trans(iter->next,iter->src,dst);
iter->next++;
}
return res;
}
int find_depth(iterator_t iter,int *src){
int table[VLEN*TMAX];
int N=0;
init(iter,src);
for(int i=0;i<TMAX;i++){
if(next(iter,&(table[N*VLEN]))){
N++;
}
}
int depth=0;
for(int i=0; i<N;i++){
printf("Eimai stin for \n");
int tmp=find_depth(iter,&(table[i*VLEN]));
printf("tmp= %d\n",tmp);
if(tmp>=depth){
depth=tmp+1;
//assert(depth);
}
}
printf("\n\n");
return depth;
}
int main(int argc,char*argv[]){
int state[VLEN];
struct next_state ns;
for(int i=0;i<VLEN;i++){
state[i]=0;
}
int depth=find_depth(&ns,state);
printf("depth is %d\n",depth);
}
int depth=find_depth(&ns,state);
You are passing &ns, but taking arg in function as iterator_t iter, is this correct ?
void init(iterator_t iter,int *src){
for(int i=0;i<VLEN;i++){
iter->src[i]=src[i];
iter->src[i] is this expression fine?
I dont know 'Satabs' but the most promising candidate for an endless loop for me seems to be
while(!res&&iter->next<TMAX){
res=trans(iter->next,iter->src,dst);
iter->next++;
}
All other loops rather look like fix count.
This loop might be dangerous for itself even without the so called calling convention error, which doest jump to my eye yet.
Anyhow you should take a look not only to the call of the funtion trans but the whole call tree to it.
You could also try to paste your code there
http://gimpel-online.com//cgi-bin/genPage.py?srcFile=intro.txt&cgiScript=analyseCode.py&title=Introduction+and+Welcome&intro=Introducing+the+testing+facility&compilerOption=online32.lnt&in
Maybe you get a few more hints.
Just a guess:
Maybe 'Satabs' doesn't like undefined preprocessor conditions
like
#if MODEL==1
In the below code I am not getting why the win[] is not getting the values. I have commented on the line in the code below where I am confused.
Pls help me guys.
Am I doing any conceptual mistake.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
void winner(int *speed,int *distance,int rats){
float winner=(float)distance[0]/speed[0];
float time;
float *win=malloc(rats * sizeof(float));
memset(win,0,rats*sizeof(float));
for(int i=0;i<rats;i++) {
time=(float)distance[i]/speed[i];
if(time<=winner) {
win[i]=time; /*Problem is here*/
}
}
for(int i=0;i<rats;i++) {
if(win[i]!=0) {
printf("%d\n",i+1);
}
}
free(win);
}
int main() {
int rats;
int *speed,*distance;
scanf("%d",&rats);
speed=malloc(rats * sizeof(int));
distance=malloc(rats * sizeof(int));
for(int i=0;i<rats;i++) {
scanf("%d",&speed[i]);
}
for(int i=0;i<rats;i++) {
scanf("%d",&distance[i]);
}
winner(speed,distance,rats);
free(speed);
free(distance);
return 0;
}
There are at least 3 problems in your code :
you do not change winner if one rat's time if shorter than first one
you do not initialize win[i] for not winners
you do no use the best time to display winning rats
So instead of :
if(time<=winner){
win[i]=time; /*Problem is here*/
}
you should have :
win[i]=time; // always initialize !
if(time<=winner){
winner = time; // keep best time
}
and then instead of
for(int i=0;i<rats;i++){
if(win[i]!=0){
printf("%d\n",i+1);
}
}
you should have :
for(int i=0;i<rats;i++){
if(win[i] == time){ // display all rats having best time
printf("%d\n",i+1);
}
}