我正在檢查指向指標的指標,在不分配的情況下傳遞它。我想分配功能a[0]="something str" a[1]="some thing str" a[2]="something str" a[3]="something str"。pp我可以這樣做(在 pp 函式中分配和填充strcpy)并將其回傳給 main 嗎?
這是我的嘗試:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#define MAX_LEN 100
// float 3
void pp(char *arr, char *delimiter, char **a)
{
int i = 0;
*a = malloc(sizeof(char) * 10);
}
int main(int argc, void **argv)
{
char *arr = "1.77 1.65 1.56 5.555 6.1";
char **f;
pp(arr, " ", &f[0]);
}
我以為我可以分配個人char *然后填充為,strcpy(*(a x),"something")但它會導致*a = malloc(sizeof(char) * 10);.
uj5u.com熱心網友回復:
對于初學者來說,標頭<malloc.h>不是標準的 C 標頭。而是使用 header <stdlib.h>。
為你的任務
是的,我最終會做的。基本上包含浮點數的陣列
那么您可以使用下面演示程式中顯示的方法
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
size_t split( const char *s, const char *delim, double **a )
{
*a = NULL;
size_t n = 0;
for ( const char *p = s; p = strspn( p, delim ), *p != '\0'; )
{
n;
p = strcspn( p, delim );
}
if ( n != 0 && ( *a = malloc( n * sizeof( double ) ) ) != NULL )
{
char *endptr;
for ( size_t i = 0; i < n; i )
{
( *a )[i] = strtod( s, &endptr );
s = endptr;
}
}
return n;
}
int main( void )
{
char *s= "1.77 1.65 1.56 5.555 6.1";
double *a;
size_t n = split( s, " \t", &a );
if ( a != NULL )
{
for ( size_t i = 0; i < n; i )
{
printf( "%.3f ", a[i] );
}
putchar( '\n' );
}
free( a );
}
程式輸出為
1.770 1.650 1.560 5.555 6.100
實際上,該函式可能更復雜,因為您需要檢查轉換為 double 是否順利。
uj5u.com熱心網友回復:
您的代碼中有多個錯誤。
您沒有初始化f但訪問f[0].
您為 10 個單人分配記憶體,char但不為函式中的指標分配記憶體。
整體方法也被打破了。
你可以這樣嘗試:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#define MAX_LEN 100
void pp(char *arr,char *delimiter,char ***a)
{
// TODO: Handle NULL pointers.
int i=0;
// TODO: Calculate number of strings using arr and delimiter...
int num = 10;
*a=malloc((num 1) * sizeof(**a));
for (int k = 0; k < num; k )
{
(*a)[k] = malloc( 1 length of string to copy) ;
strcpy((*a)[k], <string to copy>);
}
(*a)[num] = NULL; // indicate end of array.
}
int main(int argc,void **argv)
{
char *arr="1.77 1.65 1.56 5.555 6.1";
char **f;
pp(arr, " ", &f);
int i = 0;
while (f[i] != NULL)
{
printf("string #%d: %s\n", i, f[i]);
i ;
}
}
您還應該考慮一種如何將找到的子字串的數量報告給呼叫者的方法。在示例中,我添加了一個額外的指標NULL來終止陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/493764.html
