Dynamically allocate string to contain user input in C - c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char* a;
scanf("%s",a);
printf("%s", a);
free(a);
return 0;
}
My question is dynamic allocation without static declaration.
I want to do dynamic assignment with just in the input statement.
Internal code or Not by a static declaration...
However, dynamic allocation is not possible with the above input this code.
Is there any other way?
By not touching the inner code or making static declarations.

You could use realloc from <stdlib.h> to achieve it.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
fputs("Input: ", stdout);
char *str = malloc(1);
int c, i;
for (i = 0; (c = fgetc(stdin)) != '\n' && c != EOF; ++i) {
str[i] = c;
str = realloc(str, i + 2);
}
str[i] = '\0';
printf("Output: %s\n", str);
free(str);
return EXIT_SUCCESS;
}
But I would not advise you to do that, because it can be expensive depending on the implementation. Instead I would just create a string with fixed size and prevent a buffer overflow.
char str[20];
scanf("%19s", str);
Or using fgets:
char str[20];
fgets(str, 20, stdin);

Related

How do I convert a string to uppercase using the standard library?

I am trying to use a for loop with ASCII table to make every character in the string uppercase one by one by subtracting the letter number with 32. but I cant use the int i in the char str and str2. how can I do this?
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define STRLEN 200
void string_lower() {
}
void string_upper(char str) {
char str2;
int length = strlen(str);
for (int i = 0; i < length; i++) {
str2[i] = str[i - 32];
}
}
int main() {
char word[STRLEN] = { 0 };
char word1 = 97;
printf("Write a word");
fgets(word, STRLEN, stdin);
string_upper(word);
return 0;
}
You can use toupper() to uppercase one character at a time. This will work for single byte character sets such as ASCII, but not for the UTF-8 encoding in general use today for non English scripts.
Here is a modified version:
#include <ctype.h>
#include <stdio.h>
#define STRLEN 200
char *string_upper(char *str) {
for (size_t i = 0; str[i] != '\0'; i++) {
str[i] = toupper((unsigned char)str[i]);
}
return str;
}
int main() {
char word[STRLEN];
printf("Enter a word: ");
if (fgets(word, STRLEN, stdin)) {
printf("%s", string_upper(word);
}
return 0;
}
The argument must be cast as (unsigned char)str[i] because str[i] has type char and tolower() like all functions and macros from <ctype.h> is only defined for values of the type unsigned char and the special negative value EOF. As char may be signed on some platforms, passing it directly to tolower() would have undefined behavior for negative values such as 'é' and 'ÿ'.
If you just want to make a function to convert your String to upper, maybe you can refer to the below example.
#include <stdio.h>
#include <ctype.h>
#define STRLEN 200
void string2upper(char *str){
int cursor=0;
while(*(str+cursor)!='\0'){
*(str+cursor) = toupper(*(str+cursor));
cursor++;
}
}
void main() {
char String1[STRLEN];
printf("Write a word:\n");
fgets(String1, STRLEN, stdin);
printf("Before : %s\n", String1);
string2upper(String1);
printf("After : %s\n", String1);
}
For the toupper() function, I think you can refer to this Link.
That has a detailed explanation and simple example to understand.
I think to know the function detail is better than only using~

How would I use a null terminator in a char array so when I use fgets for input, it does not make a new line without using string libraries?

I know I essentially need to replace the "\n" with a "\0", but how would I access the array to incorporate this? I can not use string.h library or any other libraries.
#include <stdio.h>
#include <stdlib.h>
int main() {
char buffer[32];
char digits[3];
printf("Enter name:");
fgets(buffer,32,stdin);
printf("Enter age:");
fgets(digits,3,stdin);
char *name;
name = buffer;
int *age;
age = atoi(digits);
happyBirthday(name,age);
return 0;
}
int i = 0;
while (buffer[i] != '\0')
{
if (buffer[i] == '\n') buffer[i] = '\0';
++i;
}

my own similar strcat() function prints only one array of chars

I've been trying to practice programming so I decided to try to type the strcat() function myself, or a similar one you know. I typed this code in order to proceed it and I don't know where the problem is.
#include <stdio.h>
#include <stdlib.h>
void main(){
int i, j;
char a[100]; char b[100];
printf("enter the first string\n");
scanf("%s", &a);
printf("enter the second string\n");
scanf("%s", &b);
for(i =0; i<100; i++){
if(a[i] == '\0')
break;
}
// printf("%d", i);
for(j = i; j<100; j++){
a[j+1] = b[j-i];
if(b[j-i] == '\0')
break;
}
printf("%s", a);
}
there are no syntax errors(I hope)
the compiler gives me that result: It doesn't concatenate the strings, nothing happens.
It gives me the same array the same array the user entered, Does anyone has the answer?
PS: I don't know about the pointers yet.
Implementing strcat as a "naive byte-copy loop" is not hard, just do something like this:
#include <stdio.h>
#include <string.h>
char* strdog (char* restrict s1, const char* restrict s2)
{
s1 += strlen(s1); // point at s1 null terminator and write from there
do
{
*s1 = *s2; // copy characters including s2's null terminator
s1++;
} while(*s2++ != '\0');
return s1;
}
int main(void)
{
char dst[100] = "hello ";
char src[] = "world";
strdog(dst, src);
puts(dst);
}
Professional libraries will do the copy on "aligned chunk of data" basis, to get a slight performance boost.

segmentation fault (core dumped) error in C program

I tried to compile and run the following program to reverse a string using the gcc compiler for linux but it shows the error : segmentation fault (core dumped).I even tried to debug using gdb but it didn't help. The program given below firstly inputs t which is the number of test cases.I tested the program with 3 test cases but after taking the 2nd input from user, the compiler shows error.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* strrev(char*);
int main(int argc, char *argv[])
{
int t,i=0,temp=0;
char *str[10],*rev[10];
scanf("%d",&t); //input the number of test cases
while(i<t)
{
scanf("%s",str[i]);
i++;
}
while(temp<t) //reverse the string and display it
{
rev[temp]=strrev(str[temp]);
printf("%s \n",rev[temp]);
temp++;
}
return 0;
getchar();
}
Function to reverse the string:
char *strrev(char *str)
{
int i = strlen(str)-1,j=0;
char ch;
while(i>j)
{
ch = str[i];
str[i]= str[j];
str[j] = ch;
i--;
j++;
}
return str;
}
You are getting segmentation fault because you haven't allocated space for elements of str.
You need to allocate memory first in main function.
scanf("%d",&t); //input the number of test cases
if(t <= 10)
for(size_t i = 0; i < t; i++)
str[i] = malloc(50); // Assuming string is no more than 50characters.
else
exit(0);
Beside this there are many flaws in your code. Here is the code after fixing them
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void strrev(char*); // Change return type to void
int main(void)
{
int t,i=0,temp=0, ch;
char *str[10];
scanf("%d",&t); //input the number of test cases
while((ch = getchar()) != EOF && ch != '\n'); // To consume newline character after scanf
// Allocate memory for str elements
if(t <= 10)
for(size_t i = 0; i < t; i++)
str[i] = malloc(50); // Assuming string is no more than 50characters.
else
exit(0);
i = 0;
while(i < t)
{
fgets(str[i],50,stdin); // Use fgets instead of scanf to read string
i++;
}
while(temp<t) //reverse the string and display it
{
// Since you are reversing string by flipping the characters the same
// string just pass pointer to it. str[temp] will be updated in function.
strrev(str[temp]);
printf("Reverse is %s \n", str[temp]);
temp++;
}
return 0;
}
void strrev(char *str)
{
size_t i = strlen(str)-1,j=0;
char ch;
while(i>j)
{
ch = str[i];
str[i]= str[j];
str[j] = ch;
i--;
j++;
}
//printf("Reverse is %s \n", str);
}
you have missed to allocate memory before reading char* value, so you can do this:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* strrev(char*);
int main(int argc, char *argv[])
{
int t,i=0,temp=0;
char *str[10],*rev[10];
scanf("%d",&t); //input the number of test cases
while(i<t)
{
str[i] = (char*)malloc(100); // just allocate memory
scanf("%s", str[i]);
i++;
}
while(temp<t) //reverse the string and display it
{
rev[temp]=strrev(str[temp]);
printf("%s \n",rev[temp]);
temp++;
}
return 0;
getchar();
}
char *str[10],*rev[10];
You did not assign storage to hold string values yet for those pointers.
char * str; /* this is a string pointer */
char * str = malloc(15); /* this creates storage for a string */
char str[10]; /* this creates a static char array, also is a string */
I also had the same issue. I just fixed it by correcting the indices of the matrix.

How can I read a string in c? [duplicate]

This question already has answers here:
How to read string from keyboard using C?
(6 answers)
Closed 9 years ago.
I use this code, but it's not working.
#include <stdio.h>
#include <string.h>
int main() {
char c, *strx = 0;
c = getchar();
while(c != '\n') {
strx = strcat(strx, &c);
c = getchar();
}
printf("%s\n", *strx);
return 0;
}
How can I put a word into a string?
Change
char *strx = 0
to
char strx [256];
For example:
#include <stdio.h>
#include <string.h>
int main()
{
char c, strx[256] = "";
int i = 0;
c = getchar();
while (c != '\n') {
strx[i++] = c;
c = getchar();
}
printf("%s\n", strx);
return 0;
}
You need to allocate space for strx (here on the stack, you can also you malloc)
#include <stdio.h>
#include <string.h>
int main()
{
char c, strx[100] = "";
int i = 0;
c = getchar();
while (c != '\n') {
strx[i++] = c;
if (i == 99)
break;
c = getchar();
}
strx[i] = '\0';
printf("%s\n", strx);
return 0;
}
strcat doesn't work because it expects a null char at the end but it will probably find garbage after the char.
More simply, you can use scanf:
#include <stdio.h>
#include <string.h>
int main()
{
char strx[100] = "";
scanf("%99s", strx);
printf("%s\n", strx);
return 0;
}

Resources