Below is my code snippet
struct encode
{
char code[MAX];
}a[10];
int main()
{
char x[]={'3','0','2','5','9','3','1'};
for(i=0;i<1;i++)
{
printf("%c",x[i]);
//This will printout like 3025931 now I want this to be stored in structure.
}
strcpy(a[0].code,x);
// or
a[0].code=x;//neither works
display();
}
void display()
{
printf("%c",a[0].code);
}
I want the output to be like:3025931.
Which I am not getting due to incompatible assign type. Please tell me where am i going wrong.
I see two problems here. The first is that the source of the strcpy is a where it probably should be x.
The second is that x is not null-terminated. Strings in C are null-terminated character arrays.
I would change the two lines:
char x[] = {'3','0','2','5','9','3','1'};
strcpy(a[0].code, a);
to:
char x[] = {'3','0','2','5','9','3','1', '\0'};
strcpy(a[0].code, x);
Here's a complete program that gives you what you want (it actually prints out the number twice, once in your inner loop character by character and once with the printf so that you can see they're the same):
#include <stdio.h>
#include <string.h>
#define MAX 100
struct encode {
char code[MAX];
} a[10];
int main() {
int i, j;
char x[] = {'3','0','2','5','9','3','1','\0'};
for(i = 0; i < 1; i++) {
for(j = 0; j < 7; j++) {
printf("%c", x[j]);
}
printf("\n");
strcpy(a[0].code, x);
}
printf("%s\n",a[0].code);
return 0;
}
Update based on comment:
I am sorry. I am new to C. My apologies for not pasting the code snippet correctly in the beginning: "printf("%c",a[0].code);" doesn't display "3025931".
No, it won't. That's because a[0].code is a character array (string in this case) and you should be using "%s", not "%c". Changing the format specifier in the printf should fix that particular issue.
Here,
strcpy(a[0].code, a);
did you mean
strcpy(a[0].code, x);
...?
Also, x needs to be null terminated, or you need to replace strcpy with strncpy or memcpy and pass in a length.
This line doesn't make much sense:
strcpy(a[0].code, a);
Perhaps you want this:
memcpy(a[0].code, x, sizeof x);
a[0].code[sizeof x] = '\0';
(The second line is necessary to nul-terminate code, making it a proper C string).
A lot of things are wrong in your program. The most offending line is this:
strcpy(a[0].code, a);
but there are other oddities as well, e.g.
display is never called
a is only assigned (kind of), but never read (except in display, which is never called)
the i loop makes no sense
Basically, this program looks like copy-pasted by someone who has no clue.
Related
I am writing a program that loops through a text file with two columns. the first values are strings and the second are ints. I am trying to put them in arrays based on their column.
Data example:
stephen 170
shane 150
jake 180
Im trying to do this:
["stephen", "shane", "jake"]
[170,150,180]
For some reason the strcpy function is not working. I am not getting an error message but when I use strcpy and attempt to print the first value of the string array, nothing happens.
#include <stdio.h>
#include <string.h>
int main (void) {
FILE* dict;
char word[50];
int weight;
int weights[50000];
char *words[50000];
dict = fopen("dict.txt", "r");
for (int i = 0; i < 50000; i++) {
fscanf(dict, "%s %d", &word, &weight);
weights[i] = weight;
strcpy(word, words[i]);
}
printf("%s", words[0]);
printf("%d", weights[0]);
return 0;
}
First note that the parameters of strcpy are in the wrong order: the first is the destination and the second is the source, and I guess you want to copy the word string to word[i], so you need to swap the parameters order.
But this won't work either as word[i] points to garbage memory. You'll have to allocate some. You could use for example strdup instead:
words[i] = strdup(word);
Note that it allocates memory on the heap so don't forget to free it once you finished using it.
You have swapped destination and source in your call to strcpy.
Checking man or using a good IDE showing lib function prototypes should help you to avoid that kind of stupid errors for good.
Also, it's mere luck that the program isn't segfaulting as you are reading from words[i] which is an uninitialized array of pointers to chars, you should add a malloc of words[i] before copying to it.
A minimaly fixed (there are still other problems to fix) version of the program could look like below
#include<stdio.h>
#include <string.h>
#include <stdlib.h>
int main (void)
{
FILE* dict;
char word[50];
int weight;
int weights[50000];
char *words[50000];
dict = fopen("dict.txt", "r");
for (int i = 0; i < 50000; i++) {
fscanf(dict,"%s %d", &word, &weight);
weights[i] = weight;
words[i] = malloc(strlen(word)+1);
strcpy(words[i], word);
}
printf("%s", words[0]);
printf("%d", weights[0]);
return 0;
}
Another option would be to use strdup rather than the current code because it does both malloc and strcpy.
Other obvious problems are that your program will have troubles if any word is longer than 50 characters and it's not trivial to fix using scanf. You could use something like fscanf(dict,"%49s %d", &word, &weight); to avoid overflowing word but if the word is too long that will break the parsing loop. (you will get a line with the beginning of the word and the previous value of weight).
And another issue will happen if your dictionary file has less than 50000 entries.
Let's say that the content of your dictionary file has expected format rather than fixing the code.
So I suck with functions and need to debug this. Im pretty sure the function ToPigLating does its job well at converting. However I just need help calling the function ToPigLatin inside of my main function. But when I try doing that I just get a bunch of error codes.
#include <stdlib.h>
#include <string.h>
#define LEN 32
char* ToPigLatin(char* word[LEN]){
char word[LEN];
char translation [LEN];
char temp [LEN];
int i, j;
while ((scanf ("%s", word)) != '\0') {
strcpy (translation, word);
//just pretend I have all the work to convert it in here.
} // while
}
int main(){
printf("Enter 5 words: ");
scanf("%s", word);
ToPigLatin();
}```
Roughly, variables only exist within the function they're declared in. The word in ToPigLatin exists only within ToPigLatin. It is not available in main. This lets us write functions without worrying about all the rest of the code.
You need to declare a different variable in main, it can also be called word, to store the input and then pass that into ToPigLatin.
Let's illustrate with something simpler, a function which doubles its input.
int times_two(int number) {
return number * 2;
}
We need to give times_two a number.
int main() {
// This is different from "number" in times_two.
int number = 42;
// We have to pass its value into time_two.
int doubled = times_two(number);
printf("%d doubled is %d\n", number, doubled);
}
Your case is a bit more complicated because you're working with input and memory allocation and arrays. I'd suggest just focusing on arrays and function calls for now. No scanf. No strcpy.
For example, here's a function to print an array of words.
#include <stdio.h>
// Arrays in C don't store their size, the size must be given.
void printWords(const char *words[], size_t num_words) {
for( int i = 0; i < num_words; i++ ) {
printf("word[%d] is %s.\n", i, words[i]);
}
}
int main(){
// This "words" variable is distinct from the one in printWords.
const char *words[] = {"up", "down", "left", "right"};
// It must be passed into printWords along with its size.
printWords(words, 4);
}
ToPigLatingToPigLating function expects to have a parameter like ToPigLating("MyParameter");
Hello there icecolddash.
First things first, there are some concepts missing. In main section:
scanf("%s", word);
You're probably trying to read a string format and store in word variable.
In this case, you should have it on your declaration scope. After some adjustment, it will look like this:
int main(){
char word[LEN];
As you defined LEN with 32 bytes maximum, your program will not be allowed to read bigger strings.
You're also using standard input and output funcitions as printf, and so you should ever include stdio.h, thats the header which cointains those prototypes already declared, avoiding 'implicit declaration' compiling warnings.
Next issue is how you're declaring your translation function, so we have to think about it:
char* ToPigLatin(char* word[LEN])
In this case, what you wrote:
ToPigLatin is a funcion that returns a char pointer, which means you want your function to probably return a string. If it makes sense to you, no problem at all. Although we got some real problem with the parameter char* word[LEN].
Declaring your variable like this, assume that you're passing an array of strings as a parameter. If I got it right, you want to read all five words in main section and translate each one of them.
In this case I suggest some changes in main function, for example :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 32
#define MAX_WORDS 5
char *globalname = "translated";
char* ToPigLatin(char* word){
char *translation = NULL;
//Translation work here.
if ( !strcmp(word, "icecolddash") ){
return NULL;
}
translation = globalname;
return translation;
}
int main(){
char word[LEN];
char *translatedword;
int i;
printf("Enter 5 words: \n");
for ( i=0; i < MAX_WORDS; i++ ){
fgets(word, sizeof(word), stdin);
strtok(word, "\n"); // Just in case you're using a keyboard as input.
translatedword = ToPigLatin(word);
if ( translatedword != NULL ){
//Do something with your translation
//I'll just print it out as an example
printf("%s\n", translatedword);
continue;
}
// Generic couldn't translate message
printf("Sorry, I know nothing about %s\n", word);
}
return 0;
}
The above code translate every word in a fixed word "translated".
In case of reading the exact input "icecolddash", the program will output a generic error message, simulating some problem on translation process.
I hope this help you out with your studies.
There are a few things that I see.
#include <stdio.h>
#include <stdlib.h>
char* ToPigLatin(char* word){
printf(word);
return word;
}
int main(){
printf("Enter 5 words: ");
// declare the variable read into by scanf
char * word = NULL;
scanf("%s", word);
//Pass the variable into the function
ToPigLatin(word);
// Make sure you return an int from main()
return 0;
}
I left some comments in the code with some specific details.
However, the main thing that I would like to call out is the style of the way you're writing your code. Always try to write small, testable chunks and build your way up slowly. Try to get your code to compile. ALWAYS. If you can't run your code, you can't test it to figure out what you need to do.
As for the char ** comment you left on lewis's post, here is some reading you may find useful in building up your intuition:
https://www.tutorialspoint.com/what-does-dereferencing-a-pointer-mean-in-c-cplusplus
Happy coding!
I know this code is quite simple; but that message won't stop appearing, can you help me find where the error is?
#include <stdio.h>
void Reverse(char * word[]) {
char temp = word[0];
for (int i = sizeof(word); i >= 0; i--){
for (int j = 0; j<= sizeof(word); j ++){
word[0] = word[i];
}
}
word[sizeof(word)] = temp;
printf("%s", word);
}
void main() {
Reverse(gets(stdin));
return 0;
}
gets returns char*. In this context - It is wrong to write char *[] in the function definition where you are supposedly passing a char array where input characters are being stored using gets. Also char *gets(char *str) - you need to pass a buffer to the gets where the inputted letters will be stored. You didn't pass one.
sizeof doesn't work here. It returns the size of a pointer (char*). You will have to use strlen() to get the length of the string inputted by gets.
More importantly - don't use gets - it's time to use something much safer than gets, namely fgets etc. Buffer overflow is not something you want to deal with.
Suppose you are passing an array of char* to the function reverse. Then the parameter would be char*[] which means nothing other than char** here. Here you will simply pass the char array which you will be using as buffer to gets.
This is closely related to an earlier question I asked.
To simulate the operation of a program I'm coding, I'm trying to get the following snippet to work. I need to add strings declared as const char* (such as "Eta" below) into a two-dimensional array char[][] (such as {"Alpha", "Gamma", "Epsilon"}). Here's one of my several attempts:
#include <stdio.h>
#include <string.h>
int main() {
char lines[4][10] = {"Alpha", "Gamma", "Epsilon"};
const char *p = "Eta";
strcpy(lines[4], p);
for (int i = 0; i < 4; i++) {
printf("%d\n", i);
printf("%s\n", lines[i]);
}
return 0;
}
This results in a "stack-smashing" error report, which is apparently related to buffer overflow, but which I suspect has another meaning here.
While I've tried to research the difference between char[] and char*, I haven't found a method that worked. Can someone explain where I'm mistaken?
I'm watching a course online learning C and I stumbled upon something that is crashing my program.
In the video they show the following code snippet :
#include <stdio.h>
int main()
{
char* ch;
int num = 12345;
sprintf(ch, "%d", num);
printf("%s\n", ch);
return(0);
}
I've decided to make my own little program and test it.
Here's the code I've written :
#include <stdio.h>
#define A 65
int main()
{
int n = A;
printf("n is equal to %d\n", n);
n = atoi("10");
printf("n is equal to %d\n", n);
char* ch;
sprintf(ch, "%d", n);
printf("ch is equal to %s\n", ch);
return 0;
}
When I run my program, the output is as follow :
n is equal to 65
n is equal to 10
After this part my program crashes.
I assume the sprintf function is causing this but I'm not sure why, I'm new to the language so I wouldn't know, I think I've done everything correctly judging by the code snippets that was shown in the video.
Could someone please explain me what I did wrong ?
Thanks in advance.
In the video they show the following code snippet: [...]
If this is a snippet that they say should work, stop watching that video: the snippet has undefined behavior, there is no chance that it would work properly unless by an unlucky coincidence.
I've decided to make my own little program and test it.
Your program has the same exact problem: the buffer to which sprintf is writing has not been initialized. Change the declaration of ch to allocate some space to it, like this:
char ch[20];
This will prevent your code from writing to memory pointed to by an uninitialized pointer, fixing the undefined behavior.
Could you explain to me how char* could be used?
If you would like to use char*, assign it a result of malloc of a proper size, and free the result at the end:
char *ch = malloc(20);
... // Put the rest of the code here
// Add this line before the end:
free(ch);
You need to alocate memory for ch or else use an array instead of a pointer.
char* ch = malloc(sizeyouwant * sizeof(char));
Where sizeyouwant is the number of characters you will store.
The problem is here:
char* ch;
this is just a char pointer, it needs to point to allocated memory to hold the string:
char ch[32];