the exerise in K&R about char*

R

remlostime

ex 2-4 write squeeze(s1, s2), which make s1 doesn't contain any char
int s2
now I write the code:
it seems that something wrong in
if (s2[k] == '\0')
s1[i++] = s1[j];
because i write some test code in it, it shows that
but I dont know why, can anyone tell me?

#include <iostream>
using namespace std;

void squeeze(char s1[], char s2[])
{
int i = 0;
for(int j = 0; s1[j] != '\0'; j++)
{
int k;
for(k = 0; s2[k] != '\0' && s1[j] != s2[k]; k++);
if (s2[k] == '\0')
s1[i++] = s1[j];
}
s1 = '\0';
}


int main()
{
char *a = "abcedaba";
char *b = "ab";
squeeze(a, b);
printf("%s\n", a);
}
 
R

red floyd

remlostime said:
ex 2-4 write squeeze(s1, s2), which make s1 doesn't contain any char
int s2
now I write the code:
it seems that something wrong in
if (s2[k] == '\0')
s1[i++] = s1[j];
because i write some test code in it, it shows that
but I dont know why, can anyone tell me?

#include <iostream>
using namespace std;
You don't need these. You're not using iostreams. With what you've
posted said:
void squeeze(char s1[], char s2[])
{
int i = 0;
for(int j = 0; s1[j] != '\0'; j++)
{
int k;
for(k = 0; s2[k] != '\0' && s1[j] != s2[k]; k++);
if (s2[k] == '\0')
s1[i++] = s1[j];
At this point, s1 refers to a string literal. Modifying it is
undefined behavior.
}
s1 = '\0';
}


int main()
{
char *a = "abcedaba";

Assigning a string literal to a char* is allowed, but not recommended,
it leads to undefined behavior. Make a and b const.
 
R

remlostime

remlostime said:
ex 2-4 write squeeze(s1, s2), which make s1 doesn't contain any char
int s2
now I write the code:
it seems that something wrong in
           if (s2[k] == '\0')
                   s1[i++] = s1[j];
because i write some test code in it, it shows that
but I dont know why, can anyone tell me?
#include <iostream>
using namespace std;

You don't need these. You're not using iostreams.  With what you've
posted, you need <cstdio>.


void squeeze(char s1[], char s2[])
{
   int i = 0;
   for(int j = 0; s1[j] != '\0'; j++)
   {
           int k;
           for(k = 0; s2[k] != '\0' && s1[j] != s2[k]; k++);
           if (s2[k] == '\0')
                   s1[i++] = s1[j];

At this point, s1 refers to a string literal.  Modifying it is
undefined behavior.>    }
   s1 = '\0';
}

int main()
{
   char *a = "abcedaba";

Assigning a string literal to a char* is allowed, but not recommended,
it leads to undefined behavior.  Make a and b const.
   char *b = "ab";
   squeeze(a, b);
   printf("%s\n", a);
}


thank you, now i fix it
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,817
Latest member
DicWeils

Latest Threads

Top