![]() |
| | #1 |
| Registered User Join Date: Oct 2009
Posts: 14
| Segmentation Fault? Code: void tobinary(int x, char s[]);
int main() {
char hold[4];
tobinary(5, hold);
return 0;
}
void tobinary(int x, char s[]){
int k=0,n=0;
int neg=0;
int sLength=sizeof(s);
int remain;
int temp[sLength];
if (x<0) {
x=-x;
neg=1;
}
do {
remain=x%2;
x=x/2;
temp[k++]=remain+'0';
} while (x >0);
if(neg) {
temp[k++]='-';
}
else {
temp[k++]=' ';
}
while (k>=0) {
s[n++]=temp[--k];
}
s[n-1]=0;
k=0;
while (k<4) {
printf("%d", s[k]);
k++;
}
}
|
| TIMBERings is offline | |
| | #2 |
| ... Join Date: Jan 2003
Posts: 1,190
| Code: sLength=sizeof(s); Read 6.1-6.4b here to get an idea of why this is so. Last edited by kermit; 10-08-2009 at 07:28 PM. |
| kermit is offline | |
| | #3 |
| Registered User Join Date: Sep 2009
Posts: 30
| sizeof() only works on an array in the scope that the array was defined. You define your array in main() and then use sizeof() in a different function, which won't work. In this case it returns the size of a pointer (which is what it sees s as) instead of the size of the array you allocated in main(). You could pass a 3rd argument to tobinary() to tell it specifically how big to make your temp array. |
| jdragyn is offline | |
| | #4 |
| Registered User Join Date: Oct 2009
Posts: 14
| I removed sizeof() and instead passed an integer, still get a segmentation fault |
| TIMBERings is offline | |
![]() |
| Tags |
| code, fault, segmentation |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Segmentation fault problem | odedbobi | Linux Programming | 1 | 11-19-2008 03:36 AM |
| Segmentation fault | bennyandthejets | C++ Programming | 7 | 09-07-2005 05:04 PM |
| Segmentation fault | NoUse | C Programming | 4 | 03-26-2005 03:29 PM |
| Locating A Segmentation Fault | Stack Overflow | C Programming | 12 | 12-14-2004 01:33 PM |
| Segmentation fault... | alvifarooq | C++ Programming | 14 | 09-26-2004 12:53 PM |