C language beginner [closed] - c

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 5 years ago.
Improve this question
I'm learning C language following Youtube video and I've got couple of questions.
I typed these below in Xcode
#include<stdio.h>
int main() // 1. why do we have to use this line?
{
char food[] = "tuna";
printf("the best food is %s",food);
strcpy(food,"bacon"); // error here
return 0;
}
When I typed these all, the error come out saying " implicity declaring library function 'strcpy' with type 'char*(char*,const char*)'"
I have no idea what this mean and why it happened? Sorry to bother with question guys but I need your help. Thank you

C is a super great language to learn but because of how low level it is in comparison to python, javascript, etc. There are many manual tasks you need to do including memory management.
But before we get into that, your initial problem is not including the string.h header. Once you include that header, you'll actually get Segmentation Fault.
Below is the explanation on why you'll get the Segmentation Fault.
So when you defined:
char food[] = "tuna"
C created char array with 5 bytes. Why 5? because all strings end with a NULL byte ('\0').
So your string in memory looks like "tuna\0".
Side note:
The importance of the NULL byte is to signify the end of a string. This is super important when you are using a function like printf. Because when printing a string, printf will look for the NULL byte to stop printing.
So this char array has the max size of 5 bytes, 1 being a null byte, so just 4 bytes (chars) of writeable memory.
Then you try to copy the word "bacon" into your 5 byte array.
So strcpy tries to copy the b, then the c, then the o, then the n, then when it tries to terminate the string with a NULL byte, it will seg fault because you're trying to access a byte of memory you don't have access to.
So in order to fix your issue, you could try to strcpy a string that is the same length or shorter than your original string. Or you can look into something like strdup and use pointers.
That code will look like:
#include <stdio.h>
#include <string.h>
int main()
{
char *food = "tuna";
printf("the best food is %s\n",food);
food = strdup("bacon");
printf("the best food is %s\n",food);
return 0;
}
Hope this helps!

I suggest you as exercise to explain me the behavior of this code. You have to understand how "strings" are managed by the C language into the memory.
The code I post below is not right, contains a violation of the space allocated for the variable food. In this case this code doesn't generate a Segmentation Fault, but It might generate such a error!
If you compile the code below with gcc -Wall --pedantic -std=c99 prgname.c
, the compiler doesn't signal warnings nor error, but the code is NOT RIGHT.
PAY ATTENTION! :)
#include <stdio.h>
#include <string.h>
int main() // 1. why do we have to use this line?
{ // --- 'cause is a standard!!! :)
char food[] = "tuna";
char b[]="prova";
printf("the best food is %s - %s - food-size %u\n",food,b,(unsigned int)sizeof(food));
strcpy(food,"fried or roasted bacon"); // error here
printf("the best food is %s - %s - food-size %u\n",food,b,(unsigned int)sizeof(food));
return 0;
}

We have to use main(),this is the function through which execution of C program starts.
For using strcpy()(A predefined function) you need to declare it first. and its declaration is present in string.h so just #include<string.h>
This will resolve your problem.implicit declaring library function 'strcpy' with type'char*(char*,const char*)``
There is one more problem when you declare
char food[]="tuna";
you get only 5 bytes allocated for you,four for character and one more for NULL. When you will try putting baconin it (using strcpy()),which is 6 bytes long. It will cause compiler to create segmentation fault.

Related

Why is a strange character appearing on my screen? [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 9 months ago.
Improve this question
I am new to C, I have written a very simple program to get the first name and surname, here is my code...
#include <stdio.h>
#include <conio.h>
int main(){
int num,bankpin;
char fn[20],sn[20];
printf("Welcome to authorization. We ill now begin the process");
printf("\nFirst, please enter your first name: ");
scanf(" %s",fn);
printf("\nEnter your surname: ");
scanf(" %s",sn);
printf("\nWelcome to the system %c %c",&fn,&sn);
return 0;
}
Welcome to authorization. We ill now begin the process
First, please enter your first name: A
Enter your surname: A
Welcome to the system α
Why is this strange "a" appearing on my screen instead of "A A"?
In fact it appears on my screen even if I try a different combination of letters
I have even tried recompiling the code
I'm guessing this is because you are trying to print &fn, which is a pointer, as char. You're basically telling the program to interpret the address o as a symbol code.
Try changing the
printf("\nWelcome to the system %c %c",&fn,&sn) to
printf("\nWelcome to the system %s %s",fn,sn)
Short answer
You are sending the array pointer's address as an argument, and telling printf to interpret it as a single char, resulting in undefined behavior. The fix is to replace the line
printf("\nWelcome to the system %c %c",&fn,&sn);
with
printf("\nWelcome to the system %s %s",fn,sn);
Long answer
The weird character is due to your code reading an unintended value, and trying to interpret it. If you run your code a few times, you will find that you don't always get this symbol, but many other ones, including nothing at all (seemingly). What is going here ?
The short answer is that you are misinforming the printf function by giving her a false symbol and a false value. Let's look at a similar example :
char myString[20] = "Hello!";
printf("%c", &myString);
In this snippet we create an array of characters, which actually means creating a pointer of char* type, and allocating its size (here to 20). Pointers are often confusing when starting with C, but they are in principle pretty simple : they are simply variables that, instead of containing a value, contain an address. Since arrays in C store their value sequentially, that is one after the other, it makes quite a lot of sense to have them be pointers : if you know where the array starts, and that its members are spaced evenly, it makes it quite easy to go over the array.
So since your array is a pointer, reading it directly will print something along the lines of "0x7ffc5a6dbb70". Putting '&' before it gives a very similar result : this operator consists in asking for the address of a variable, which is then in your code transmitted to the printf as an argument.
This doesn't make any sense there : a char is, in C, behind the scene, actually an integer variable with very small capacity, from 0 to 255 to be precise. For example the two lines in the following snippet produce the same result :
printf("%c", 'a');
printf("%c", 97);
Now you see what is happening in the original printf : the function is expecting to receive a very small integer to convert to one character, and instead receives an address, which is the reason why the output is so weird. Since addresses change basically at every run of the code, that is also the reason why the output changes very often.
You thus need to adapt the information in the printf function. First, inform that you wish to print a char array with the symbol "%s". This will make the function expect to receive a pointer to the first element of a char array, which it will then iterate over. Thus, as argument, you need to send this pointer, that you directly have in the form of the myString variable.
Thus running
char myString[20] = "Hello!";
printf("%s", myString);
prints 'Hello!', as expected :)
The funcion scanf is a little tricky, please delete the leading space, inside quotes only include what are you expecting to receive, ever.
scanf("%s",fn);
The printf function needs %s, same as scanf, to deal with string, later you don't need the & operator in this case.
printf("\nWelcome to the system %s %s",fn,sn);

C chars add themselves up for no reason [duplicate]

This question already has answers here:
Space for Null character in c strings
(5 answers)
Closed 3 years ago.
I think I'm going insane because I cannot find an explanation to why C is combining my chars.
I've made you guys a test programm...
#include <stdio.h>
#include <stdlib.h>
int main()
{
char alphabet_big[26] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char alphabet_small[26] = "abcdefghijklmnopqrstuvwxyz";
printf("%s\n", alphabet_small);
return 0;
}
Results: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZV
Why is C combining alphabet_small and alphabet_big? That's not making sense. And why is there a "V" at the end of the char?
I hope someone can provide me an answer to this "problem".
Best regards.
Keep in mind that a C String is defined as a null terminated char array.
Change the declaration and initialization statement here: (for both statements.)
char alphabet_big[26] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//forces compiler to use only 26 char
//regardless of the count of initializers
//(leaving no room for NULL terminator)
To
char alphabet_big[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//allows compiler to set aside
^^ //the proper space, no matter how many initializers
The first produces undefined behavior when using with any of the string functions, such as strcpy, strcmp, and in this case printf with the "%s" format specifier.
The first produces the following, which is not is not a C string:
|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|?|?|?|
While the 2nd produces the following, which is a C string:
|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|\0|?|?|
Note - The ? symbols used in above illustration depict memory locations that are not owned by the program, and for which the contents are unknown, or may not even exist. A program attempting to access these locations would be invoking undefined behavior.
Normally the library functions expect to find a NUL byte at the end of a string, and the compiler is happy to add it for you automatically except you've told it that alphabet_big has only 26 bytes, essentially avoiding that extra NUL byte, so it combines with what's next.
Remove the 26 and let the compiler count for you.

Error Copying 1 string to another in C [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 8 years ago.
Improve this question
I was trying to copy the contents of 1 string to another (a into b) .
I deliberately took the second string(b) to be smaller than the 1st
one(a) .
I copied the contents of the first one into second
. I added WATCH on both of them . In the Debug tab , I found out that while
copying the original string gets destroyed and the new one also
DISPLAYED LARGER than its size.
#include<stdio.h>
int main()
{
char a[10]="What?";
char b[2];
int i;
for(i=0;i<6;i++)
{
b[i]=a[i];
}
printf("This is %s",a);
printf("\n this is b now: ",b);
return 0;
}
I have attached the screenshot for the same. I took a = a string of
size 10 . a="WHat?" then I took a string b[2]
After copying , I printed both a and b . I expected the output to be
, a = "WHat?" , b="WH" But the output is coming something else.(See
the screenshot)
Why did the original string get destroyed ? Has the pointer changed ? But I have made it a constant pointer .It can't be changed.
Here is the Screen shot to the problem I am facing :
https://www.dropbox.com/s/8xwxwb27qis8xww/sjpt.jpg
Please Help Somebody !!
You are copying 6 bytes into an array of two bytes, essentially invoking undefined behavior.
You are passing array b to printf with %s specifier that expects a null-terminated string, while b is most likely not null-terminated at that point, which is another undefined behavior.
Also, a null-terminated string that can fit into 2 bytes array can essentially have only one printable character, so you should not expect b to be "WH". At best, if you fix the copying, it can only be "W" as the second character will be a termination byte (\0). If you want to have two characters, either increase the array size to 3 to allow for null terminator, or simply do not use C strings and print out two bytes using "%c%c" format string.
As pointed out in other answers, you are writing outside the bounds of the array. The original string a changes because it happens to be exactly after b in memory as you can see in the debug window.
Before the loop, memory looks like this:
b a
|00|WHat?00000|
After the loop, memory looks like this:
b a
|WH|at?0?00000|
This explains why
a is changed
the original questionmark in a is still there (you only write 6 characters - two into the location reserved for b, 4 (including null terminator) into the location of a)
Of course this is undefined behavior as already mentioned by Vlad Lazarenko, but it explains the behavior for your compiler/settings/version/etc.
A constant pointer only exists for the compiler. It ensures that you cannot explicitly manipulate its data, but if you have memory leaks, nothing can be guaranteed.
What you're doing currently is very unsafe! It might work on Windows for some godforsaken reason, but don't do this!
The C standard library has special functions for working with strings and memory, strcpy for example is for copying character arrays. I suggest you learn more about how strings work and how you can manipulate them.

I am trying to do a program that picks a vowel from the user input [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *v= "a";
char *o='e';
char * w='i';
char *e='o';
char *l='u';
char *u[1];
printf ("please enter your character\n");
scanf ("%c",& u);
if (u == v){
puts("the character is it a vowel\n");
}
if (u == o) {
puts("the character is it a vowel\n");
}
else
puts("the character is a constant\n");
system("PAUSE");
return 0;
}
i need help in getting the right answer in finding a vowel from the user input.
First of all, shame on you for ignoring all of the compiler warnings you certainly received. They are there to help prevent you from doing "stupid things."
And why all this nonsense? This is the first of the "stupid things" the compiler is trying to tell you about.
char *v= "a";
char *o='e'; // invalid - Initializing a pointer to a constant 'e' (101).
char * w='i'; // invalid
char *e='o'; // invalid
char *l='u'; // invalid
Are you familiar with how pointers work? If not, I suggest you do some reading and understand them.
The first line makes sense - you're making a string and pointing char* v to that string.
But there's really no point in using pointer for those characters - or even variables at all. Just compare them directly:
char my_character;
if (my_character == 'a') {
// do something
}
And as for reading the character, again, you're using pointers when it doesn't make sense:
char *u[1]; // why?
Instead, just define a single char variable. Now, go look at the documentation for scanf. Giving it a format string of "%c" means, "I want to read just one character". Then, you need to tell where scanf to put it. You do this by passing it the "address of" the variable you want to store it in. You do this with (unsurprisingly!) the address of operator &.
char input_character;
scanf("%c", &input_character);
Armed with this information, you should be able to complete your work. Next, I suggest you look into the switch statement.
Finally, you must use consistent formatting (indentation, spacing) and use meaningful variable names, if you have any desire of ever being taken seriously as a programmer. Spelling out "vowel" for your pointless variables may be "cute" but it's total nonsense.
Most importantly, you should never write a single line of code, unless you understand exactly what it does. If you do this, then do not go asking anyone for help (especially not StackOverflow). If you can't explain what your code is doing (or at least what you think it's supposed to do), then you don't deserve for your program to work.

Initializing a variable causing printf to stop working [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
int get_max_horizantal()
{
char str[2];
char strb[2]; //Everything works well unless I put this
extern char shit[1200];
int x,number;
while((3*x+1)<1200)
{
if(number%17==0 && number!=0)
{
x+=2;
number=-1;
}
str[0]=shit[3*x];
str[1]=shit[3*x+1];
int val1=atoi(str);
printf("%d\n",val1);
x++;
number++;
}
}
Ok so this is something I don't get at all...The whole function works well but when I put this
char strb[2];
printf doesn't print anything and there are no compile errors or warnings...
This time I really need help on this one...Thanks in advance.
If you want to use atoi on a char array, you must put a null terminator at the end.
Adding things to the stack changing the behaviour often means you have walked off the end of some memory.
Make str bigger and add the null at the end:
char str[3];
str[2] = 0;
atoi wants a proper string. What you pass it is not a proper string since it's not nul-terminated. This leads to undefined behavior which in your case presents itself as seemingly unrelated change making things work or not work.
The atoi(3) function expects a null-terminated string, that is an array of char containing a zero byte (which conventionally terminates the string).
You should give at least 3 characters to str and zero them before filling them, either using memset or explicitly clearing the last byte:
char str[3];
/* possible alternative:
memset (str, 0, sizeof(str)); // the compiler will optimize that...
*/
str[0] = shit[3*x];
str[1] = shit[3*x+1];
str[2] = (char)0;
Please take the habit of enabling all warnings and debugging information at compile time (e.g. compile with gcc -Wall -g on Linux), and learn how to use the debugger (gdb on Linux).
I'm sure that your compiler is able to warn you that x and number are not initialized, and you should fix that:
int x=0, number=0;
As a rule of thumb, improve your source code till no warnings are given by your compiler (with all warnings requested by e.g. -Wall and possibly even also -Wextra if using gcc). Then use a debugger to debug your code: on Linux the p or print, s or step, d or display, bt or backtrace commands of gdb should become familiar to you.
Consider using snprintf(3) (but don't use the deprecated and unsafe sprintf).
Learn about Undefined Behavior. Your program might apparently happens to work (by lack of luck) but be buggy.

Resources