例如,
n = 3432, result 4
n = 45, result 2
n = 33215, result 5
n = -357, result 3
Run Code Online (Sandbox Code Playgroud)
我想我可以把它变成一个字符串然后得到字符串的长度,但这看起来很复杂和黑客.
像这样转换int时:
char a[256];
sprintf(a, "%d", 132);
Run Code Online (Sandbox Code Playgroud)
什么是确定如何大的最好方式一个应该是什么?我假设手动设置它很好(因为我看到它在任何地方使用),但它应该有多大?在32位系统上可能的最大int值是多少,是否有一些棘手的方法来确定它?
据我所知,在编译c的时间之前,数组需要具有特定的大小.
我想知道为什么这段代码仍然有效?
int s;
printf("enter the array size: ");
scanf("%d",&s);
int a[s]; // Isn't s value determined at run time?
Run Code Online (Sandbox Code Playgroud) 我一直在研究学校的一些练习题,其中之一是必须将输入的整数写到动态分配的字符串中。该代码可以很好地完成工作,直到释放分配的内存(发生堆损坏)为止。
有人可以解释为什么会发生这种情况以及我在做什么错吗?
int main() {
char *string = NULL;
char **string2 = &string;
Conversion(string2);
printf("Entered number converted to string: %s", string);
free(string);
return 0;
}
int Conversion(char **string) {
int num = 0, temp = 0, dcount = 0;
printf("Enter number: ");
scanf(" %d", &num);
temp = num;
while (temp != 0) {
temp /= 10;
dcount++;
}
*string = (char*)malloc(dcount*sizeof(char));
if (*string == NULL) {
printf("Error during memory allocation!");
return -1;
}
sprintf(*string, "%d", num);
return 0;
}
Run Code Online (Sandbox Code Playgroud) c string pointers segmentation-fault dynamic-memory-allocation