Case 1:
When I take string input, it successfully gives the output, writing this piece of code:
#include <stdio.h>
int main()
{
char *str;
scanf("%s",&str);
printf("%s",&str);
return 0;
}
Case 2:
On the other hand, it throws a Runtime Error for this snippet:
#include <stdio.h>
int main()
{
char *str;
scanf("%s",&str);
printf("%s",str);
return 0;
}
I found this thing peculiar, and want to know why it happens...
Thanks in advance.
None of those two cases are right.
Case 1 only worked because you got lucky, probably by giving a short string as input. Try something like "bfjabfabjkbfjkasjkvasjkvjksbkjafbskjbfakbsjfbjasbfjasbfkjabsjfkbaksbfjasbfkja" and you'll suffer a seg fault, most likely.
You should have a block of memory associated with str, either on the stack by declaring an array for it or on the heap malloc'ing memory for it.
And you shouldn't use the & operator.
So it would go like this:
#include <stdio.h>
int main()
{
char str[50]; // 50 is arbitrary
scanf("%s",str);
printf("%s",str);
return 0;
}
or like this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* str = malloc(50); // 50 is arbitrary
scanf("%s",str);
printf("%s",str);
free(str);
return 0;
}
Related
This code compiles without errors, but upon opening the app, it says:
file.exe has stopped working
#include <string.h>
#include <stdio.h>
int main() {
char *a = 'Hello';
char *b = 'World';
strcat(a,b);
puts(a);
}
Where did I go wrong?
You need to allocate sufficient space and use double quote instead of single quote. You could use array.
#include <string.h>
#include <stdio.h>
int main() {
char a[20] = "Hello";
char b[10] = "World";
strcat(a,b);
puts(a);
}
Constant strings are not modifiable. This is a proper way to declare, initialize and modify a string buffer in C:
#include <string.h>
#include <stdio.h>
int main() {
char a[20];
char *b = "World";
strcpy(a,"Hello");
strcat(a,b);
puts(a);
return(0);
}
You can't do strcat on pointer of characters. You only can do strcat on array of characters .... Sorry for my precedent answer, look at the code below :
#include <string.h>
#include <stdio.h>
int main() {
char a [20];
char b[20];
strcpy(a,"Hello");
strcpy(b,"World");
strcat(a,b);
puts(a);
return(0);
}
I need to put 3 strings on an array[3][3].
I tried to do it with pointers, but I only receive a single character.
#include <stdio.h>
int array[3][3]
char thing[5] = "thing";
main()
{
thing = array[0][0];
printf("%s", array[0][0];
}
Try this. With due respect your code absolutely incorrect and need many changes. You need to update your programming skills too.
#include <stdio.h>
#include <string.h>
char array[3][6]={0};
char *thing = "this";
main()
{
strcpy(array[0],thing);
printf("%s\n", array[0]);
}
I need help to understand why in this little program i cannot manipulate correctly pointers:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void change(char *s[][15]){
int i=0;
while(i<5){
if(s[i][0]=='B') s[i][0]='v';
i++;
}
}
/*My code is supposed to allocate dynamically 5 arrays of 15 chars each
(like tab[5][15])and then put a message on them and try to modify the messages.
In this particular case i'm trying to change the first letter of each string to 'V'.
I'm doing this little experience because of another program
in which i have difficulties accessing double arrays*/
int main(){
int i;
char **s;
s =malloc(5*sizeof(char*));
for(i=0;i<5;i++){
s[i]=malloc(15*sizeof(char));
sprintf(s[i],"Bonjour%d",i);
}
change(s);
for(i=0;i<5;i++){
printf("%s\n",s[i]);
}
return 0;
}
I was expecting :
Vonjour0
Vonjour1
Vonjour2
Vonjour3
Vonjour4
but I get :
Bonjour0
Bonjour1
Bonjour2
Bonjour3
Bonjour4
I'm testing this little code for another program and I don't get why the arrays don't change.
In my other program I can't access the double pointer or print the content.
so my question is : why in this program I can't modify the content of the arrays ?
Your change method needs to use "char** s" instead of char *s[][15]. This is because your method is expecting a pointer to a multi-dimensional array. This is immutable as a result, since your original data type for the string is a pointer to an array of strings (IE: An array of chars).
Hopefully that was clear.
It should be
char **change(char **s){
int i=0;
while(i<5){
if(s[i][0]=='B') s[i][0]='v';
i++;
}
return s;
}
You only need to change the function argument to char *s[].
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void change(char *s[]){
int i=0;
while(i<5){
if(s[i][0]=='B') s[i][0]='v';
i++;
}
}
int main(){
int i;
char **s;
s =malloc(5*sizeof(char*));
for(i=0;i<5;i++){
s[i]=malloc(15*sizeof(char));
sprintf(s[i],"Bonjour%d",i);
}
change(s);
for(i=0;i<5;i++){
printf("%s\n",s[i]);
}
return 0;
}
Program output:
vonjour0
vonjour1
vonjour2
vonjour3
vonjour4
This question already has answers here:
Passing address of array as a function parameter
(6 answers)
Closed 9 years ago.
I'm writing a function that gets a string, allocates memory on the heap that's enough to create a copy, creates a copy and returns the address of the beginning of the new copy.
In main I would like to be able to print the new copy and afterwards use free() to free the memory. I think the actual function works although I am not the char pointer has to be static, or does it?
The code in main does not work fine...
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int make_copy(char arr[]);
int main()
{
char arrr[]={'a','b','c','d','e','f','\0'};
char *ptr;
ptr=make_copy(arrr);
printf("%s",ptr);
getchar();
return 0;
}
int make_copy(char arr[])
{
static char *str_ptr;
str_ptr=(char*)malloc(sizeof(arr));
int i=0;
for(;i<sizeof str_ptr/sizeof(char);i++)
str_ptr[i]=arr[i];
return (int)str_ptr;
}
OK, so based on the comments. A revised version:
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
char* make_copy(char arr[]);
int main()
{
char arrr[]={"abcdef\0"};
char *ptr=make_copy(arrr);
printf("%s",ptr);
getchar();
return 0;
}
char* make_copy(char arr[])
{
static char *str_ptr;
str_ptr=(char*)malloc(strlen(arr)+1);
int i=0;
for(;i<strlen(arr)+1;i++)
str_ptr[i]=arr[i];
return str_ptr;
}
Or even better:
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char* make_copy(char arr[]);
int main()
{
char arrr[]={"abcdef\0"};
printf("%s",make_copy(arrr));
getchar();
return 0;
}
char* make_copy(char arr[])
{
char *str_ptr;
str_ptr=(char*)malloc(strlen(arr)+1);
return strcpy(str_ptr,arr);
}
You're on the right track, but there are some issues with your code:
Don't use int when you mean char *. That's just wrong.
Don't list characters when defining a string, write char arrr[] = "abcdef";
Don't scale string alloations by sizeof (char); that's always 1 so it's pointless.
Don't re-implement strcpy() to copy a string.
Don't cast the return value of malloc() in C.
Don't make local variables static for no reason.
Don't use sizeof on an array passed to a function; it doesn't work. You must use strlen().
Don't omit including space for the string terminator, you must add 1 to the length of the string.
UPDATE Your third attempt is getting closer. :) Here's how I would write it:
char * make_copy(const char *s)
{
if(s != NULL)
{
const size_t size = strlen(s) + 1;
char *d = malloc(size);
if(d != NULL)
strcpy(d, s);
return d;
}
return NULL;
}
This gracefully handles a NULL argument, and checks that the memory allocation succeeded before using the memory.
First, don't use sizeof to determine the size of your string in make_copy, use strlen.
Second, why are you converting a pointer (char*) to an integer? A char* is already a pointer (a memory address), as you can see if you do printf("address: %x\n", ptr);.
sizeof(arr) will not give the exact size. pass the length of array to the function if you want to compute array size.
When pass the array to function it will decay to pointer, we cannot find the array size using pointer.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *strdup(const char *str)
{
char *s = (char*)malloc(strlen(str)+1);
if (s == NULL) return NULL;
return strcpy(s, str);
}
int main()
{
char *s = strdup("hello world");
puts(s);
free(s);
}
Points
~ return char* inside of int.
~ you can free the memory using below line
if(make_copy!=NULL)
free(make_copy)
Below is the modified code.
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
char* make_copy(char arr[]);
int main()
{
char arrr[]={'a','b','c','d','e','f','\0'};
char *ptr;
ptr=make_copy(arrr,sizeof(arrr)/sizeof(char));
printf("%s",ptr);
printf("%p\n %p",ptr,arrr);
getchar();
return 0;
}
char* make_copy(char arr[],int size)
{
char *str_ptr=NULL;
str_ptr=(char*)malloc(size+1);
int i=0;
for(;i<size;i++)
str_ptr[i]=arr[i];
str_ptr[i]=0;
return str_ptr;
}
I am trying to write a small function to trim left spaces from a string, but I cannot get it right. In this version, I get the following error:
bus error: 10
Could anyone please explain to me what I am doing wrong? I am not looking so much for an alternative piece of code, but would like to understand the errors in my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void trim_string(char *);
int main(int argc, char *argv[]) {
char *temp = " I struggle with strings in C.\n";
trim_string(temp);
printf("%s", temp);
return 0;
}
void trim_string(char *string) {
char *string_trimmed = "";
int i=0, j=0;
while (isblank(string[i])) {
i++;
}
while (string[i] != '\0') {
string_trimmed[j] = string[i];
i++;
j++;
}
string_trimmed[j] = '\0';
strcpy(string, string_trimmed);
}
I have now found a workaround solution, shown below. But I am still not very clear about what I did wrong in the first place:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_LENGTH 100
void trim_string(char [MAX_LENGTH]);
int main(int argc, char *argv[]) {
char temp[MAX_LENGTH] = " I struggle with strings in C.\n";
trim_string(temp);
printf("%s", temp);
return 0;
}
void trim_string(char string[MAX_LENGTH]) {
char string_trimmed[MAX_LENGTH];
int i=0, j=0;
while (isblank(string[i])) {
i++;
}
while (string[i] != '\0') {
string_trimmed[j] = string[i];
i++;
j++;
}
string_trimmed[j] = '\0';
printf("c\n");
strcpy(string, string_trimmed);
}
Both string and string_trimmed point to string literals, here in main:
char *temp = " I struggle with strings in C.\n";
^
|
This is a string literal
temp points to a string literal and the standard says you are not allowed to modify them.
In the function trim_string you are modifying a them which is undefined behavior of which a bus error is one possible result, although anything can happen.
string_trimmed either needs to be an array like this:
char string_trimmed[n] ;
where n is the size of your input using strlen(string) would probably make sense or dynamically allocated via malloc which you would need to free at the end of your function. The same things goes for your input from main, this would work as a substitute:
char temp[] = " I struggle with strings in C.\n";
For completeness sake, the draft C99 standard section 6.4.5 String literals paragraph 6 says (emphasis mine):
It is unspecified whether these arrays are distinct provided their elements have the
appropriate values. If the program attempts to modify such an array, the behavior is
undefined.