Printing ���� when adding a string to an array of strings [duplicate] - c

This question already has answers here:
Since I can't return a local variable, what's the best way to return a string from a C or C++ function?
(8 answers)
Return a string from function to main
(3 answers)
How to access a local variable from a different function using pointers?
(10 answers)
Closed 3 years ago.
I kept getting the error "Command terminated by signal 11" when I try to save a string into an array of strings. After changing the code from the link below, now the name prints out ���W.
I used this link to fix my code off of but it is still causing me to get the error "Command terminated by signal 11".
#include<stdio.h>
#include<string.h>
void getName(char* c[], int size);
int main(void) {
int yenoSize = 0;
int strSize = 0;
char name1[30];
char* name[30];
char* students[5][30];
for(int i=0;i<1;i++){
getName(name, strSize);
students[i][0] = name1;
}
for(int k=0; k<1;k++){
printf("Student Name: %s \n", students[k][30]);
}
}
void getName(char* c[], int size){
char name1[30];
printf("Enter student name: ");
fgets(name1, 30, stdin);
c[0] = &name1[0];
printf("%s", name1);
}
The output is supposed to print out the name that the user inputs (Student Name: Jon) but it is currently printing ���W. How can I fix the problem? I believe the problem exists with the name pointer pointing to null. Is that the problem? I appreciate the help!

2 major issues.
1) In main(), you are calling getName() with name but storing name1 in students variable.
2) In function getName(), name1 is a local array. The scope of this variable is limited to getName(). You can not return address of name1 by assigning it to c[0] as it may get freed by OS after function returns. You can consider using malloc() for this.

Related

Why this program showing segmentation fault? [duplicate]

This question already has answers here:
What is the meaning of "wild pointer" in C?
(11 answers)
What is a segmentation fault?
(18 answers)
Closed 7 months ago.
Instead of pointer char *s if I use array char s[100] (in line 4) the code gets executed. Why is that?
#include<stdio.h>
int main(){
int l=0;
char *s;
printf("enter string : \n");
fgets(s,100,stdin);
puts(s);
while(s[l]!='\0'){
l++;
}
printf("length : %d",l-1);
return 0;
}
Because you haven't allocated any memory for s, nor even initialized it to a known value.
That means fgets() is scribbling onto some random address, and your program crashes.
With a local char s[100]; you allocate 100 bytes on the stack, and the value of s is a pointer to the zeroth byte of that allocation.

if/else statement is not validating data [duplicate]

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 4 years ago.
I'm writing a code to better understand if/else statements, but I encountered a problem when trying to validate(?) a string, thanks for any help (C language)
#include <stdio.h>
#include <stdlib.h>
int main(){
char nametype[100];
printf("Enter the name type (firstname/lastname): ");
scanf("%s", &nametype);
script1(nametype);
return 0;
}
void script1(nametype){
char firstname[100];
int age;
char typename[100];
if(nametype == "firstname"){
char typename[100] = "first name.";
}
if(nametype == "lastname"){
char typename[100] = "last name.";
} else {
printf("You must enter the correct parameters! \n");
main();
}
printf("Enter your name: ");
scanf("%s", &firstname);
printf("Enter your age: ");
scanf("%d", &age);
printf("Hey! Your %s is %s, you're %d \n", typename, firstname, age);
}
I expect the code to proceed on to the end after I enter "firstname" or "lastname" in the first input, but instead it always proceeds to go to the else block.
You have a fundamental misunderstanding what the == operator does.
It doesn't compare strings. It compares pointers. If you write
char a[100] = "Hello";
char b[100] = "Hello";
then a == b while compare the pointers. a is a pointer to the array a, b is a pointer to the array b, the pointers are different, the comparison is false.
Use strcmp.
PS. That alone won't make your code work, because you are creating a second variable named "typename" in a nested block. It's a different variable than typename in the outer block, so this will have no useful effect whatsoever.
if(nametype == "firstname"){
char typename[100] = "first name.";
}
In this, nametype is compares to an char array "firstname" ,so you have to use strcmp(str1,str2) function.For use this function, you have to use header. It returns 0 if two strings are equal. Like this
if(strcmp(nametype,"firstname")==0){
// char typename[100] = "first name.";//
}
In the if condition, you have used typename variable which is already declared.So no need to re-declare this variable.
In C, it doesn't support the direct string or char array assignment.So you have to use strcpy(destination,source) function.So the code will be like this
if(strcmp(nametype,"firstname")==0){
strcpy(typename,"first name.");
}

printf wrong output when reversing a string [duplicate]

This question already has an answer here:
Reversing a string literal in C with pointers [duplicate]
(1 answer)
Closed 4 years ago.
so this is the code for reversing a string
#include<stdio.h>
char* function(char *);
int main()
{
char a[]="computer";
printf("%s", function(a));
return 0;
}
char* function(char *p)
{
int l,i;
char t;
for (l=0;*(p+l)!='\0';l++);
for(i=0; i<(l/2) ; i++)
{
t=*(p+i);
*(p+i)=*(p+l-1-i);
*(p+l-1-i)=t;
}
return (p);
}
but if i change printf("%s", function(a)); in the main body to
printf("%s", function("computer"));
there is no output (the output is blank) in dev c++.... but it gives the desired output in turbo c++ even with this change....why is that?
Parameter "computer", which you pass to function, is a string literal, and changing/manipulating the contents of a string literal is undefined behaviour. That's what you are experiencing - something undefined.

Returning string from function is not giving proper output [duplicate]

This question already has answers here:
returning a local variable from function in C [duplicate]
(4 answers)
Closed 7 years ago.
I'm trying to make a function which will receive a char * from the user and will print it.
It turns my value to something weird when I'm printing it.
**//input method**
char* readContactName(){
char tmp[20];
do{
printf("What is your contact name?: (max %d chars) ", MAX_LENGH);
fflush(stdin);
scanf("%s", &tmp);
} while (!strcmp(tmp, ""));
return tmp;
}
void readContact (Contact* contact)
{
char* tmp;
tmp = readContactName();
updateContactName(contact, tmp);
}
**//when entering this function the string is correct**
void updateContactName(Contact* contact, char str[MAX_LENGH])
{
printf("contact name is %s\n",&str); --> prints rubish
}
What did I miss here?
In your code, char tmp[20]; is local to the function readContactName(). Once the function finishes execution, there is no existence of tmp. So, the address-of-tmp also becomes invalid.
So, after returning, in the caller, if you try to use the returned pointer, (as you're doing in updateContactName(contact, tmp);()) it will invoke undefined behaviour.
FWIW, fflush(stdin); is also UB. fflush() is only defined for output streams.
Solution:
Define tmp as to be a pointer.
Allocate memory dynamically (using malloc() or family).
Once you're done using the allocated memory, you need to free() it also.

Variable passes out of scope and memory keeps values [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
I am studying C programming and making some tests in Ubuntu with Geany. I have a question about pointers. When an array is declared in a function and then returned as a pointer, array values are lost in the main method. I could check this with a simple example:
#include <stdio.h>
char* msg ();
int main(int argc, char **argv)
{
char* p = msg();
int i;
for(i=0;i<=10;i++)
printf("i: %d, value: %c \n", i, p[i]);
return 0;
}
char* msg (){
char msg [] = "hello";
return msg;
}
The output is random values (excepting the first one that always is 'h'). I suppose that this is because the pointer passed out of the scope and the memory could be written by other functions.
But if the value of message is bigger enough (like thousands of characters for example or maybe less), values stand in the same memory place and I can read them despite of the array was created in other function.
What is the reason for this results?
Thank you so much.
Returning a pointer to an automatic local variable invokes undefined behavior.

Resources