Check chars in a string while using pointers - c

I want to check each individual char in a string. The string is stored in a pointer.
for some reason I can't, it only let me get the whole string.
here's my code:
int main() {
char *s=(char*)calloc(30,sizeof(char));
s="hello";
printf("%s",&s[2]);
return 0;
}
this code print "llo", i need only 1 char like "l" or "o".
anyone know how i can achieve it?
ty

Use the %c conversion specifier to print a sinlge character instead of %s to print a string.
Also the memory allocation by calloc() is useless, since the pointer to char s get assigned by the address of the first element of the string literal "hello" one statement later.
#include <stdio.h>
int main (void)
{
const char *s = "hello";
printf("%c", s[2]);
return 0;
}
Output:
l
Side Note:
Use the const qualifier to prevent any unintentional write attempts to the string literal that lead to undefined behavior.
If you want to allocate memory and assign/initialize the allocated memory by the string literal "hello", use strcpy() (header string.h):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (void)
{
char *s = calloc(30, sizeof(*s));
if (!s) // Check if allocation failed.
{
fputs("Error at allocating memory!", stderr);
exit(1);
}
strcpy(s, "hello");
printf("%c", s[2]);
return 0;
}
Output:
l
or you can use strdup() (Note: strdup() is not part of the standard C library) which will automatically allocate memory with the string of the string literal passed as argument initialized:
#include <stdio.h>
#include <string.h>
int main (void)
{
char *s = strdup("hello");
if (!s) // Check if allocation failed.
{
fputs("Error at allocating memory!", stderr);
exit(1);
}
printf("%c", s[2]);
return 0;
}
Side note:
"The string is stored in a pointer."
Something like that is not possible. The pointer points to the first element of the string (literal). The pointer does not store a string.

Related

Truncate string with realloc() in C?

For an assignment i´m asked to change a string str3 containing "Hello World!" to "Hello", and to use realloc() to remove the the exess memory. I dont realy know how to do it.
How do i use realloc() to truncate the string?
How do i change the string from "Hello World!" to "Hello"?
The DString is a char* pointer so DString *str is a double pointer char**.
From the main()function we send str3 containing "Hello World!" and a blanc space to the function shrinkDString().
int main() {
shrinkDString(&str3, ' '); // truncate str3 after the blank, only "Hello" remains
shrinkDString(&str3, ' '); // nothing happens, "Hello" remains the same
}
As pre- and postcondition i´m supposed to use assert(). The DString *str is a double pointer to str3 and ch is a blanc space. Storing "hello World!" in str3 uses 13 memory including \0, "Hello" should only use memory of 6 including \0.
void shrinkDString(DString *str, char ch) {
// Shrinks the DString *str up to the first occurence of ch.
// Precondition: str is not NULL
// Precondition: *str is not NULL
/* Postcondition: if str has been truncated, its new length corresponds to the position of ch in the
original str*/
/* Tips:
- think that str is already allocated in memory and may be changed! Only the proper amount of
memory for storing the truncated string is allocated when the function return
- do not forget the char for ending a string '\0'
- useful C functions: realloc.
*/
}
This is what i´ve tried so far but i get a memory leak when using realloc() and assert(*str != NULL); is dereferencing NULL pointer.
void shrinkDString(DString *str, char ch) {
assert(str != NULL);
assert(*str != NULL);
*str = (char*)realloc(*str, 6);
}
I dont know how to continue. Grateful for any help!
You'd do something like
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *s = malloc(100);
strcpy(s, "Hello World!");
printf("1 - s=%p *s = '%s'\n", s, s);
s[5] = '\0';
s = realloc(s, strlen(s)+1);
printf("2 - s=%p *s = '%s'\n", s, s);
return 0;
}
Note that realloc may not actually change the address of the memory block - it may just release the extra space at the end of it, or it may not do anything at all!
Note that this example code doesn't do any of the necessary checking for invalid return values, etc, which you should add.
onlinegdb here
It is not possible only using the realloc. You need also to add the trailing null character.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TEXT "Hello World"
int main()
{
char *ptr = malloc(strlen(TEXT) + 1);
strcpy(ptr,TEXT);
printf("original string: %s", ptr);
ptr = realloc(ptr, 6);
ptr[5] = 0;
printf("realloced string: %s", ptr);
free(ptr);
return(0);
}
How do i use realloc() to truncate the string?
You don't. A string is terminated by a null byte, and realloc() does not change any of the string's bytes. At least not in any way that you could rely on. The entire effect of a shrinking realloc() is, that it will consider the memory beyond the new size as free and safe for reuse by a future malloc() call. So, for example, the code
char* string1 = strdup("Hello World!");
string1 = realloc(string1, 6);
char* string2 = malloc(7);
printf("%s", string2); //reading uninitialized data, don't do this
might conceivably print "World!". It could print "I've encrypted your harddrive, please pay ***$ in bitcoins..." instead. Whatever. The C standard does not care. It is simply one of the possible things that might happen, that the malloc() call returns the memory that was cut off from string1 with the realloc() call. (Real implementations won't actually print "World!" for reasons which are way beyond this question.)
How do i change the string from "Hello World!" to "Hello"?
You terminate the string with a null byte. That's as simple as
(*str)[5] = 0;
Note the parentheses which force the double pointer to be dereferenced before performing the array subscript operation. Once you have cut down the string like this, you can subsequently also shrink the allocation with realloc():
(*str)[5] = 0;
*str = realloc(*str, 6); //5 characters plus one terminating null byte
the following proposed code:
cleanly compiles
performs the desired functionality
checks for and handles errors
and now, the proposed code:
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
void shrinkDString( char **str, char targetChar)
{
char *localStr = *str;
assert(str != NULL);
assert(localStr != NULL);
char *stopChar = strchr( localStr, (int)targetChar );
if( ! stopChar )
{
fprintf( stderr, "target char not in **str\n" );
return;
}
// impllied else, target char found
*stopChar = '\0';
char *temp = realloc( localStr, strlen( localStr ) + 1 );
if( ! temp )
{
perror( "realloc failed" );
exit( EXIT_FAILURE );
}
// implied else, realloc successful
*str = temp;
}

cutting a string when a character is found

I wrote a function that cuts the string "hello world" to "hell" if a 'o' is found.
I keep getting a segmentation fault. I don't know where the mistake could be.
Could anyone help?
Thank you in advance.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* cutString(char* str, char del){
char *newstring =(char*) str;
malloc(sizeof(char)*strlen(str));
int i= 0;
for(; newstring[i]!='\0'&&newstring[i]!=del;i++);
if(i==strlen(newstring))
printf("not found");
else
newstring[i]='\0';
return newstring;
}
int main(){
cutString("Hello World",'o');
return 0;
}
There are two major problems with your code:
char *newstring =(char*) str makes newstring point to the old str. And since you pass a literal string (which is read only) you will have undefined behavior attempting to modify it.
malloc(sizeof(char)*strlen(str)); is a memory leak. And doesn't allocate space for the terminator.
The crash is probably because point one, when you attempt to modify the read-only string literal.
There are a number of problems in your code. The main problem is that you don't assign the return value from malloc to newstring. Besides that you need to malloc an extra byte for the string termination.
Further, your loop must copy characters from str into newstring.
In main you must assign the return value from the function to a char pointer variable to get hold of the new string.
Something like:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* cutString(char* str, char del){
char *newstring = malloc(strlen(str) + 1); // malloc into newstring
int i= 0;
while (newstring[i]!='\0' && str[i] != del) // Stop when a) no more chars in str or b) "del" is found
{
newstring[i] = str[i]; // Copy character from str to newstring
++i;
}
newstring[i]='\0'; // Terminate the string
return newstring;
}
int main(){
char* newstring = cutString("Hello World",'o'); // Save the returned value
printf("%s\", newstring);
free(newstring);
return 0;
}
newstring[i]='\0';
This line is invalid. Modifying string literals is undefined behavior. I would suggest check this out :segmentation fault when using pointer
A better solution would be to use arrays instead of pointers

Is there a possible way to use char in strcmp?

I have this program that's supposed to be a 'chat simulator', the only thing it's supposed to do now is replying 'Hello!' when the user types 'Hello'.
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <string.h>
int main()
{
printf("Chat simulator!\n");
do {
char x;
printf("[User1] ");
scanf("%s",&x);
if (strcmp (x,"Hello") == 0)
{
Sleep(1500);
printf("[User2] Hello!\n");
}
else {}
} while(1);
}
I know that strcmp is only for const char *, not a single char, and that's the problem here, but I couldn't find any other solution for this, since I need to use char x in scanf, so it can't be a const char *. Also it may be possible that I'm using strcmp wrong.
Code:Blocks warning:
passing argument 1 of 'strcmp' makes pointer from integer without a cast*
expected 'const char *' but argument is of type 'char'*
Edit:
So I changed the char to char[16] as #robin.koch told me, and it's all working as it should. Thanks!
You cannot compare a string with a char with strcmp, but it is easy to do by hand:
int samechar(const char *str, char c) {
return *str == c && (c == '\0' || str[1] == '\0');
}
The above function however is not what you need for you problem:
You should read a string from the user, not a single char.
scanf() needs a pointer to a char array for the conversion specifier %s.
Furthermore you should specify the maximum number of characters to store into the this array to avoid potential a buffer overflow.
Finally, scanf() will only read a single word. You probably want to read a full line from the user. Use fgets() for this.
Here is a modified version:
#include <stdio.h>
#include <string.h>
int main(void) {
printf("Chat simulator!\n");
for (;;) {
char buf[100];
printf("[User1] ");
if (!fgets(buf, sizeof buf, stdin))
break;
buf[strcspn(buf, "\n")] = '\0'; /* strip the newline if present */
if (strcmp(buf, "Hello") == 0) {
printf("[User2] Hello!\n");
}
}
return 0;
}
As others have pointed out, you're trying to store a string into a char variable using scanf when chars are only meant to store one character. You should you use a char * or char[] variable to hold your string instead. So change
char x;
printf("[User1] ");
scanf("%s",&x);
//...rest of your code...
to
char * x = malloc(sizeof(char) * 10); //can hold up to ten characters
printf("[User1] ");
scanf("%s",x);
//...rest of your code...
free(x);
Note that if you just want to use a char array instead of a pointer you can replace the first line above with something like char x[10]; and get rid of free(x);

how to make a copy of string into a dynamically allocated character array of the appropriate size?

char input[1000];
I want to copy input into a dynamically allocated character array, how do I approach this problem.
So far I have used strncpy, but get lots of errors.
Are you looking for something like this:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main() {
int i;
char input[1000] = "Sample string";
char *in = malloc(1000 * sizeof(char)); // use dynamic number instead of 1000
strcpy(in, input);
for (i = 0; i < 5; ++i) { // intentionally printing the first 5 character
printf("%c", in[i]);
}
}
The output is:
Sampl
Edit: In C++ the cast is required for malloc, so I write:
(char *)malloc(1000 * sizeof(char))
But in C, never cast the result of malloc().
What you can do is just use strcpy() offer by C string.h after dynamically allocating memory to your array, as shown:
char *input = malloc(1000*sizeof(char));
and if the string you are trying to copy to variable input exceeds the allocated memory size (strlen > 999: don't forget! String has a null terminator '\0' that takes up the additional 1 char space), just realloc as shown:
input = realloc(input, 1000*2*sizeof(char));
/* check if realloc works */
if (!input) {
printf("Unexpected null pointer when realloc.\n");
exit(EXIT_FAILURE);
}

Terminating a pointer to a pointer?

I get no compiler warning from this but it segfaults. So how can I copy a '\0' at the beginning of the string so I can then use strncat ? (The use of strncpy is not allowed and using memcpy and then terminating the string segfaults also.)
I wrote this to illustrate the problem:
void func(char **str)
{
*str = realloc(*str, -);
*str[0] = '\0'; // I get segfault here.
strncat(*str, -, -);
// memcpy(*str, -, -);
// *str[strlen(*str)] = '\0'; // I get segfault here.
}
int main(void)
{
char *str = NULL;
func(&str);
return 0;
}
EDIT: I meant to write strlen(*str) and not strlen(str). Sorry.
The problem with the second segfaulting line is operator precedence.
[] has higher precedence than *, so *str[strlen(*str)] is interpreted as *(str[strlen(*str)]) - that is, dereference the address pointed to by the memory at str + strlen(*str).
You want (*str)[strlen(*str)] - that is, the character at the end of of str-dereferenced.
Segmentation faults occur when the memory being accessed by the program is invalid. It is very likely that the realloc call was not able to allocate the amount of memory being requested. It is a best practice to check whether the memory is properly allocated before proceeding to access it.
I tried this program and works well in my system.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void func(char **str)
{
*str = realloc(*str, sizeof(char) * 20);
if( *str == NULL)
{
printf("Memory allocation failed\n");
return;
}
*str[0] = '\0';
strncat(*str, "hello world", 11);
//memcpy(*str, "hello world", 11); //memcpy also works fine
//(*str) [strlen(*str)] = '\0';
printf("String : %s\n", *str);
}

Resources