Mors Alphabet Segmentation Fault - c

My code doesn't adding second node to tree. It gives me SIGSEGV fault when i'm adding the second node.I think its about strcmp function but when i'm trying to understand how it works properly at the very bottom of main func it returns -1 so i've wrote it like this.And most of my variables named Turkish so here are the translations of them to make you understand more easily
dugum=node,kok=root;sol=left;sag=right;anne=mother
// C program to demonstrate insert operation in binary search tree
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct tree {
char *harf;
char *morskodu;
struct tree *left;
struct tree *right;
} agac;
agac *kok = NULL;
void ekle(char *harf, char *morskodu) {
if (kok == NULL) {
kok = (agac *)malloc(sizeof(agac));
kok->harf = harf;
kok->morskodu = morskodu;
kok->left = NULL;
kok->right= NULL;
} else {
agac *yeni = (agac *)malloc(sizeof(agac));
yeni->harf = harf;
yeni->morskodu = morskodu;
yeni->left = NULL;
yeni->right = NULL;
agac *dugum = kok, *anne;
while (dugum != NULL) {
anne = dugum;
if (harf <= dugum->harf)
dugum = dugum->left;
else
dugum = dugum->right;
}
if (harf <= dugum->harf)
anne->left = yeni;
else
anne->right = yeni;
}
}
void dolas(agac *dugum) {
if (dugum != NULL) {
printf(" %s ", dugum->harf);
dolas(dugum->left);
dolas(dugum->right);
}
}
void main() {
ekle("a", "-");
ekle("b", "-.");
dolas(kok);
int x = strcmp("A", "B");
printf("%d", x);
}

You try to dereference a NULL pointer.
while (dugum != NULL) {
anne = dugum;
if (harf <= dugum->harf)
dugum = dugum->sol;
else
dugum = dugum->sag;
}
This loop ends when dugum is NULL.
Directly after you try to access dugum->harf:
if (harf <= dugum->harf)
This leads to undefined behavior.
Also note that this comparisons compare the pointers to string literals, and is therefore also undefined behavior. To compare two C strings you should use strcmp.

Related

Recursive function to represent binary tree in C

Problem
I want to print the nodes of a binary tree inorder and would like to have the nodes printed with as many dashes as the height they are in and then it's data.
Research done
I have found other posts like this one or this one but I'm still clueless on how I can represent my binary tree the way I want, as it differs to the ones stated on those questions.
Example
So lets say I insert nodes with data in this manner:
5,4,2,3,9,8
The output I would expect when representing the binary tree would be:
-9
--8
5
-4
---3
--2
Toy example code
So far I was able to print the nodes in the correct order. But after days I'm still clueless on how to implement a recursive function to get the correct representation. I also tried loops but found it's even messier and wasn't getting the correct result either.
The problem is that the amount of dashes is not the correct one and I'm unsure on where I need to append the dashes within the recursion. I'm thinking I may need to rewrite the whole printBinaryTreeRecurrsively code.
Below you can see the toy example code which can be compiled as a whole:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct repBinaryTree *BinaryTree;
struct repBinaryTree {
int data;
BinaryTree left;
BinaryTree right;
};
BinaryTree newNode() {
BinaryTree b = new repBinaryTree;
b->data = NULL;
b->left = b->right = NULL;
return b;
}
BinaryTree insertNode(int i, BinaryTree b) {
if (b==NULL) {
b = newNode();
b->data = i;
} else if ( i < b->data ) {
if (b->left == NULL) {
b->left = newNode();
b->left->data = i;
} else {
insertNode(i, b->left);
}
} else if ( i > b->data ) {
if (b->right == NULL) {
b->right = newNode();
b->right->data = i;
} else {
insertNode(i, b->right);
}
}
return b;
}
char* printBinaryTreeRecurrsively(BinaryTree b, char level[]) {
if (b == NULL) {
printf("\n");
return level;
} else {
level = printBinaryTreeRecurrsively(b->right, level);
printf("%s%d",level,b->data);
level = printBinaryTreeRecurrsively(b->left, level);
}
strcat(level,"-");
return level;
}
int main () {
BinaryTree b = insertNode(5,NULL);
b = insertNode(4, b);
b = insertNode(2, b);
b = insertNode(3, b);
b = insertNode(9, b);
b = insertNode(8, b);
printf("Recursive BinaryTree print:");
char level0[] = "";
printBinaryTreeRecurrsively(b, level0);
printf("Expected BinaryTree print:");
printf("\n-9\n--8\n5\n-4\n---3\n--2\n");
}
The output I get after compiling and running the program from command line is as follows:
cedric#multivac:~$ g++ printBinaryTree.cpp -o printBinaryTree
cedric#multivac:~$ ./printBinaryTree
Recursive BinaryTree print:
9
8
--5
--4
--3
---2
Expected BinaryTree print:
-9
--8
5
-4
---3
--2
Question
How should I rewrite my printBinaryTreeRecurrsively function code so as I get the correct output?
Modify the function to this instead
void printBinaryTreeRecurrsively(BinaryTree b, int level) {
if (b == NULL) {
printf("\n");
} else {
printBinaryTreeRecurrsively(b->right, level+1);
for (int i = 0; i < level; i++) {
printf("-");
}
printf("%d",b->data);
printBinaryTreeRecurrsively(b->left, level+1);
}
}
and call in main() as
printBinaryTreeRecurrsively(b, 0);
This method is much simpler than worrying about string concatenation etc. Just keep track of which level you're on with an int, print the correct number of -, and tell the levels below to print with one more -.

Trouble using strcmp in c code

I've used strcmp before and it worked as expected, but it's not working for me in my current code.
I'm reading a .csv file with the names of a bunch of famous people. "Mark Zuckerberg" is the key name that triggers things that my code will eventually do (once I get past this bump in the road and this has nothing to do with what he's been in the news for lately). I'm using a counter (queue_size) to count the number of lines in the .csv file. My goal is to save the value of the counter when strcmp(temp_name, key) == 0 but I'm not entering that if statement and I can't see why.
The key appears in the .csv file as "Mark,Zuckerberg". I've tried using strtok to eliminate the comma. I was successful in doing that but strcmp() still isn't working (I adjusted the key to be "MarkZuckerberg"). I also added memset to clean the slate with each iteration but that didn't resolve the issue either.
Commenting the line, temp_name[strlen(temp_name) - 1] = '\0'; doesn't appear to change anything either. I know that my struct is getting all of the names because printf (I've since deleted) and my print_list function prints as expected.
I really need help finding out why I'm not entering that if statement.
Thanks in advance for any help that anyone can provide.
I think that it's something dumb that I'm overlooking but I just can't find it.
Here's my code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct char_node {
char name[40];
struct char_node *next;
} char_node;
typedef struct char_queue {
char_node *q_head;
char_node *q_tail;
int q_size;
} char_queue;
void enqueue(char_queue *q_ptr, char new_name[40]);
//int dequeue(char_queue *q_ptr);
void print_list(char_queue *queue);
int main() {
int queue_size = 0;
int m_z_position;
char_queue queue;
char temp_name[40];
char key[] = "Mark,Zuckerberg";
queue.q_head = NULL;
queue.q_tail = NULL;
queue.q_size = 0;
FILE *file_input;
file_input = fopen("party.csv", "r");
memset(temp_name, '\0', sizeof(temp_name));
while(fgets(temp_name, sizeof(temp_name), file_input)) {
temp_name[strlen(temp_name) - 1] = '\0';
if(strcmp(temp_name, key) == 0) {
printf("test\n");
m_z_position = queue_size;
}
enqueue(&queue, temp_name);
memset(temp_name, '\0', sizeof(temp_name));
queue_size++;
}
fclose(file_input);
//print_list(&queue);
printf("m_z_position = %d\n", m_z_position);
return 0;
}
void enqueue(char_queue *q_ptr, char new_name[40]) {
char_node *new_node = (char_node*)malloc(sizeof(char_node));
strcpy(new_node->name, new_name);
new_node->next = NULL;
int num;
if(q_ptr->q_size == 0) {
q_ptr->q_tail = new_node;
q_ptr->q_head = new_node;
} else {
q_ptr->q_tail->next = new_node;
q_ptr->q_tail = new_node;
}
(q_ptr->q_size)++;
return;
}
void print_list(char_queue *queue) {
char_node *temp_list;
if(queue->q_head != NULL) {
temp_list = queue->q_head;
while(temp_list != NULL) {
printf("%s\n", temp_list->name);
temp_list = temp_list->next;
}
}
printf("\n");
return;
}
I can't figure out how to add the file but here are the contents of the .csv file
Jeff,Bezo
Bill,Gates
Warren,Buffett
Berkshire,Hathaway
Bernard,Arnault
Amancio,Ortega
Carlos,Slim
Charles,Koch
David,Koch
Larry,Ellison
Michael,Bloomberg
Larry,Page
Sergey,Brin
Jim,Walton
S,Robson
Alice,Walton
Ma,Huateng
Francoise,Bettencourt
Mukesh,Ambani
Jack,Ma
Sheldon,Adelson
Steve,Ballmer
Li,Ka-shing
Hui,Ka
Lee,Shau
Wang,Jianlin
Beate,Heister
Phil,Knight
Jorge,Paulo
Francois,Pinault
Georg,Schaeffler
Susanne,Klatten
David,Thomson
Jacqueline,Mars
John,Mars
Joseph,Safra
Giovanni,Ferrero
Dietrich,Mateschitz
Michael,Dell
Masayoshi,Son
Serge,Dassault
Stefan,Quandt
Yang,Huiyan
Paul,Allen
Leonardo,Del
Dieter,Schwarz
Thomas,Peterffy
Theo,Albrecht
Len,Blavatnik
He,Xiangjian
Lui,Che
James,Simons
Henry,Sy
Elon,Musk
Hinduja,family
Tadashi,Yanai
Vladimir,Lisin
Laurene,Powell
Azim,Premji
Alexey,Mordashov
Lee,Kun-Hee
Lakshmi,Mittal
Wang,Wei
Leonid,Mikhelson
Charoen,Sirivadhanabhakdi
Pallonji,Mistry
Ray,Dalio
Takemitsu,Takizaki
William,Ding
R,Budi
Gina,Rinehart
German,Larrea
Carl,Icahn
Stefan,Persson
Michael,Hartono
Joseph,Lau
Thomas,A
Vagit,Alekperov
James,Ratcliffe
Donald,Bren
Iris,Fontbona
Gennady,Timchenko
Abigail,Johnson
Vladimir,Potanin
Lukas,Walton
Charlene,de
Zhang,Zhidong
Petr,Kellner
Andrey,Melnichenko
David,A
Klaus-Michael,Kuehne
Li,Shufu
Mikhail,Fridman
Rupert,Murdoch
Dhanin,Chearavanont
Robert,Kuok
Emmanuel,Besnier
Shiv,Nadar
Viktor,Vekselberg
Aliko,Dangote
Harold,Hamm
Steve,Cohen
Dustin,Moskovitz
Marcel,Herrmann
Reinhold,Wuerth
Charles,Ergen
Eric,Schmidt
Philip,Anschutz
Jim,Kennedy
Blair,Parry-Okeden
Alain,Wertheimer
Gerard,Wertheimer
Leonard,Lauder
Heinz,Hermann
Dilip,Shanghvi
Hasso,Plattner
Stephen,Schwarzman
Lei,Jun
Hans,Rausing
Alisher,Usmanov
Donald,Newhouse
Peter,Woo
Luis,Carlos
Robin,Li
Carlos,Alberto
Seo,Jung-Jin
Kumar,Birla
Alexander,Otto
Stefano,Pessina
Udo,A
Wang,Wenyin
Andrew,Beal
Lee,Man
John,Menard
Xu,Shihui
Zhou,Hongyi
Gong,Hongjia
Michael,Otto
David,Tepper
Roman,Abramovich
Liu,Qiangdong
Robert,A
Alberto,Bailleres
Uday,Kotak
Pierre,Omidyar
Walter,PJ
Dietmar,Hopp
Graeme,Hart
Eduardo,Saverin
Yan,Zhi
Radhakishan,Damani
German,Khan
Ronald,Perelman
Gautam,Adani
Micky,Arison
Pan,Zhengmin
Joseph,Tsai
Thomas,Frist
Mikhail,Prokhorov
Galen,Weston
Zong,Qinghou
Eyal,Ofer
Charles,Schwab
Gianluigi,A
Herbert,Kohler
Viktor,Rashnikov
Harry,Triguboff
August,von
Yao,Zhenhua
Jan,Koum
Cyrus,Poonawalla
James,Goodnight
Ken,Griffin
Giorgio,Armani
Ernesto,Bertarelli
Savitri,Jindal
Sunil,Mittal
James,Chambers
Katharine,Rayner
Margaretta,Taylor
Terry,Gou
Gordon,Moore
James,Irving
Stanley,Kroenke
Melker,Schorling
Johann,Graf
Guo,Guangchang
John,Malone
Xavier,Niel
Silvio,Berlusconi
Carl,Cook
David,Geffen
Hui,Wing
Walter,Kwok
George,Soros
Edward,Johnson
Massimiliana,Landini
David,Duffield
George,Kaiser
Patrick,Soon-Shiong
Zhou,Qunfei
Nicky,Oppenheimer
Sun,Piaoyang
Wu,Yajun
Alexei,Kuzmichev
Stephen,Ross
Vincent,Bollore
Pauline,MacMillan
Jay,Y
Anders,Holch
Eli,Broad
Michael,Kadoorie
Iskander,Makhmudov
Frederik,Paulsen
Sun,Hongbin
Christy,Walton
Shahid,Khan
Ananda,Krishnan
Carrie,Perrodo
Quek,Leng
Wang,Wenxue
John,Doerr
Patrick,Drahi
Eva,Gonda
Willi,A
Ricardo,Salinas
Suh,Kyung-Bae
Pollyanna,Chu
John,Fredriksen
Goh,Cheng
Sri,Prakash
Lu,Zhiqiang
Jorn,Rausing
Johann,Rupert
Jacques,Saade
Wu,Shaoxun
Leonid,Fedun
Kim,Jung-Ju
Sandra,Ortega
Jim,Pattison
Michael,Platt
Chan,Laiwa
David,Green
Hank,A
Dmitry,Rybolovlev
Tsai,Eng-Meng
Andreas,von
Oleg,Deripaska
Liu,Yongxing
Ludwig,Merckle
Brian,Acton
John,Grayken
Ann,Walton
Augusto,A
Finn,Rausing
Mark,Zuckerberg
Kirsten,Rausing
Odd,Reitan
Nassef,Sawiris
Wee,Cho
Aloys,Wobben
Leon,Black
Ivan,Glasenberg
John,Paulson
Wei,Jianjun
Francis,Choi
Erivan,Haub
Jason,Jiang
Suleiman,Kerimov
Ian,A
Pang,Kang
David,Shaw
Kushal,Pal
John,A
Acharya,Balkrishna
Guenther,Fielmann
Daniel,Gilbert
Antonia,Johnson
Vikram,Lal
Akira,Mori
Maria-Elisabeth,Schaeffler-Thumann
Albert,Frere
Richard,Kinder
Robert,Kraft
Ralph,Lauren
Bruno,Schroder
Nusli,Wadia
Pierre,Bellon
Les,Wexner
Benu,Gopal
David,Cheriton
Ma,Jianrong
Whitney,MacMillan
Dan,Olsson
Vivek,Chaand
Teh,Hong
Abdulla,bin
Maria,Asuncion
Ralph,Dommermuth
Frank,Lowy
Wolfgang,Marguerre
Marijke,Mars
Pamela,Mars
Valerie,Mars
Victoria,Mars
David,A
John,Gokongwei
Kwon,Hyuk-Bin
Nancy,Walton
Lin,Yu-Ling
Tom,A
Robert,Rowling
Dennis,Washington
Yao,Liangsong
Zhang,Jindong
Juan,Francisco
David,Sun
John,Tu
Martin,Viessmann
Stef,Wertheimer
Hansjoerg,Wyss
James,Dyson
Laurence,Graff
Jen-Hsun,Huang
Charles,Johnson
Jerry,Jones
Kei,Hoi
Kwee,family
Lee,Shin
Richard,LeFrak
Shigenobu,Nagamori
Steven,Rales
Friede,Springer
Yeung,Kin-man
Rinat,Akhmetov
Shari,Arison
Dannine,Avara
Rahel,Blocher
Andrew,Currie
Scott,Duncan
Milane,Frantz
Diane,Hendricks
Magdalena,Martullo-Blocher
Hiroshi,Mikitani
Gabe,Newell
Pan,Sutong
Anthony,Pratt
John,Reece
Randa,Williams
Zhang,Bangxin
I was fixing your code, but as this comment already state, your file use "\r\n" as end line code, can be fixed with str[strcspn(str, "\r\n")] = '\0'; just after your read.
But here, an other exemple of implementation of your code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct char_node {
struct char_node *next;
char name[];
} char_node;
typedef struct char_queue {
char_node *q_head;
char_node *q_tail;
size_t q_size;
} char_queue;
char_node *enqueue(char_queue *q_ptr, char const *new_name);
void print_list(char_queue const *queue);
int main(void) {
char_queue queue = { .q_head = NULL, .q_tail = NULL, .q_size = 0 };
char const key[] = "Mark,Zuckerberg";
FILE *file_input = fopen("party.csv", "r");
if (file_input == NULL) {
file_input = stdin;
}
char str[40];
size_t m_z_position = 0;
while (fgets(str, sizeof str, file_input)) {
str[strcspn(str, "\r\n")] = '\0';
if (strcmp(str, key) == 0) {
m_z_position = queue.q_size;
}
enqueue(&queue, str);
}
fclose(file_input);
print_list(&queue);
printf("m_z_position = %zu\n", m_z_position);
}
char_node *enqueue(char_queue *q_ptr, char const *name) {
size_t i = strlen(name) + 1;
char_node *node = malloc(sizeof *node + i);
if (!node) {
return NULL;
}
strcpy(node->name, name);
node->next = NULL;
if (q_ptr->q_size++ == 0) {
q_ptr->q_tail = q_ptr->q_head = node;
} else {
q_ptr->q_tail = q_ptr->q_tail->next = node;
}
return node;
}
void print_list(char_queue const *queue) {
for (char_node const *list = queue->q_head; list; list = list->next) {
printf("%s\n", list->name);
}
printf("\n");
}
I am afraid that .csv file contains "Mark,Zuckerberg" not Mark,Zuckerberg.
In if(strcmp(temp_name, key) == 0){ key is compared with temp_name.
Here key is Mark,Zuckerberg.
int strcmp(const char *s1, const char *s2);
The strcmp() and strncmp()
functions return an integer greater than, equal to, or less than 0,
according as the string s1 is greater than, equal to, or less than the
string s2.
strcmp will return positive number if temp_name is "Mark,Zuckerberg" because it contains additional 2 characters and, 0 if temp_name is Mark,Zuckerberg as key here is Mark,Zuckerberg clearly.

Exit code 11 on extractMin() in PriorityQueue in C'99

I'm new in C programming. I'm developing a priority queue in C'99 with the heap data structure.
I'm using heapifyDown() in combination with swapValues() to sort the heap array for extracting the first element (min-heap) pqueue_extractMin() function. My structure looks like this:
typedef struct ProrityQueue_s PriorityQueue;
typedef struct PriorityQueue_Entry_s *PriorityQueue_Entry;
struct ProrityQueue_s {
int size, last;
char error;
PriorityQueue_Entry *entries;
};
struct PriorityQueue_Entry_s {
char *value;
float priority;
};
For information – Full code for information on gist: https://gist.github.com/it4need/ddf9014bfda9fe6a64bb01a7417422bc
Questions:
Insertion into the Priority queue ("minheap") looks good. Everything is fine. But when I'm extract more than one element at once, I will get this error: "Process finished with exit code 11".
Is this line allowed to copy the whole contents of the last element to the first of the heap? priorityqueue->entries[0] = priorityqueue->entries[priorityqueue->last];
swapValues(priorityqueue, currentPositionIndex, smallestChild); Can I swap values of whole Structure elements? -> implementation (bottom).
HeapifyDown():
void heapifyDown(PriorityQueue *priorityqueue)
{
int currentPositionIndex = 0;
while(currentPositionIndex < priorityqueue->last)
{
int smallestChild = currentPositionIndex;
int leftChildIndex = (2 * currentPositionIndex) + 1;
int rightChildIndex = (2 * currentPositionIndex) + 2;
smallestChild = (priorityqueue->entries[leftChildIndex]->priority < priorityqueue->entries[smallestChild]->priority && priorityqueue->last > leftChildIndex)
? leftChildIndex : smallestChild;
smallestChild = (priorityqueue->entries[rightChildIndex]->priority < priorityqueue->entries[smallestChild]->priority && priorityqueue->last > rightChildIndex)
? rightChildIndex : smallestChild;
if(smallestChild == currentPositionIndex)
{
break;
}
swapValues(priorityqueue, currentPositionIndex, smallestChild); // #todo: Why does this line break the function on two function calls by negative values
currentPositionIndex = smallestChild;
}
}
SwapValues():
void swapValues(PriorityQueue *priorityqueue, int firstIndex, int secondIndex)
{
// #todo: Does this work properly?
PriorityQueue_Entry tmp_entry = priorityqueue->entries[firstIndex];
priorityqueue->entries[firstIndex] = priorityqueue->entries[secondIndex];
priorityqueue->entries[secondIndex] = tmp_entry;
}
extractMin():
char *pqueue_extractMin(PriorityQueue *priorityqueue)
{
if(isEmpty(priorityqueue))
{
priorityqueue->error = ERROR_PRIORITY_QUEUE_EMPTY;
}
priorityqueue->last--;
char *tmp = priorityqueue->entries[0]->value;
priorityqueue->entries[0] = priorityqueue->entries[priorityqueue->last]; // #todo: Is this allowed?
heapifyDown(priorityqueue); // #todo: Why does this line break the extractMin() function on two function calls -> check swapValues() in heapifyDown()
return tmp;
}
Full code for information on gist: https://gist.github.com/it4need/ddf9014bfda9fe6a64bb01a7417422bc

How do you use a typedef struct for a FIFO?

I just started programming in C for school. I am being asked to do a program that uses a FIFO struct to resolve math problems. I got the folowing code on the internet for a FIFO, I just don't know how to use it. I tried a lot of things and I can't find anything useful on the internet or maybe that I just don't know the right thing to research but could you please help me? Thanks!
#include <stdio.h>
#include <stdlib.h>
typedef struct pile
{
int donnee;
struct pile *precedent;
} Pile;
void pile_push(Pile **p_pile, int donnee)
{
Pile *p_nouveau = malloc(sizeof *p_nouveau);
if (p_nouveau != NULL)
{
p_nouveau->donnee = donnee;
p_nouveau->precedent = *p_pile;
*p_pile = p_nouveau;
}
}
int pile_pop(Pile **p_pile)
{
int ret = -1;
if (p_pile != NULL)
{
Pile *temporaire = (*p_pile)->precedent;
ret = (*p_pile)->donnee;
free(*p_pile), *p_pile = NULL;
*p_pile = temporaire;
}
return ret;
}
void pile_clear(Pile **p_pile)
{
while (*p_pile != NULL)
{
pile_pop(p_pile);
}
}
I tried doing this:
int main()
{
int return_val;
Pile pile;
pile_push(Pile, 5);
return_val = pile_pop(Pile);
printf(return_val);
}
and got this error:
expected expression before 'Pile'
too few arguments to function 'pile_push'
You have mixed up Pile and pile which is the issue with the first warning. The functions expect a pointer to a pointer to a Pile. That is: They update the value of a pointer, so they need to be passed a reference to a pointer. Your use of printf is also wrong.
int main()
{
int return_val;
Pile *pile = NULL;
pile_push(&pile,5);
return_val = pile_pop(&pile);
printf("return_val is: %d\n",return_val);
}

Remove the duplicate from a String Using Pointers

#include<stdio.h>
char *removedps(char *x)
{
int Ar[256] = {0};
int ip=0;
int op=0;
char temp;
while(*(x+ip))
{
temp = (*(x+ip));
if (!Ar[temp]) {
Ar[temp] = 1;
*(x+ip) = *(x+op);
op++;
}
ip++;
*(x+op) = '\0';
}
return x;
}
int main()
{
char lo[] = "0001";
printf("%s",removedps(lo));
}
My code is not working
I have tried hard to see the error
All I GET IS the first character .
My idea is simple
make an array of 256 places
insert Zero into them
Then insert 1 for each character inside the string (on that position of the array)
your assignment looks to be the error here.
op is "out postiion", ip is "in position"
so it should be
*(x+op) = *(x+ip);
not the other way.
because *(x+op) = '\0';
is always run every iteration of the loop.
I'd probablly do it more like this ( using your method, which I probablly wouldn't use personally)
char *removedps(char *x)
{
int Ar[256] = {0};
char* start = x;
while(*x)
{
if (Ar[*x])
{ // remove the repeated character
memmove(x, x+1, strlen(x));
}
else
{
Ar[*x] = 1;
x++;
}
}
return start;
}
also, I'd name it remove_duplicate_chars or something, not a fan of cryptic abbreviations.
At the end of the loop, you do *(x+op)='\0';, and then, in the next iteration, you do *(x+ip)=*(x+op);, so from the 2sd iteration, you put there 0.
try do something like:
for (op=ip=0;x[ip];ip++) {
if (!Ar[x[ip]]++) x[op++]=x[ip];
}
x[op]=0;

Resources