runtime error on char* but not char[] [duplicate] - c

This question already has answers here:
What is the difference between char s[] and char *s?
(14 answers)
Closed 9 years ago.
I have a piece of code that works fine on char[] but gives a run-time error when performed on a char*.
#include <stdio.h>
#include <string.h>
void rotateLeft(char* str, int pos, int size){
char temp;
int i;
for(i=pos; i < size-1; i++) {
temp = str[i];
str[i] = str[i+1];
}
str[size-1] = temp;
}
void removeAllDups(char* str) {
int size = strlen(str);
int i,j;
char cur;
for (i=0; i<size; i++) {
cur = str[i];
for(j=i+1; j<size;) {
if (str[j] == cur) {
rotateLeft(str, j, size);
size--;
str[size] = '\0';
}
else {
j++;
}
}
}
}
int main(void) {
char str1[] = "hello there";
char* str2 = malloc(sizeof(char)*14);
strcpy (str2, "goodbye matey");
removeAllDups(str1); // succeeds
printf("%s\n", str1);
removeAllDups(str2); // fails
printf("%s\n", str2);
free(str2);
return 0;
}
Run-time error is given when removeAllDups(str2) is reached. What is my problem?

char* str2 = "goodbye matey"; initializes str2 with a pointer to data that should not be changed. While str2 points to such data, modiying it leads to UB.
char str1[] = "hello there";
char* str2 = "goodbye matey";
removeAllDups(str2); // fails
str2 = str1;
removeAllDups(str2); // OK
str2 = "goodbye matey2";
removeAllDups(str2); // fails
str2 = strdup("goodbye matey3");
removeAllDups(str2); // OK

char* str2 = "goodbye matey" is equivalent to declaring static const char str2[] = "goodbye matey". So you cannot modify the content pointed to by str2.

Related

trying copy character from pointer to string [duplicate]

This question already has an answer here:
String literals: pointer vs. char array
(1 answer)
Closed 2 months ago.
I am trying to reverse string using pointer (ref source). in function
string_reverse
Bus Error happened at this line when copying character from char pointer end to start char pointer :
*start = *end;
I tried LLDB in VS code. .
Can some one explain why there is bus error happened at below line?
*start = *end
Full code below:
#include <stdio.h>
#include <string.h>
void string_reverse(char* str)
{
int len = strlen(str);
char temp;
char *end = str;
char *start = str;
/* Move end pointer to the last character */
for (int j = 0; j < len-1; j++)
{
end++;
}
for(int i = 0; i< len/2;i++ )
{
temp = *start;
*start = *end;
*end = temp;
/* update pointer positions */
start++;
end--;
}
}
int main( void )
{
char *str = "test string";
printf("Original string is %s\n", str);
string_reverse(str);
printf("Reverse string is %s\n", str);
return 0;
}
Actual result: Bus Error happened at line
*start = *end;
Expected output:
Reverse string is gnirts tset
The error happens because
char * str = "...";
mean you have a pointer to a string literal. It's a constant string that you can not modify.
When you change it to
char str[] = "...";
as chux-reinstate-monica mentioned, str will be char array with the length of your string, and you can modify it without any error.

Storing tokens from 1D char array to char** array

I am trying to write a program that will dynamically allocate enough space to store all the words in a 1D char array separated by a space.
ex:
char *literal = "The quick brown fox";
char **words = { "The", "quick", "brown", "fox" };
The program I wrote keeps segfaulting when trying to strncpy(str[buff_ptr],tok,strlen(tok));
I will post my code bellow:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *mutableString(char *lit) {
int size = strlen(lit);
char *str = (char *)malloc(sizeof(char) * size);
strncpy(str, lit, size + 1);
return str;
}
int numTokens(char *str, const char *DELIM) {
char* clone = (char*)malloc(sizeof(char*));
strncpy(clone, str, strlen(str) + 1);
int count = 0;
for (char *tok = strtok(clone, " "); tok != NULL; tok = strtok(NULL, " "))
count++;
free(clone);
return count;
}
char **tokenize(char *str, const char *DELIM) {
printf("tokenize-------------------------\n");
int size = numTokens(str, DELIM);
//allocate space on heap for buffer
char **buff = (char **)malloc(size * sizeof(char *));
//get first word
char *tok = strtok(str, DELIM);
int buff_ptr = 0;
while (tok != NULL) {
strncpy(buff[buff_ptr], tok, strlen(tok) + 1);
printf("buff[%d]%s\n", buff_ptr, buff[buff_ptr]);
//increment to next word for storage
buff_ptr++;
//find next word in string
tok = strtok(NULL, DELIM);
}
for (int i = 0; i < size; i++) {
printf("%s\n", buff[i]);
}
//return 2D pointer
return buff;
}
int main() {
char *literal = "some literal string.";
//convert string to mutable string for strtok
char *str = mutableString(literal);
//set 2D pointer equal to the pointer address returned
char **no_spaces_str = tokenize(str, " ");
printf("%s\n", str);
for (int i = 0; i < numTokens(str, " "); i++) {
printf("%s\n", no_spaces_str[i]);
}
//free heap allocated memory
free(str);
free(no_spaces_str);
return 0;
}
Please see attachment of lldb stack variables:
Within the function mutableString there is dynamically allocated the character array str that does not contain a string
char* mutableString(char* lit){
int size = strlen(lit);
char* str = (char*)malloc(sizeof(char)*size);
strncpy(str,lit,size);
return str;
}
So other functions invoke undefined behavior as for example in this for loop
int numTokens(char* str, const char* DELIM){
int count = 0;
for(; *str != '\0'; str++)
//...
Moreover if the array contained a string nevertheless the function numTokens is incorrect because for example it returns 0 when a passed string contains only one word.
Also in the function tokenize
strncpy(buff[buff_ptr],tok,strlen(tok));
there are used uninitialized pointers buff[buff_ptr] allocated like.
char **buff = (char**)malloc(size*sizeof(char*));
And again you are trying to copy strings without including the terminating zero character '\0; using eth functions strncpy.
So this call in main
printf("%s\n",no_spaces_str[i]);
also will invoke undefined behavior.
This is the corrected version of the code above
When you copying string you should add 1 char for '\0'
int size = strlen(lit)+1;
Tokens buffer size should be size+1
int size = numTokens(str, DELIM)+1;
Strncpy is not required strncpy(buff[buff_ptr], tok, strlen(tok) + 1);
you already copied string char* str = mutableString(literal);
just point to n-th buffer every next token buff[buff_ptr]=tok;
for (int i = 0; i<numTokens(str, " "); i++){
printf("%s\n", no_spaces_str[i]);
}
This code wouldn't work correctly. strtok manipulates the string you pass in and returns a pointer to it, so no memory is allocated.
so all spaces will be replaced by '\0'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(push)
#pragma warning(disable : 4996)
char* mutableString(char* lit){
int size = strlen(lit)+1;
char* str = (char*)malloc(sizeof(char)*size);
strncpy(str, lit, size);
return str;
}
int numTokens(char* str, const char* DELIM){
int count = 0;
for (; *str != '\0'; str++)
{
if (*str == ' ')
count++;
}
return count;
}
char** tokenize(char* str, const char* DELIM){
printf("tokenize-------------------------\n");
int size = numTokens(str, DELIM)+1;
//allocate space on heap for buffer
char **buff = (char**)malloc((size)*sizeof(char*));
//get first word
char* tok = strtok(str, DELIM);
int buff_ptr = 0;
while (tok != NULL){
buff[buff_ptr]=tok;
printf("buff[%d]%s\n", buff_ptr, buff[buff_ptr]);
//increment to next word for storage
buff_ptr++;
//find next word in string
tok = strtok(NULL, DELIM);
}
for (int i = 0; i<size; i++){
printf("%s\n", buff[i]);
}
//return 2D pointer
return buff;
}
int main(){
char* literal = "some literal string.";
//convert string to mutatable string for strtok
char* str = mutableString(literal);
//set 2D pointer equal to the pointer addres returned
char** no_spaces_str = tokenize(str, " ");
printf("%s\n", str);
for (int i = 0; i<numTokens(str, " "); i++){
printf("%s\n", no_spaces_str[i]);
}
//free heap allocated memory
free(str);
free(no_spaces_str);
return 0;
}
results
tokenize-------------------------
buff[0]some
buff[1]literal
buff[2]string.
some
literal
string.
some
char* mutableString(char* lit){
int size = strlen(lit)+1;
char* str = (char*)malloc(sizeof(char)*size);
strncpy(str,lit,size);
return str;
}
int numTokens(char* str, const char* DELIM){
int size = strlen(str)+1;
char* clone = (char*)malloc(sizeof(char)*size);
strncpy(clone,str,size);
int count = 0;
for(char* tok = strtok(clone," "); tok != NULL; tok=strtok(NULL, " "))
count++;
free(clone);
return count;
}
char** tokenize(char* str, const char* DELIM){
int size = strlen(str)+1;
char* clone = (char*)malloc(sizeof(char)*size);
strncpy(clone,str,size);
// printf("tokenize-------------------------\n");
int size = numTokens(str, DELIM);
//allocate space on heap for buffer
char **buff = (char**)calloc(size,sizeof(char*));
//get first word
char* tok = strtok(clone,DELIM);
int buff_ptr = 0;
while(tok != NULL){
// printf("token%d:%s\n",buff_ptr,tok);
buff[buff_ptr] = (char*)malloc(sizeof(char)*strlen(tok)+1);
strncpy(buff[buff_ptr],tok,strlen(tok)+1);
//increment to next word for storage
buff_ptr++;
//find next word in string
tok = strtok(NULL, DELIM);
}
//return 2D pointer
free(clone);
return buff;
}
int main(){
char* literal = "some literal string.";
//convert string to mutatable string for strtok
char* str = mutableString(literal);
//set 2D pointer equal to the pointer addres returned
char** no_spaces_str = tokenize(str, " ");
int num_words = numTokens(str," ");
char* oneD = (char*)calloc(strlen(str)+1,sizeof(char));
for(int i = 0;i<num_words;i++){
strncat(oneD,no_spaces_str[i],strlen(no_spaces_str[i])+1);
printf("%s\n",oneD);
}
//free heap allocated memory
free(str);
free(no_spaces_str);
free(oneD);
return 0;
}
Is solution to my problem. Thanks to all those who commented and helped me understand dynamic memory better.
Apart from the #Vlad from Moscow mentioned points,
malloc return values must not be type-casted Do I cast the result of malloc?
I tried to clean up the code find the snippet below, DEMO
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char** buff;
int size;
}Array_2d;
char* mutableString(const char* lit){
int size = strlen(lit);
char* str = malloc(size);
strncpy(str,lit,size+1);
return str;
}
int getNextWordLength(const char* str){
int index = 0;
while(*str && (*str != ' ')){
//printf("%c",*str);
++index;
++str;
}
return index;
}
int numTokens(const char* str){
int count = 0;
for(; *str != '\0'; str++)
{
if(*str == ' ')
count++;
}
return count;
}
void tokenize(const char* str, const char *DELIM, Array_2d *array){
int len = strlen(str)+1;
if(!str && !len){
array->buff = 0;
array->size = 0;
}
int number_of_words = numTokens(str)+1;
//allocate space on heap for buffer
char **buff = (char**)malloc(number_of_words*sizeof(char*));
int index = 0;
do{
//get first word
int word_length = getNextWordLength(str);
//To compensate null terminal
buff[index] = malloc(word_length+1);
strncpy(buff[index], str,word_length);
buff[index][word_length+1] = '\0';
str += word_length+1;
++index;
}while(index < number_of_words);
//update return value
array->buff = buff;
array->size = number_of_words;
}
int main(){
char* literal = "hello world this is test";
//convert string to mutatable string for strtok
char* str = mutableString(literal);
printf("Complete String is : %s\n",str);
Array_2d array;
// set 2D pointer equal to the pointer addres returned
tokenize(str, " ",&array);
printf("Tokenized String\n");
for(int i=0;i<array.size;i++){
printf("%s\n",array.buff[i]);
}
free(str);
for(int i =0;i< array.size; ++i)
free(array.buff[i]);
free(array.buff);
return 0;
}

How to return a pointer to a string in C [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I tried to develop a function which take a string reverse letters and return pointer to string.
char *reverseStr(char s[])
{
printf("Initial string is: %s\n", s);
int cCounter = 0;
char *result = malloc(20);
while(*s != '\0')
{
cCounter++;
s++;
}
printf("String contains %d symbols\n", cCounter);
int begin = cCounter;
for(; cCounter >= 0; cCounter--)
{
result[begin - cCounter] = *s;
s--;
}
result[13] = '\0';
return result;
}
in main function I invoke the function and tried to print the result in this way:
int main()
{
char testStr[] = "Hello world!";
char *pTestStr;
puts("----------------------------------");
puts("Input a string:");
pTestStr = reverseStr(testStr);
printf("%s\n", pTestStr);
free(pTestStr);
return 0;
}
but the result is unexpected, there is no reverse string.
What is my fault?
There are multiple mistakes in the shared code, primarily -
s++; move the pointer till '\0'. It should be brought back 1 unit to
point to actual string by putting s--. Other wise the copied one will start with '\0' that will make it empty string.
Magic numbers 20 and 13. where in malloc() 1 + length of s should be
sufficient instead or 20. For 13 just move a unit ahead and put '\0'
However, using string.h library functions() this can be super easy. But I think you are doing it for learning purpose.
Therefore, Corrected code without using string.h lib function() should look like this:
char *reverseStr(char s[])
{
printf("Initial string is: %s\n", s);
int cCounter = 0;
while(*s != '\0')
{
cCounter++;
s++;
}
s--; //move pointer back to point actual string's last charecter
printf("String contains %d symbols\n", cCounter);
char *result = (char *) malloc(sizeof(char) * ( cCounter + 1 ));
if( result == NULL ) /*Check for failure. */
{
puts( "Can't allocate memory!" );
exit( 0 );
}
char *tempResult = result;
for (int begin = 0; begin < cCounter; begin++)
{
*tempResult = *s;
s--; tempResult++;
}
*tempResult = '\0';
//result[cCounter+1] = '\0';
return result;
}
Calling from main
int main()
{
char testStr[] = "Hello world!";
char *pTestStr;
puts("----------------------------------");
puts("Input a string:");
pTestStr = reverseStr(testStr);
printf("%s\n", pTestStr);
free(pTestStr);
}
Output
----------------------------------
Input a string:
Initial string is: Hello world!
String contains 12 symbols
!dlrow olleH
As per WhozCraig suggestion just by using pointer arithmetic only -
char *reverseStr(const char s[])
{
const char *end = s;
while (*end)
++end;
char *result = malloc((end - s) + 1), *beg = result;
if (result == NULL)
{
perror("Failed to allocate string buffer");
exit(EXIT_FAILURE);
}
while (end != s)
*beg++ = *--end;
*beg = 0;
return result;
}
Your code can be simplified using a string library function found in string.h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *reverseStr(char s[])
{
printf("Initial string is: %s\n", s);
int cCounter = strlen(s);
char *result = malloc(cCounter + 1);
printf("String contains %d symbols\n", cCounter);
int begin = cCounter;
for(; cCounter > 0; cCounter--)
{
result[begin - cCounter] = s[cCounter - 1];
}
result[begin] = '\0';
return result;
}
int main()
{
char testStr[] = "Hello world!";
char *pTestStr;
puts("----------------------------------");
puts("Input a string:");
pTestStr = reverseStr(testStr);
printf("%s\n", pTestStr);
free(pTestStr);
return 0;
}
Output:
----------------------------------
Input a string:
Initial string is: Hello world!
String contains 12 symbols
!dlrow olleH

What is wrong with my 'append' algorithm or code?

2 strings are given, second word will be append to first one and 3rd variable will store this. For example;
char *str1 = "abc";
char *str2 = "def";
char *str3 = "abcdef"; //should be
Here is my code, I get runtime error:
#include <stdio.h>
#include <malloc.h>
void append(char *str1, char *str2, char *str3, int size1, int size2)
{
int i=0;
str3 = (char*) malloc(size1+size2+1);
str3 = str1;
while (str2[i] != '\0') {
str3[i+size1] = str2[i];
i++;
}
str3[size1+size2] = '\0';
}
int main()
{
char *str1 = "abc";
char *str2 = "def";
char *str3;
append(str1, str2, str3, 3, 3);
return 0;
}
str3 = (char*) malloc(size1+size2+1);
str3 = str1;
Here's your problem. Doing this replaces the pointer to the correct amount of space from malloc to the pointer where str1 is contained. Keeping with your loop design, change this to:
str3 = malloc(size1+size2+1);
for (int j = 0; str1[j] != '\0'; j++)
str3[j] = str1[j];
Also, see this question/answer about casting the result of malloc in C:
Do I cast the result of malloc?
There is another issue with the code. You pass pointer by value. So any malloc inside a function will do only local changes. After function ends your pointer will still point to the old value. You should pass a pointer to pointer if you want to change it. See an example:
#include <stdio.h>
char *c = "Second";
void assign(char *s) { s = c; }
int main()
{
char *str = "First";
assign(str);
printf("String after assign: %s\n", str);
return 0;
}
After running the program you will see 'First' in you console. The correct code is:
#include <stdio.h>
char *c = "Second";
void assign(char **s) { *s = c; }
int main()
{
char *str = "First";
assign(&str);
printf("String after assign: %s\n", str);
return 0;
}
#include <stdio.h>
#include <stdlib.h> //to standard
#include <string.h>
char *append(const char *str1, const char *str2, int size1, int size2){
//parameter char *str3 is local variable.
//It is not possible to change the pointer of the original.
//str3 = str1;//<<-- memory leak
//str3[i+size1] = str2[i];//<<-- write to after str1(can't write!)
char *str3 = (char*) malloc(size1+size2+1);
memcpy(str3, str1, size1);//copy to alloc'd memory.
memcpy(str3 + size1, str2, size2);//copy to after str1
str3[size1+size2] = '\0';
return str3;
}
int main(){
char *str1 = "abc";
char *str2 = "def";
char *str3;
str3 = append(str1, str2, 3, 3);
printf("%s\n", str3);
return 0;
}

Create a new string that will consist of common letters from other two strings

I'm new to C programming. I have a task to do.
User inputs two strings. What I need to do is to create a new string that will consist only from common letters of those two given strings.
For example:
if given:
str1 = "ABCDZ"
str2 = "ADXYZ"
the new string will look like: "ADZ".
I can't make it work. I think there must be a better (more simple) algorithm but I have waisted too much time for this one so I want to complete it .. need your help!
what I've done so far is this:
char* commonChars (char* str1, char* str2)
{
char *ptr, *qtr, *arr, *tmp, *ch1, *ch2;
int counter = 1;
ch1 = str1;
ch2 = str2;
arr = (char*) malloc ((strlen(str1)+strlen(str2)+1)*(sizeof(char))); //creating dynamic array
strcpy(arr, str1);
strcat(arr,str2);
for (ptr = arr; ptr < arr + strlen(arr); ptr++)
{
for (qtr = arr; qtr < arr + strlen(arr); qtr++) // count for each char how many times is appears
{
if (*qtr == *ptr && qtr != ptr)
{
counter++;
tmp = qtr;
}
}
if (counter > 1)
{
for (qtr = tmp; *qtr; qtr++) //removing duplicate characters
*(qtr) = *(qtr+1);
}
counter = 1;
}
sortArray(arr, strlen(arr)); // sorting the string in alphabetical order
qtr = arr;
for (ptr = arr; ptr < arr + strlen(arr); ptr++, ch1++, ch2++) //checking if a letter appears in both strings and if at least one of them doesn't contain this letter - remove it
{
for (qtr = ptr; *qtr; qtr++)
{
if (*qtr != *ch1 || *qtr != *ch2)
*qtr = *(qtr+1);
}
}
}
Don't know how to finish this code .. i would be thankful for any suggestion!
The output array cannot be longer that the shorter of the two input arrays.
You can use strchr().
char * common (const char *in1, const char *in2) {
char *out;
char *p;
if (strlen(in2) < strlen(in1)) {
const char *t = in2;
in2 = in1;
in1 = t;
}
out = malloc(strlen(in2)+1);
p = out;
while (*in1) {
if (strchr(in2, *in1)) *p++ = *in1;
++in1;
}
*p = '\0';
return out;
}
This has O(NxM) performance, where N and M are the lengths of the input strings. Because your input is alphabetical and unique, you can achieve O(N+M) worst case performance. You apply something that resembles a merge loop.
char * common_linear (const char *in1, const char *in2) {
char *out;
char *p;
if (strlen(in2) < strlen(in1)) {
const char *t = in2;
in2 = in1;
in1 = t;
}
out = malloc(strlen(in2)+1);
p = out;
while (*in1 && *in2) {
if (*in1 < *in2) {
++in1;
continue;
}
if (*in2 < *in1) {
++in2;
continue;
}
*p++ = *in1;
++in1;
++in2;
}
*p = '\0';
return out;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define min(x,y) ((x)<(y)? (x) : (y))
char* commonChars (const char *str1, const char *str2){
//str1, str2 : sorted(asc) and unique
char *ret, *p;
int len1, len2;
len1=strlen(str1);
len2=strlen(str2);
ret = p = malloc((min(len1, len2)+1)*sizeof(char));
while(*str1 && *str2){
if(*str1 < *str2){
++str1;
continue;
}
if(*str1 > *str2){
++str2;
continue;
}
*p++ = *str1++;
++str2;
}
*p ='\0';
return ret;
}
char *deleteChars(const char *str, const char *dellist){
//str, dellist : sorted(asc) and unique
char *ret, *p;
ret = p = malloc((strlen(str)+1)*sizeof(char));
while(*str && *dellist){
if(*str < *dellist){
*p++=*str++;
continue;
}
if(*str > *dellist){
++dellist;
continue;
}
++str;
++dellist;
}
if(!*dellist)
while(*str)
*p++=*str++;
*p ='\0';
return ret;
}
int main(void){
const char *str1 = "ABCDXYZ";
const char *str2 = "ABCDZ";
const char *str3 = "ADXYZ";
char *common2and3;
char *withoutcommon;
common2and3 = commonChars(str2, str3);
//printf("%s\n", common2and3);//ADZ
withoutcommon = deleteChars(str1, common2and3);
printf("%s\n", withoutcommon);//BCXY
free(common2and3);
free(withoutcommon);
return 0;
}
I will do something like this :
char* commonChars(char* str1, char* str2) {
char* ret = malloc(strlen(str1) * sizeof(char));
int i = j = k = 0;
for (; str1[i] != '\n'; i++, j++) {
if (str1[i] == str2[j]) {
ret[k] = str1[i];
k++;
}
}
ret[k] = '\0';
ret = realloc(ret, k);
return ret;
}
It's been a while i didn't do C, hope this is correct
You can use strpbrk() function, to do this job cleanly.
const char * strpbrk ( const char * str1, const char * str2 );
char * strpbrk ( char * str1, const char * str2 );
Locate characters in string
Returns a pointer to the first occurrence in str1 of any of the characters that are part of str2, or a null pointer if there are no matches.
The search does not include the terminating null-characters of either strings, but ends there.
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "ABCDZ";
char key[] = "ADXYZ";
char *newString = malloc(sizeof(str)+sizeof(key));
memset(newString, 0x00, sizeof(newString));
char * pch;
pch = strpbrk (str, key);
int i=0;
while (pch != NULL)
{
*(newString+i) = *pch;
pch = strpbrk (pch+1,key);
i++;
}
printf ("%s", newString);
return 0;
}
Sorry for the weird use of char arrays, was just trying to get it done fast. The idea behind the algorithm should be obvious, you can modify some of the types, loop ending conditions, remove the C++ elements, etc for your purposes. It's the idea behind the code that's important.
#include <queue>
#include <string>
#include <iostream>
using namespace std;
bool isCharPresent(char* str, char c) {
do {
if(c == *str) return true;
} while(*(str++));
return false;
}
int main ()
{
char str1[] = {'h', 'i', 't', 'h', 'e', 'r', 'e', '\0'};
char str2[] = {'a', 'h', 'i', '\0'};
string result = "";
char* charIt = &str1[0];
do {
if(isCharPresent(str2, *charIt))
result += *charIt;
} while(*(charIt++));
cout << result << endl; //hih is the result. Minor modifications if dupes are bad.
}
So i found the solution for my problem. Eventually I used another algorithm which, as turned out, is very similar to what #BLUEPIXY and #user315052 have suggested. Thanks everyone who tried to help! Very nice and useful web source!
Here is my code. Someone who'll find it useful can use it.
Note:
(1) str1 & str2 should be sorted alphabetically;
(2) each character should appear only once in each given strings;
char* commonChars (char* str1, char* str2)
{
char *ptr, *arr,*ch1, *ch2;
int counter = 0;
for (ch1 = str1; *ch1; ch1++)
{
for(ch2 = str2; *ch2; ch2++)
{
if (*ch1 == *ch2)
counter++;
}
}
arr = (char*)malloc ((counter+1) * sizeof(char));
ch1 = str1;
ch2 = str2;
ptr = arr;
for (ch1 = str1; *ch1; ch1++,ch2++)
{
while (*ch1 < *ch2)
{
ch1++;
}
while (*ch1 > *ch2)
{
ch2++;
}
if (*ch1 == *ch2)
{
*ptr = *ch1;
ptr++;
}
}
if (ptr = arr + counter)
*ptr = '\0';
return arr;
}

Resources