This question already has answers here:
Sizeof vs Strlen
(4 answers)
Closed 3 years ago.
I have simple function that should connect string but in different way.
If i have one string "abc" and another "123" final string should be "a1b2c3".
Here is code
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
char *connStrings(char *s1, char *s2) {
int s1L, s2L,i = 0,k=1,j=0;
s1L = sizeof(s1);
s2L = sizeof(s2);
char* result = (char*) malloc((s1L + s2L));
while (s1[i] != '\0') {
result[j] = s1[i++];
j = j + 2;
}
i = 0;
while (s2[i] != '\0') {
result[k] = s2[i++];
k = k + 2;
}
result[s1L + s2L] = '\0';
printf("\n %s \n", result);
}
int main() {
connStrings("abcdefghi","123456789");
}
So what's the problem?
the final output of this program is still the same "a1b2c3d4e5f6g7h8"
It ignores i and 9 somehow. Even if I add more chars into both strings it still prints the same
"a1b2c3d4e5f6g7h8". I will be thankful for any help or advice.
Use proper function return type and strlen instead of sizeof
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void connStrings(char *s1, char *s2) {
int s1L, s2L, i = 0, k = 1, j = 0;
s1L = strlen(s1);
s2L = strlen(s2);
char *result = (char *) malloc((s1L + s2L + 1 )); // extra one for the `null` terminator `\0`
while (s1[i] != '\0') {
result[j] = s1[i++];
j = j + 2;
}
i = 0;
while (s2[i] != '\0') {
result[k] = s2[i++];
k = k + 2;
}
result[s1L + s2L + 1] = '\0';
printf("\n %s \n", result);
// free memory when you're done
free(result);
}
int main() {
connStrings("abcdefghi", "123456789");
return 0; // or use void
}
When you pass an array as an argument to a function, what you're really passing is a pointer to the first element of the array.
sizeof will not return the length of the buffer in this case, but the size of a pointer.
Fortunately, C strings have the useful property of being terminated with a null character ('\0'), which allows functions like strlen to give you the actual length of the string, even when all you have is a pointer and not the array. strlen works similar to this:
size_t strlen(char *s)
{
size_t ret = 0;
while(*s) ret++, s++;
return ret;
}
Even when calculating the length of a string when you have an actual array, you still shouldn't use sizeof because that will return the entire size of the buffer, which may not be the length of the string within it.
Consider: char s[100] = "Hello World";
sizeof s would be 100; strlen(s) would return 11.
Related
I am having trouble with the very last line in my function, where I am stilly learning the basics of C. I have the signature of this function given and am tasked to write a function to concatenate two strings. The commented line outputs the correct result.
#include <stdio.h>
#include <stdlib.h>
// 1) len = dst-len + max_dst_len
int strlcat(char *dst, const char *src, int max_dst_len) {
int len = 0;
while (dst[len] != '\0') {
len++;
}
int total_len = len + max_dst_len;
char *new_str = malloc(sizeof(char) * total_len);
for (int i = 0; i < len; i++) {
new_str[i] = dst[i];
}
for (int i = len; i < total_len; i++) {
new_str[i] = src[i - len];
}
new_str[total_len] = '\0';
//printf("%s <--\n", new_str);
dst = *new_str;
return total_len;
}
int main() {
char test1[] = "dst";
char test1src[] = "src";
printf("%s\n", test1);
printf("%d\n", strlcat(test1, test1src, 10));
printf("%s\n", test1);
}
You should not be adding max_dst_len to the length of dst. max_dst_len is the amount of memory that's already allocated in dst, you need to ensure that the concatenated string doesn't exceed this length.
So you need to subtract len from max_dst_len, and also subtract 1 to allow room for the null byte. This will tell you the maximum number of bytes you can copy from src to the end of dst.
In your main() code, you need to declare test1 to be at least 10 bytes if you pass 10 as the max_dst_len argument. When you omit the size in the array declaration, it sizes the array just big enough to hold the string you use to initialize it. It's best to use sizeof test1 as this argument, to ensure that it's correct for the string you're concatenating to.
#include <stdio.h>
int strlcat(char *dst, const char *src, int max_dst_len) {
int len = 0;
while (dst[len] != '\0') {
len++;
}
int len_to_copy = max_dst_len - len - 1;
int i;
for (i = 0; i < len_to_copy && src[i] != '\0'; i++) {
dst[len+i] = src[i];
}
dst[i] = '\0';
//printf("%s <--\n", new_str);
return i + len;
}
int main() {
char test1[6] = "dst";
char test1src[] = "src";
printf("%s\n", test1);
printf("%d\n", strlcat(test1, test1src, sizeof test1));
printf("%s\n", test1);
}
Hello guys so I am learning C and I am creating the strcat function and when I print out the values of dest at the index i concatenate a char at I get that char but when I return dest and print it out back in my main function the changes aren't reflected. Can someone please help me out? thanks.
#include <stdio.h>
#include <stdlib.h>
int size_s(char *str) {
int size = 0;
int index = 0;
while (str[index] != '\0') {
size += 1;
index += 1;
}
return (size + 1);
}
/*
* #function: strcat
* #desc: Takes in two char pointers and concatenates them. provided the destination has enough size otherwise undefined behavior can occur. Overwrites the null terminator
*/
char *strcat_s(char *dest, char *source)
{
int index_of_src = 0;
int index_of_dest = size_s(dest);
while (source[index_of_src] != '\0') {
*(dest + index_of_dest) = source[index_of_src];
index_of_src += 1;
index_of_dest += 1;
}
// Add Null terminator
*(dest + (index_of_dest + 1)) = '\0';
return dest;
}
int main(int argc, char **argv) {
char firstname[100];
scanf("%s", firstname);
char lastname[100];
scanf("%s", lastname);
int sizeofFirst = size_s(firstname);
printf("Sizeof first: %d\n", sizeofFirst);
int sizeofSecond = size_s(lastname);
printf("Sizeof second: %d\n", sizeofSecond);
char *concatinated = strcat_s(firstname, lastname);
printf("%s\n", concatinated);
}
The function size_s returns the index of the character after the zero-terminating character '\0' due to this return statement
return (size + 1);
So in this while loop
int index_of_src = 0;
int index_of_dest = size_s(dest);
while(source[index_of_src] != '\0')
{
*(dest + index_of_dest) = source[index_of_src];
index_of_src += 1;
index_of_dest += 1;
}
the array pointed to by the pointer dest is filled after the terminating zero character '\0'.
As a result this call of printf
printf("%s\n", concatinated);
outputs the initially stored string in the array firstname.
Rewrite the function size_s the following way
size_t size_s( const char *s )
{
size_t n = 0;
while ( s[n] != '\0' ) ++n;
return n;
}
In turn the function strcat_s that should be renamed because there is standard function strcat_s can look for example the following way
char * strcat_str( char *dest, const char *source )
{
size_t n = size_s( dest );
while ( ( *( dest + n++ ) = *source++ ) != '\0' );
return dest;
}
There are multiple issues in your code:
the size_s function really computes the size of the string, including the null terminator, but counting the null terminator is not helping for the task at hand, you should instead compute the length of the string, ie: the number of bytes before the null terminator, which is exactly the offset where to copy the second string at the end of the first.
*(dest + (index_of_dest + 1)) = '\0'; does not store the null terminator at the correct place: it places it one step too far. You should write *(dest + index_of_dest) = '\0'; or simply dest[ndex_of_dest] = '\0';
the name strcat_s may conflict with a library function of the same name defined in the infamous Annex K of the C Standard. A different name is preferable.
scanf("%s", firstname); is a security flaw: sufficient long input will cause a buffer overflow and carefully crafted input may allow the user to execute arbitrary code. Use scanf("%99s", firstname); to avoid this.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
int my_strlen(const char *str) {
int index = 0;
while (str[index] != '\0') {
index += 1;
}
return index;
}
/*
* #function: strcat
* #desc: Takes in two char pointers and concatenates them. provided the destination has enough size otherwise undefined behavior can occur. Overwrites the null terminator
*/
char *my_strcat(char *dest, const char *source) {
int index_of_src = 0;
int index_of_dest = my_strlen(dest);
while (source[index_of_src] != '\0') {
dest[index_of_dest] = source[index_of_src];
index_of_src += 1;
index_of_dest += 1;
}
// Add the null terminator
dest[index_of_dest] = '\0';
return dest;
}
int main(int argc, char **argv) {
char firstname[200];
char lastname[100];
if (scanf("%99s %99s", firstname, lastname) != 2)
return 1;
printf("length of first: %d\n", my_strlen(firstname));
printf("length of second: %d\n", my_strlen(lastname));
char *concatenated = my_strcat(firstname, lastname);
printf("%s\n", concatenated);
printf("length of concatenation: %d\n", my_strlen(concatenated));
return 0;
}
This is my program:
Does anyone know why it doesn't work?
My professor asked me to remove a character at an index using pointers, I'm also not allowed to use a for - loop so I'm kind of lost.
int count = 0;
int strl = strlen(s);
char s2 [strl-1];
if (index >= 0 && index < strl){
while(count < strl){
if (count == index){
*(s+index) == *s;
strl--;
}
count++;
}
printString(s);
}
}
Your program won't work because your program don't modify strings.
You can use memmove() to shift the string after the character to be removed left by one character to remove a character. (Pointers are used as the arguments of memmove())
#include <stdio.h>
#include <string.h>
void removeAt(char* str, int idx) {
size_t len = strlen(str);
memmove(str + idx, str + idx + 1, len - idx);
}
int main(void) {
char target[] = "0123456789";
printf("before removing : %s\n", target);
removeAt(target, 5);
printf("after removing : %s\n", target);
return 0;
}
Output:
before removing : 0123456789
after removing : 012346789
In order to remove a character at index i from a string you need to move every character after it one space back:
void remove_at(char* s, size_t i) {
if (!s) return;
while (s[i]) {
s[i] = s[i+1];
i++;
}
}
It's undefined behavior to pass an i >= strlen(s), so beware.
Here is an example using pointers to delete a character at a specific index in a string:
#include <assert.h>
#include <stdio.h>
#include <string.h>
void DeleteChar(int index, char string[])
{
char *ptr;
assert(index >= 0);
assert(index < strlen(string));
ptr = string + index;
while (*ptr != '\0') {
*ptr = *(ptr + 1);
ptr++;
}
}
int main(void)
{
char string[] = "hello world";
DeleteChar(9, string);
puts(string);
return 0;
}
Note, however, that it is safer and simpler to use only indices instead of pointers.
I'm trying to create a function that will receive an array of strings and the size and will return a string made of the biggest ASCII value's letter of each word, and the size of the string has to be precised and I'm not allowed using operator [](which is my main issue).
so for:
char *strArr[SIZE] = { "hello", "and", "good", "morning" };
the function shall return a string with the word
"onor"
.
So i thought of creating a double for loop, first one will lead me into the location of each word in the array and the inside one will help me go through each word.
currently I'm having trouble finding the right format with my pointers to actually go through the letters of my first word.
I'm aware i haven't checked if my memory allocation is valid and also didn't free my memory yet as I'm trying to figure out whats wrong first.
char *bigLetters(char *str[], int size)
{
char *strNew = (char *)malloc((size + 1) * sizeof(char));
char max = 'a';
for (int i = 0; i < size; i++)
{
for (int j = 0; (*(str + i)+j) != NULL; j++)
{
if ((*(str + i) + j) >= max)
{
max = (*(str + i) + j);
}
}
*(strNew + i) = max;
}
*(strNew +(size+1)) = NULL;
return *(strNew);
}
void main()
{
char *strArr[SIZE] = { "hello", "and", "good", "morning" };
char *res = bigLetters(strArr, SIZE);
printf("The new string is --> %s\n", res);
system("pause");
}
It will be easier to use the pointers if you separate the string pointer from its character pointer. Also, the max needs to be reset for each string, and you were writing the final string terminator outside of the memory allocated. You also use NULL where you should be using the character '\0'.
Finally the function was returning the first character of the new string (which I later free).
#include <stdio.h>
#include <stdlib.h>
#define SIZE 4
char *bigLetters(char *str[], int size)
{
char *strNew = malloc(size + 1); // no cast or sizeof necessary
for (int i = 0; i < size; i++)
{
char ch;
char max = 'a'; // moved inside loop
char *ptr = *(str + i); // use a separate pointer
for (int j = 0; (ch = *(ptr + j)) != '\0'; j++) // pull out the character
{
if (ch > max) // >= is not necessary
{
max = ch;
}
}
*(strNew + i) = max;
}
*(strNew + size) = '\0'; // correct the bounds error
return strNew; // just the pointer not its target
}
int main(void) // correct signature
{
char *strArr[SIZE] = { "hello", "and", "good", "morning" };
char *res = bigLetters(strArr, SIZE);
printf("The new string is --> %s\n", res);
free(res); // clean up
system("pause");
}
Program output
The new string is --> onor
Press any key to continue . . .
If you didn't impose odd and unhelpful restrictions upon your coding, you'd be able to quickly see the problems with your code or even avoid making them in the first place. The problem is that the following statement makes no sense - you're comparing a char * with a char as you're only de-referencing str once.
if ((*(str + i) + j) >= max)
This is the same as writing
if ((str[i] + j) >= max)
which you can see the obvious mistake since what you're trying to write is the equivalent of
if ((str[i][j]) >= max)
which would be
if (*(*(str + i) + j) >= max)
Your compiler should be throwing up warnings because comparing between a pointer and an integer is rarely something you'd want to do.
You can use pointers as position indicators and advance them as needed.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 4
char
biggest_ascii(char* str)
{
char c = 0;
int i;
for (i = 0; *str; str++)
if (*str > c)
c = *str;
return c;
}
int
main()
{
int i;
char* strArr[SIZE] = {"hello", "and", "good", "morning"};
char** ppch;// current string
char res_str[SIZE + 1] = {0};/* resulting string,
initilized to 0 to be 0-terminated */
char* pch;// current char position
for (i = 0, ppch = strArr, pch = res_str; i < SIZE; i++, ppch++, pch++)
*pch = biggest_ascii(*ppch);
printf("%s\n", res_str);
return 0;
}
First, (*(str + i)+j) isn't the good way.
You could replace all
(*(str + i) + j)
by :
str[i][j]
Then, you need to reset the max to "a", because it's 'o' when you leave the loop, so your condition become str[i][j] >= o which is not what you want. Do it before the second for.
And I would have used while instead of for for the first loop.
I edited your code and this version is working fine for me :
#include <stdlib.h>
char *bigLetters(char *str[], int size)
{
char *strNew = (char *)malloc((size + 1) * sizeof(char));
int i = 0;
while (i < size) {
char max = 'a';
for (int j = 0; str[i][j]; j++) {
if (str[i][j] >= max) {
max = str[i][j];
}
}
strNew[i] = max;
i++;
}
strNew[i] = '\0';
return strNew;
}
void main()
{
char *strArr[5] = { "hello", "and", "good", "morning"};
char *res = bigLetters(strArr, 4);
printf("The new string is --> %s\n", res);
return 0;
}
str[i] is equivalent to *(str + i) and str[i][j] is equivalent to *(*(str + i) + j).
In your code you are using (*(str + i) + j) which is incorrect.
When char *[] passed to function, it will decay to char **. So, in bigLetters(), you can give char **str as the parameter. Also, it is inline with you requirement - not allowed using operator [].
Instead of hardcoding the dimension SIZE in char *strArr[SIZE], you can give the empty [] and let the compiler assign the dimension based on the size of initializer. In your case, size of initializer is 4 as you have given 4 strings in the strArr initializer. You can compute the size of strArr like this:
sizeof(strArr)/sizeof(strArr[0]);
You can do:
#include <stdio.h>
#include <stdlib.h>
char *bigLetters(char **str, size_t size) {
char *strNew = calloc(size + 1, 1); // sizeof(char) is always 1
// calloc will initialize all bytes in the allocated storage to zero.
// You dont need to add the null terminating character at the end of strNew
if (strNew == NULL)
exit(EXIT_FAILURE);
for (size_t i = 0; i < size; i++) {
for (size_t j = 0; *(*(str + i)+j) != '\0'; j++) {
if (*(*(str + i) + j) > *(strNew + i)) {
// You can directly fill the allocated memory with biggest ASCII
*(strNew + i) = *(*(str + i) + j);
}
}
}
return strNew;
}
int main(void) {
char *strArr[] = { "hello", "and", "good", "morning" };
char *res = bigLetters(strArr, sizeof(strArr)/sizeof(strArr[0]));
if (res != NULL) {
printf("The new string is --> %s\n", res);
free (res);
}
else
printf("bigLetters returned NULL\n");
return 0;
}
Note that void return type main() is not as per standard. Instead, you should use int as return type of main().
I've written a function called safecat that adds one string (called ct) to the end of another string (called s).
The resulting new s is then returned.
In the main function my task is to check if my function worked the intended way, and if so, then print the result of my function safecat.
The problem I have is that when I assign the return value of safecat to another char-string (in this case str) in my main function, the stuff in str which comes from ct is just garbage.
I don't understand where the problem is, if I just do printf("%s", safecat(s, ct)); I get the correct result.
Here you see my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *safecat(char *s, const char *ct);
int main()
{
char s[] = "Twin";
const char ct[] = "Peaks";
char *str = safecat(s, ct);
if(str == NULL){
printf("Error in function!");
return 1;
}
printf("\n%s\n", str);
return 0;
}
char *safecat(char *s, const char *ct){
int i, k, j = 0;
int max_count = strlen(s) + strlen(ct) + 1;
for(i = strlen(s); i < max_count; i = i + sizeof(char)){
*(s + i) = (char *) malloc((strlen(s) + strlen(ct) + 1) * sizeof(char));
if(!(s + i)){
for(k = strlen(s) / sizeof(char); k < i; k++){
free(*(s + k));
}
return NULL;
}
*(s + i) = *(ct + j);
j++;
}
return s;
}
I think the error happens when I assign safecat to str.
When I print out str I get "TwinP' a" instead of "TwinPeaks".
Thanks for helping!
You can not change the size of the array
char s[] = "Twin";
in the function using malloc.
And in any case this loop
for(i = strlen(s); i < max_count; i = i + sizeof(char)){
*(s + i) = (char *) malloc((strlen(s) + strlen(ct) + 1) * sizeof(char));
if(!(s + i)){
for(k = strlen(s) / sizeof(char); k < i; k++){
free(*(s + k));
}
return NULL;
}
*(s + i) = *(ct + j);
j++;
}
does not make sense. For example the expression *(s + i) has type char instead of the type char *. And also it is not clear why a memory is allocated in each iteration of the loop.
A correct approach is to allocate dynamically a new array with the size equal to the sum of the sizes of the source arrays plus one and to copy the source arrays in the allocated array.
Here is a demonstrative program that shows how it can be done. Also you should free the allocated memory when the array is not needed any more.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char * safecat(const char *s1, const char *s2)
{
char *result = malloc(strlen(s1) + strlen(s2) + 1);
if (result != NULL)
{
char *p = result;
while (*s1) *p++ = *s1++;
do { *p++ = *s2; } while (*s2++);
}
return result;
}
int main( void )
{
char s[] = "Twin";
char ct[] = "Peaks";
char *str = safecat(s, ct);
if (str == NULL)
{
puts("Error in function!");
return 1;
}
puts(str);
free(str);
return 0;
}
The program output is
TwinPeaks
Of course you could use standard string functions strcpy and strcat instead of the loops that can be both written even in the return statement
return result == NULL ? result : strcat( strcpy( result, s1 ), s2 );
I think that you misunderstand the meaning of malloc.
You are using malloc as if it would make a new slot in or at the end of a string. malloc(sizeX), however, reserves a new memory block with sizeX bytes somewhere in the memory (rather than at a particular position that you could determine). And the result of malloc is a pointer to a memory block, not a character.
So what you do with expression *(s + i) = (char *) malloc((strlen(s) + strlen(ct) + 1) * sizeof(char)); is actually writing a pointer value (usually something obscure when viewed as characters) as value directly into string s at the position of s's string terminating character;
For your safecat, first reserve memory for the new concatenated result string, then fill it up with your logic (I suppose this is a programming assignment and you are not allowed to use strcpy, right?
int slen = strlen(s);
int ctlen = strlen(ct);
char *result = (char *) malloc((slen + ctlen + 1) * sizeof(char));
for (int i=0; i<slen; i++)
result[i] = s[i];
for (int i=0; i < ctlen + 1 ; i++) // note "i < ctlen + 1" for considering string terminator of ct.
result[i+slen] = ct[i];
When you copy the new string to the old string you wind up putting in the null character after the initial P. What you need to do is as follows.
malloc a new buffer (ns) of the size of maxcount.
strcpy s into ns
strcpy ct into ns + strlen(s)
Note. If you are not allowed to used strcpy(), then write your own version as a function safecpy() in the a similar fashion to safecat()
return ns
Note that you would want to free ns sometime later in the program if you no longer need it.
Thank you to everyone who helped. It was a coding assignment and I was able to figure it out the next day.
The stuff I've written must have seemed to be very chaotic as I've just learned about pointers, and yes, I was not allowed to use 'strcat()' or 'strcpy()'.