So i have this code in c.It all works fine until i get to the point to read word again.It gets the new word but also the (*A)[size-1] takes the price of the new word.How do i prevent this?
void fuction(char ***A,char ***B,int size)
{
char word[20],word2[20];
printf("Type word .\n");
gets(word);
while(strcmp(word,"0")!=0)
{
printf("Type second word.\n");
gets(word2);
printf("%d",size);
**A=realloc(**A,(size+1)*sizeof(char));
**B=realloc(**B,(size+1)*sizeof(char));
(*A)[size-1]=word;
(*B)[size-1]=word2;
size++;
printf("Type another word to add or 0 to exit.\n");//**it all works fine**
gets(word);
}
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void function(char ***A, char ***B, int *size){
char word[32], word2[32];
printf("Type first word.\n");
scanf("%31s", word);
while(strcmp(word,"0")!=0){
printf("Type second word.\n");
scanf("%31s", word2);
*A =realloc(*A, (*size+1)*sizeof(char*));
*B =realloc(*B, (*size+1)*sizeof(char*));
(*A)[*size]=strdup(word);
(*B)[*size]=strdup(word2);
++*size;
printf("Type another word to add or 0 to exit.\n");
scanf("%31s", word);
}
}
int main(void){
int i, size = 0;
char **w1, **w2;
w1 = w2 = NULL;
function(&w1, &w2, &size);
for(i = 0; i < size; ++i){
printf("%s, %s\n", w1[i], w2[i]);
free(w1[i]);free(w2[i]);
}
free(w1);free(w2);
return 0;
}
Turns out the problem was that i didnt allocate memory for the words in the array.I added these lines and it worked.Thank you for your answers.
(*A)[size-1]=(char*) malloc(31);
(*B)[size-1]=(char*) malloc(31);
This
(*A)[size-1]=word;
(*B)[size-1]=word2;
is not what you think it is.
In c, this means you are assigning the address to the first element of the array word to (*A)[size-1] if you want this to work, provided that you have allocated memory for (*A)[size-1] you should do it this way
strcpy((*A)[size-1], word);
strcpy((*B)[size-1], word2);
You should think about why do you need char ***, generally you wont need more than char **, and don't use gets() use fgets() instead.
Related
got this little problem, I made this code for my task, it should input strings and print it in revese, the loop should end when you enter end, but it doesnt end, I know this is not how you check strings but I don't know how to correct it. Thanks in advance for help.
#include <stdio.h>
#include <stdlib.h>
void reverse(char str[]){
int length;
for(length=strlen(str)-1; length >= 0; length--){
printf("%c",str[length]);
}
}
int main(void){
char str[]="";
while(str != "end"){
printf("\nEnter string: ");
scanf("%s", str);
reverse(str);
}
return 0;
}
you have many problems in your code :
when you write char str[]=""; this is will create a string of size = 1 only which will not accept any string you enter except for only one char , so you should do char str[50]; where 50 is the max expected length of the entered string.
it's not while(str != "end") it's , while(strcmp(str,"end") != 0) as you want to compare the strings itself not addresses
it's better to write scanf("%49s", str); than scanf("%s", str); just to make sure that the entered string will always fit in your array
in this line length = strlen(str)-1; , the strlen function return unsigned long long , so you should typecast that and write length = (int)strlen(str)-1; instead
with this all being said , this is the edited code :
#include <stdio.h>
#include <string.h>
void reverse(char str[]){
int length;
for(length = (int)strlen(str)-1; length >= 0; length--){
printf("%c",str[length]);
}
}
int main(void){
char str[50];
while(strcmp(str,"end") != 0){
printf("\nEnter string: ");
scanf("%49s", str);
reverse(str);
}
return 0;
}
and this is the output:
Enter string:abcd
dcba
Enter string:end
dne
Process finished with exit code 0
I have been working some time on the code below but for some reason there is no way I can print out correctly the chars array of an array after returning it and using it in the main function.
I cannot come up with any other things I could print in the code to check what is wrong. I do have checked other similar posts in the forum but I cannot spot any differences between the answers given there and how my code is written.
Does anyone spot anything wrong?
Many thanks in advance.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_STRING 35
char **getWordsList(size_t *wordsNumber);
int main(){
int wordsNumber;
char **arrayOfArrays=getWordsList(&wordsNumber);
printf("WordsNumber is %d",wordsNumber);
printf("\nPrinting the resulting array of arrays: \n");
for (size_t indx=0; indx<wordsNumber; indx++){
printf("%s ", *(arrayOfArrays+indx)); //WHY ISNT THE STRING PRINTED CORRECTLY ?
}
free(*arrayOfArrays);
free(arrayOfArrays);
return 0;
}
char **getWordsList(size_t *wordsNumber){
printf("Please enter the number of words: ");
scanf("%zu",wordsNumber);
fflush(stdin);
char **wordsList=malloc(sizeof (char *)*(*wordsNumber));
if (wordsList!=NULL){
for (size_t indx=0; indx<*wordsNumber; indx++)
{
char inputWord [30];
printf("Please enter a word: ");
fgets(inputWord,sizeof(inputWord),stdin);
fflush(stdin);
printf("Word is %s",inputWord);
*(wordsList+indx)=malloc(MAX_STRING*sizeof(char));
if (*(wordsList+indx)){
*(wordsList+indx)=inputWord;
printf("Added array component is: %s\n",*(wordsList+indx));
}
}
return wordsList;}
else{
printf("Error in allocating memory for array of arrays");
}
}
Thanks to the help I got from the post comments, I was able to produce a working code. I am posting it so others who are struggling wih similar problems can benefit from it.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_STRING 35
char **getWordsList(size_t *wordsNumber);
int main(){
int wordsNumber;
char **answer=getWordsList(&wordsNumber);
printf("WordsNumber is %d",wordsNumber);
printf("\nChecking: \n");
for (size_t indx=0; indx<wordsNumber; indx++){
printf("%s ", answer[indx]);
free(answer[indx]);
}
free(answer);
return 0;
}
char **getWordsList(size_t *wordsNumber){
long wordsNumberFoo;
char wordsNumberStr [40];
char *wordsNumberPtr;
printf("Please enter the number of words: ");
fgets(wordsNumberStr, sizeof(wordsNumberStr), stdin);
wordsNumberFoo=strtol(wordsNumberStr, &wordsNumberPtr, 10);
*wordsNumber=(size_t)wordsNumberFoo;
char **wordsList=malloc(sizeof (char *)*(*wordsNumber));
if (wordsList!=NULL){
for (size_t indx=0; indx<*wordsNumber; indx++)
{
char inputWord [30];
printf("Please enter a word: ");
fgets(inputWord,sizeof(inputWord),stdin);
inputWord[strcspn(inputWord, "\n")] = 0;
printf("Word is %s\n",inputWord);
strncpy(*(wordsList+indx),inputWord, MAX_STRING);
printf("Added array component is: %s\n",*(wordsList+indx));
}
return wordsList;}
else{
printf("Error in allocating memory");
return NULL;
}
}
I'm learning C Programming and I can't resolve this issue.
This is my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int first;
printf("Write Down Your First Name!\n\n");
scanf("%s", &first);
int last;
printf("\nNow Write Your Sir Name!\n\n");
scanf("%s", &last);
printf("\nYour Full Name is %s\n\n");
system("pause");
return 0;
}
And I want to show the full name written.
Should I use void?
Thanks in advance
first and last should be of char array type instead of int type if you want to store characters into that.
int first; ---> char first[100]; /* define how many char you want in first*/
similarly
int last; --> char last[100];
And while scanning it you don't have to pass &
scanf("%s", first);
scanf("%s", last);
Want to print/show ?
printf("\nNow Write Your Sir Name! %s n\n", first);/* you missed to pass argument to printf */
printf("\nYour Full Name is %s\n\n",first);
How to join both ? Iterate last upto '\0' char and copy each char of last to end of first
int len = strlen(first);
first[len] = ' ';/* if needed, put space at the end of first */
for( i = 0, j = len + 1 ; last[i]!='\0;i++,j++) {
first[j] = last[i]; /* first should have enough space */
}
first[j] = '\0';
Now print it as
printf("\nYour Full Name is %s\n\n",first);
My main goal for this code is to capture the users input and do whatever he wants to do with the choices I have presented, but I'm stuck: when I compile, I can only type the word and the program stops working.
i have no idea where I'm making a mistake.
The is my code:
#include <stdio.h>
#include <string.h>
#define MAX_STRING_LENGTH 100
void grab_user_input(void);
void load_menu(void);
void Count_the_letters(void);
int main(void)
{
grab_user_input();
return 0;
}
void grab_user_input(void)
{
char word;
{
printf("Please enter a single word (25 characters or less): \n");
scanf("%s", &word);
printf("Thanks! The word you entered is: %s\n", word);
}
void load_menu(void)
{
int choice;
do
{
int choice;
printf("\n(:===Menu====:)\n");
printf("1. Count_the_letters\n");
printf("2. Count_the_vowels\n");
printf("3. Reverse_the_word\n");
printf("4. Check_if_palindrome\n");
printf("5. Enter_a_new_word\n");
printf("6. Exit\n");
scanf("%d", &choice);
switch (choice)
{
case 1: Count_the_letters();
break;
}
} while (choice != 3);
}
void Count_the_letters(void)
{
char S[MAX_STRING_LENGTH];
int count;
count = 0;
do {
printf("string:\t");
scanf("%s",S);
if (strcmp(S,"exit") != 0)
++count;
} while (strcmp(S,"exit") != 0);
printf("word count:\t%d\n", count);
}
return 0;
}
scanf("%s", &word);
needs an array of characters to read the data. &word only has space for one character.
You are running into undefined behavior.
Use
char word[26];
scanf("%25s", &word);
The reason is that you are passing the address to the char variable you declared and scanf() is trying to write two bytes where it only fits one.
char word
this declares a char variable, it can hold a single byte
scanf("%s", &word);
whill require at least one byte for an empty string the '\0'.
But also, you declared a lot of functions inside void grab_user_input(void), that is not valid standard c, it might work with some compiler, but it's not standard.
What I'm trying to do in my program is to copy the content of one string to another, in reverse. This part of the program works.
However, I don't want to limit the user for input, so I want to use malloc and realloc. This is my code:
#include <stdio.h>
#include <stdlib.h>
/*copy one string to another, in reverse*/
void copyStr(char *p, char *h){
int i=0,j=0;
int length=0;
length=strlen(p); int l=length;
for (i=0; i<length; i++){
h[i]=p[l-1];
l--;
}
char *temp=&h[0];
for (i=0; i<length; i++){
printf("%c",temp[i]);
}
}
main(){
printf("please enter a string\n");
char c; int i=0; int end=10;
/*allocate initial memory*/
char *p=(char*)malloc(sizeof(end)); char *temp=p;
while (c!='\n')
{
/*reallocate if needed*/
if (i==(end-1)){
end*=2;
temp = realloc(p,end*sizeof(temp));
if (temp!=NULL){
/*this is for myself, to see what the error was*/
printf("error allocating\n");
exit(1);
}
else
free(p);
}
c=getchar();
p[i]=c;
i++;
}
char h [sizeof(p)];
copyStr(p,h);
}
I found out that the realloc function doesn't work and so I am asking for your help.
The program works if the input is very short (i.e 3 chars).
If it longer than 10 letters, it will not reallocate memory.
If it longer than 5, it will print reversly but will send me a message called "stack smashed".
Thank you.
In fact, there are some little tricks to change :
the *temp=realloc(... should become temp=realloc(...
The fact that temp!=NULL is the normal behavior of realloc().
do not forget to change p after the realloc operation if you use it after.
sizeof(p) is the size of a pointer, that is 4 or 8... I turned it into char h [sizeof(char)*(i+1)];
i also added the \0 character at the end of the string. This is useful if you wish to print it or use strlen() and #include string.h. Then you can printf("the result is :\n%s \n",h);
Here goes the code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*copy one string to another, in reverse*/
void copyStr(char *p, char *h){
int i=0,j=0;
int length=0;
length=strlen(p); int l=length;
for (i=0; i<length; i++){
h[i]=p[l-1];
l--;
}
//keep end-of-string character
h[length+1]='\0';
/* char *temp=&h[0];
for (i=0; i<length; i++){
printf("%c",temp[i]);
}*/
printf("the result is :\n%s \n",h);
}
main(){
printf("please enter a string\n");
char c; int i=0; int end=10;
/*allocate initial memory*/
char *p=(char*)malloc(sizeof(end)); char *temp=p;
//signaling end of string
p[0]='\0';
while (c!='\n' && c!=EOF)
{
/*reallocate if needed*/
if (i==(end-2)){
end*=2;
temp=(char*)realloc(p,end*sizeof(char));
if (temp==NULL){
/*this is for myself, to see what the error was*/
printf("error allocating\n");
exit(1);
}
else{
p=temp;
printf("ok here\n");
}
}
c=getchar();
p[i]=c;
i++;
}
//signaling end of string
p[i+1]='\0';
printf("INVERTING STRING\n");
char h [sizeof(char)*(i+1)];
copyStr(p,h);
free(p);
}
! enif krow ot smees ti
Bye,
Francis
Its not *temp its temp. Realloc returns a address of the location where the memory is allocate which you should store in pointer . not storing in the address pointed by pointer already which would make no sense
*temp=(char*)realloc(p,end*sizeof(temp));
to be
temp = realloc(p,end*sizeof(temp));
The pointer is temp, *temp refers to content.