Monday, May 27, 2013

segment fault???

#include<iostream>
#include<cstdarg>
using namespace std;
char* nstrcat(char* name,...){
char* temp = name;
int i,j;

va_list(ap);
va_start(ap,name);
for(int i=0; temp[i];i++){
;
}
char* add = va_arg(ap,char*);
while(add){
for(int j =0;add[j];j++,i++)
    temp[i] =add[j];
temp[i]='\0';
add = va_arg(ap,char*);
}
va_end(ap);
return temp;
}

int main(){
 cout << nstrcat("hello","how","are");
 return 0;
}


the right one should like look the following:


#include<iostream>
#include<cstdarg>
using namespace std;
#define LENGTH 100

char* nstrcat(char* name,...){

    char* temp = new char[LENGTH]; //dynamic memory
    char* source;

    int i;
    int length = 0;
    va_list ap;
    va_start(ap,name);
    for(source = name; source; source=va_arg(ap,char*)){
        for(i=0; source[i]; i++)
            temp[i +length] = source[i];
        length += i;
}
    temp[length] = '\0';
    va_end(ap);
    return temp;
}

int main(){
 cout << nstrcat("hello","how","are");
 return 0;

No comments:

Post a Comment